Bug Summary

File:build/source/clang/lib/Sema/SemaType.cpp
Warning:line 954, 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-16/lib/clang/16.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -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 _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-16/lib/clang/16.0.0/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/= -source-date-epoch 1668078801 -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/= -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-2022-11-10-135928-647445-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 <bitset>
44
45using namespace clang;
46
47enum TypeDiagSelector {
48 TDS_Function,
49 TDS_Pointer,
50 TDS_ObjCObjOrBlock
51};
52
53/// isOmittedBlockReturnType - Return true if this declarator is missing a
54/// return type because this is a omitted return type on a block literal.
55static bool isOmittedBlockReturnType(const Declarator &D) {
56 if (D.getContext() != DeclaratorContext::BlockLiteral ||
57 D.getDeclSpec().hasTypeSpecifier())
58 return false;
59
60 if (D.getNumTypeObjects() == 0)
61 return true; // ^{ ... }
62
63 if (D.getNumTypeObjects() == 1 &&
64 D.getTypeObject(0).Kind == DeclaratorChunk::Function)
65 return true; // ^(int X, float Y) { ... }
66
67 return false;
68}
69
70/// diagnoseBadTypeAttribute - Diagnoses a type attribute which
71/// doesn't apply to the given type.
72static void diagnoseBadTypeAttribute(Sema &S, const ParsedAttr &attr,
73 QualType type) {
74 TypeDiagSelector WhichType;
75 bool useExpansionLoc = true;
76 switch (attr.getKind()) {
77 case ParsedAttr::AT_ObjCGC:
78 WhichType = TDS_Pointer;
79 break;
80 case ParsedAttr::AT_ObjCOwnership:
81 WhichType = TDS_ObjCObjOrBlock;
82 break;
83 default:
84 // Assume everything else was a function attribute.
85 WhichType = TDS_Function;
86 useExpansionLoc = false;
87 break;
88 }
89
90 SourceLocation loc = attr.getLoc();
91 StringRef name = attr.getAttrName()->getName();
92
93 // The GC attributes are usually written with macros; special-case them.
94 IdentifierInfo *II = attr.isArgIdent(0) ? attr.getArgAsIdent(0)->Ident
95 : nullptr;
96 if (useExpansionLoc && loc.isMacroID() && II) {
97 if (II->isStr("strong")) {
98 if (S.findMacroSpelling(loc, "__strong")) name = "__strong";
99 } else if (II->isStr("weak")) {
100 if (S.findMacroSpelling(loc, "__weak")) name = "__weak";
101 }
102 }
103
104 S.Diag(loc, diag::warn_type_attribute_wrong_type) << name << WhichType
105 << type;
106}
107
108// objc_gc applies to Objective-C pointers or, otherwise, to the
109// smallest available pointer type (i.e. 'void*' in 'void**').
110#define OBJC_POINTER_TYPE_ATTRS_CASELISTcase ParsedAttr::AT_ObjCGC: case ParsedAttr::AT_ObjCOwnership \
111 case ParsedAttr::AT_ObjCGC: \
112 case ParsedAttr::AT_ObjCOwnership
113
114// Calling convention attributes.
115#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
\
116 case ParsedAttr::AT_CDecl: \
117 case ParsedAttr::AT_FastCall: \
118 case ParsedAttr::AT_StdCall: \
119 case ParsedAttr::AT_ThisCall: \
120 case ParsedAttr::AT_RegCall: \
121 case ParsedAttr::AT_Pascal: \
122 case ParsedAttr::AT_SwiftCall: \
123 case ParsedAttr::AT_SwiftAsyncCall: \
124 case ParsedAttr::AT_VectorCall: \
125 case ParsedAttr::AT_AArch64VectorPcs: \
126 case ParsedAttr::AT_AArch64SVEPcs: \
127 case ParsedAttr::AT_AMDGPUKernelCall: \
128 case ParsedAttr::AT_MSABI: \
129 case ParsedAttr::AT_SysVABI: \
130 case ParsedAttr::AT_Pcs: \
131 case ParsedAttr::AT_IntelOclBicc: \
132 case ParsedAttr::AT_PreserveMost: \
133 case ParsedAttr::AT_PreserveAll
134
135// Function type attributes.
136#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
\
137 case ParsedAttr::AT_NSReturnsRetained: \
138 case ParsedAttr::AT_NoReturn: \
139 case ParsedAttr::AT_Regparm: \
140 case ParsedAttr::AT_CmseNSCall: \
141 case ParsedAttr::AT_AnyX86NoCallerSavedRegisters: \
142 case ParsedAttr::AT_AnyX86NoCfCheck: \
143 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
144
145// Microsoft-specific type qualifiers.
146#define MS_TYPE_ATTRS_CASELISTcase ParsedAttr::AT_Ptr32: case ParsedAttr::AT_Ptr64: case ParsedAttr
::AT_SPtr: case ParsedAttr::AT_UPtr
\
147 case ParsedAttr::AT_Ptr32: \
148 case ParsedAttr::AT_Ptr64: \
149 case ParsedAttr::AT_SPtr: \
150 case ParsedAttr::AT_UPtr
151
152// Nullability qualifiers.
153#define NULLABILITY_TYPE_ATTRS_CASELISTcase ParsedAttr::AT_TypeNonNull: case ParsedAttr::AT_TypeNullable
: case ParsedAttr::AT_TypeNullableResult: case ParsedAttr::AT_TypeNullUnspecified
\
154 case ParsedAttr::AT_TypeNonNull: \
155 case ParsedAttr::AT_TypeNullable: \
156 case ParsedAttr::AT_TypeNullableResult: \
157 case ParsedAttr::AT_TypeNullUnspecified
158
159namespace {
160 /// An object which stores processing state for the entire
161 /// GetTypeForDeclarator process.
162 class TypeProcessingState {
163 Sema &sema;
164
165 /// The declarator being processed.
166 Declarator &declarator;
167
168 /// The index of the declarator chunk we're currently processing.
169 /// May be the total number of valid chunks, indicating the
170 /// DeclSpec.
171 unsigned chunkIndex;
172
173 /// The original set of attributes on the DeclSpec.
174 SmallVector<ParsedAttr *, 2> savedAttrs;
175
176 /// A list of attributes to diagnose the uselessness of when the
177 /// processing is complete.
178 SmallVector<ParsedAttr *, 2> ignoredTypeAttrs;
179
180 /// Attributes corresponding to AttributedTypeLocs that we have not yet
181 /// populated.
182 // FIXME: The two-phase mechanism by which we construct Types and fill
183 // their TypeLocs makes it hard to correctly assign these. We keep the
184 // attributes in creation order as an attempt to make them line up
185 // properly.
186 using TypeAttrPair = std::pair<const AttributedType*, const Attr*>;
187 SmallVector<TypeAttrPair, 8> AttrsForTypes;
188 bool AttrsForTypesSorted = true;
189
190 /// MacroQualifiedTypes mapping to macro expansion locations that will be
191 /// stored in a MacroQualifiedTypeLoc.
192 llvm::DenseMap<const MacroQualifiedType *, SourceLocation> LocsForMacros;
193
194 /// Flag to indicate we parsed a noderef attribute. This is used for
195 /// validating that noderef was used on a pointer or array.
196 bool parsedNoDeref;
197
198 public:
199 TypeProcessingState(Sema &sema, Declarator &declarator)
200 : sema(sema), declarator(declarator),
201 chunkIndex(declarator.getNumTypeObjects()), parsedNoDeref(false) {}
202
203 Sema &getSema() const {
204 return sema;
205 }
206
207 Declarator &getDeclarator() const {
208 return declarator;
209 }
210
211 bool isProcessingDeclSpec() const {
212 return chunkIndex == declarator.getNumTypeObjects();
213 }
214
215 unsigned getCurrentChunkIndex() const {
216 return chunkIndex;
217 }
218
219 void setCurrentChunkIndex(unsigned idx) {
220 assert(idx <= declarator.getNumTypeObjects())(static_cast <bool> (idx <= declarator.getNumTypeObjects
()) ? void (0) : __assert_fail ("idx <= declarator.getNumTypeObjects()"
, "clang/lib/Sema/SemaType.cpp", 220, __extension__ __PRETTY_FUNCTION__
))
;
221 chunkIndex = idx;
222 }
223
224 ParsedAttributesView &getCurrentAttributes() const {
225 if (isProcessingDeclSpec())
226 return getMutableDeclSpec().getAttributes();
227 return declarator.getTypeObject(chunkIndex).getAttrs();
228 }
229
230 /// Save the current set of attributes on the DeclSpec.
231 void saveDeclSpecAttrs() {
232 // Don't try to save them multiple times.
233 if (!savedAttrs.empty())
234 return;
235
236 DeclSpec &spec = getMutableDeclSpec();
237 llvm::append_range(savedAttrs,
238 llvm::make_pointer_range(spec.getAttributes()));
239 }
240
241 /// Record that we had nowhere to put the given type attribute.
242 /// We will diagnose such attributes later.
243 void addIgnoredTypeAttr(ParsedAttr &attr) {
244 ignoredTypeAttrs.push_back(&attr);
245 }
246
247 /// Diagnose all the ignored type attributes, given that the
248 /// declarator worked out to the given type.
249 void diagnoseIgnoredTypeAttrs(QualType type) const {
250 for (auto *Attr : ignoredTypeAttrs)
251 diagnoseBadTypeAttribute(getSema(), *Attr, type);
252 }
253
254 /// Get an attributed type for the given attribute, and remember the Attr
255 /// object so that we can attach it to the AttributedTypeLoc.
256 QualType getAttributedType(Attr *A, QualType ModifiedType,
257 QualType EquivType) {
258 QualType T =
259 sema.Context.getAttributedType(A->getKind(), ModifiedType, EquivType);
260 AttrsForTypes.push_back({cast<AttributedType>(T.getTypePtr()), A});
261 AttrsForTypesSorted = false;
262 return T;
263 }
264
265 /// Get a BTFTagAttributed type for the btf_type_tag attribute.
266 QualType getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr,
267 QualType WrappedType) {
268 return sema.Context.getBTFTagAttributedType(BTFAttr, WrappedType);
269 }
270
271 /// Completely replace the \c auto in \p TypeWithAuto by
272 /// \p Replacement. Also replace \p TypeWithAuto in \c TypeAttrPair if
273 /// necessary.
274 QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement) {
275 QualType T = sema.ReplaceAutoType(TypeWithAuto, Replacement);
276 if (auto *AttrTy = TypeWithAuto->getAs<AttributedType>()) {
277 // Attributed type still should be an attributed type after replacement.
278 auto *NewAttrTy = cast<AttributedType>(T.getTypePtr());
279 for (TypeAttrPair &A : AttrsForTypes) {
280 if (A.first == AttrTy)
281 A.first = NewAttrTy;
282 }
283 AttrsForTypesSorted = false;
284 }
285 return T;
286 }
287
288 /// Extract and remove the Attr* for a given attributed type.
289 const Attr *takeAttrForAttributedType(const AttributedType *AT) {
290 if (!AttrsForTypesSorted) {
291 llvm::stable_sort(AttrsForTypes, llvm::less_first());
292 AttrsForTypesSorted = true;
293 }
294
295 // FIXME: This is quadratic if we have lots of reuses of the same
296 // attributed type.
297 for (auto It = std::partition_point(
298 AttrsForTypes.begin(), AttrsForTypes.end(),
299 [=](const TypeAttrPair &A) { return A.first < AT; });
300 It != AttrsForTypes.end() && It->first == AT; ++It) {
301 if (It->second) {
302 const Attr *Result = It->second;
303 It->second = nullptr;
304 return Result;
305 }
306 }
307
308 llvm_unreachable("no Attr* for AttributedType*")::llvm::llvm_unreachable_internal("no Attr* for AttributedType*"
, "clang/lib/Sema/SemaType.cpp", 308)
;
309 }
310
311 SourceLocation
312 getExpansionLocForMacroQualifiedType(const MacroQualifiedType *MQT) const {
313 auto FoundLoc = LocsForMacros.find(MQT);
314 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", 315, __extension__ __PRETTY_FUNCTION__
))
315 "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", 315, __extension__ __PRETTY_FUNCTION__
))
;
316 return FoundLoc->second;
317 }
318
319 void setExpansionLocForMacroQualifiedType(const MacroQualifiedType *MQT,
320 SourceLocation Loc) {
321 LocsForMacros[MQT] = Loc;
322 }
323
324 void setParsedNoDeref(bool parsed) { parsedNoDeref = parsed; }
325
326 bool didParseNoDeref() const { return parsedNoDeref; }
327
328 ~TypeProcessingState() {
329 if (savedAttrs.empty())
330 return;
331
332 getMutableDeclSpec().getAttributes().clearListOnly();
333 for (ParsedAttr *AL : savedAttrs)
334 getMutableDeclSpec().getAttributes().addAtEnd(AL);
335 }
336
337 private:
338 DeclSpec &getMutableDeclSpec() const {
339 return const_cast<DeclSpec&>(declarator.getDeclSpec());
340 }
341 };
342} // end anonymous namespace
343
344static void moveAttrFromListToList(ParsedAttr &attr,
345 ParsedAttributesView &fromList,
346 ParsedAttributesView &toList) {
347 fromList.remove(&attr);
348 toList.addAtEnd(&attr);
349}
350
351/// The location of a type attribute.
352enum TypeAttrLocation {
353 /// The attribute is in the decl-specifier-seq.
354 TAL_DeclSpec,
355 /// The attribute is part of a DeclaratorChunk.
356 TAL_DeclChunk,
357 /// The attribute is immediately after the declaration's name.
358 TAL_DeclName
359};
360
361static void processTypeAttrs(TypeProcessingState &state, QualType &type,
362 TypeAttrLocation TAL,
363 const ParsedAttributesView &attrs);
364
365static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
366 QualType &type);
367
368static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &state,
369 ParsedAttr &attr, QualType &type);
370
371static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
372 QualType &type);
373
374static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
375 ParsedAttr &attr, QualType &type);
376
377static bool handleObjCPointerTypeAttr(TypeProcessingState &state,
378 ParsedAttr &attr, QualType &type) {
379 if (attr.getKind() == ParsedAttr::AT_ObjCGC)
380 return handleObjCGCTypeAttr(state, attr, type);
381 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", 381, __extension__ __PRETTY_FUNCTION__
))
;
382 return handleObjCOwnershipTypeAttr(state, attr, type);
383}
384
385/// Given the index of a declarator chunk, check whether that chunk
386/// directly specifies the return type of a function and, if so, find
387/// an appropriate place for it.
388///
389/// \param i - a notional index which the search will start
390/// immediately inside
391///
392/// \param onlyBlockPointers Whether we should only look into block
393/// pointer types (vs. all pointer types).
394static DeclaratorChunk *maybeMovePastReturnType(Declarator &declarator,
395 unsigned i,
396 bool onlyBlockPointers) {
397 assert(i <= declarator.getNumTypeObjects())(static_cast <bool> (i <= declarator.getNumTypeObjects
()) ? void (0) : __assert_fail ("i <= declarator.getNumTypeObjects()"
, "clang/lib/Sema/SemaType.cpp", 397, __extension__ __PRETTY_FUNCTION__
))
;
398
399 DeclaratorChunk *result = nullptr;
400
401 // First, look inwards past parens for a function declarator.
402 for (; i != 0; --i) {
403 DeclaratorChunk &fnChunk = declarator.getTypeObject(i-1);
404 switch (fnChunk.Kind) {
405 case DeclaratorChunk::Paren:
406 continue;
407
408 // If we find anything except a function, bail out.
409 case DeclaratorChunk::Pointer:
410 case DeclaratorChunk::BlockPointer:
411 case DeclaratorChunk::Array:
412 case DeclaratorChunk::Reference:
413 case DeclaratorChunk::MemberPointer:
414 case DeclaratorChunk::Pipe:
415 return result;
416
417 // If we do find a function declarator, scan inwards from that,
418 // looking for a (block-)pointer declarator.
419 case DeclaratorChunk::Function:
420 for (--i; i != 0; --i) {
421 DeclaratorChunk &ptrChunk = declarator.getTypeObject(i-1);
422 switch (ptrChunk.Kind) {
423 case DeclaratorChunk::Paren:
424 case DeclaratorChunk::Array:
425 case DeclaratorChunk::Function:
426 case DeclaratorChunk::Reference:
427 case DeclaratorChunk::Pipe:
428 continue;
429
430 case DeclaratorChunk::MemberPointer:
431 case DeclaratorChunk::Pointer:
432 if (onlyBlockPointers)
433 continue;
434
435 [[fallthrough]];
436
437 case DeclaratorChunk::BlockPointer:
438 result = &ptrChunk;
439 goto continue_outer;
440 }
441 llvm_unreachable("bad declarator chunk kind")::llvm::llvm_unreachable_internal("bad declarator chunk kind"
, "clang/lib/Sema/SemaType.cpp", 441)
;
442 }
443
444 // If we run out of declarators doing that, we're done.
445 return result;
446 }
447 llvm_unreachable("bad declarator chunk kind")::llvm::llvm_unreachable_internal("bad declarator chunk kind"
, "clang/lib/Sema/SemaType.cpp", 447)
;
448
449 // Okay, reconsider from our new point.
450 continue_outer: ;
451 }
452
453 // Ran out of chunks, bail out.
454 return result;
455}
456
457/// Given that an objc_gc attribute was written somewhere on a
458/// declaration *other* than on the declarator itself (for which, use
459/// distributeObjCPointerTypeAttrFromDeclarator), and given that it
460/// didn't apply in whatever position it was written in, try to move
461/// it to a more appropriate position.
462static void distributeObjCPointerTypeAttr(TypeProcessingState &state,
463 ParsedAttr &attr, QualType type) {
464 Declarator &declarator = state.getDeclarator();
465
466 // Move it to the outermost normal or block pointer declarator.
467 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
468 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
469 switch (chunk.Kind) {
470 case DeclaratorChunk::Pointer:
471 case DeclaratorChunk::BlockPointer: {
472 // But don't move an ARC ownership attribute to the return type
473 // of a block.
474 DeclaratorChunk *destChunk = nullptr;
475 if (state.isProcessingDeclSpec() &&
476 attr.getKind() == ParsedAttr::AT_ObjCOwnership)
477 destChunk = maybeMovePastReturnType(declarator, i - 1,
478 /*onlyBlockPointers=*/true);
479 if (!destChunk) destChunk = &chunk;
480
481 moveAttrFromListToList(attr, state.getCurrentAttributes(),
482 destChunk->getAttrs());
483 return;
484 }
485
486 case DeclaratorChunk::Paren:
487 case DeclaratorChunk::Array:
488 continue;
489
490 // We may be starting at the return type of a block.
491 case DeclaratorChunk::Function:
492 if (state.isProcessingDeclSpec() &&
493 attr.getKind() == ParsedAttr::AT_ObjCOwnership) {
494 if (DeclaratorChunk *dest = maybeMovePastReturnType(
495 declarator, i,
496 /*onlyBlockPointers=*/true)) {
497 moveAttrFromListToList(attr, state.getCurrentAttributes(),
498 dest->getAttrs());
499 return;
500 }
501 }
502 goto error;
503
504 // Don't walk through these.
505 case DeclaratorChunk::Reference:
506 case DeclaratorChunk::MemberPointer:
507 case DeclaratorChunk::Pipe:
508 goto error;
509 }
510 }
511 error:
512
513 diagnoseBadTypeAttribute(state.getSema(), attr, type);
514}
515
516/// Distribute an objc_gc type attribute that was written on the
517/// declarator.
518static void distributeObjCPointerTypeAttrFromDeclarator(
519 TypeProcessingState &state, ParsedAttr &attr, QualType &declSpecType) {
520 Declarator &declarator = state.getDeclarator();
521
522 // objc_gc goes on the innermost pointer to something that's not a
523 // pointer.
524 unsigned innermost = -1U;
525 bool considerDeclSpec = true;
526 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
527 DeclaratorChunk &chunk = declarator.getTypeObject(i);
528 switch (chunk.Kind) {
529 case DeclaratorChunk::Pointer:
530 case DeclaratorChunk::BlockPointer:
531 innermost = i;
532 continue;
533
534 case DeclaratorChunk::Reference:
535 case DeclaratorChunk::MemberPointer:
536 case DeclaratorChunk::Paren:
537 case DeclaratorChunk::Array:
538 case DeclaratorChunk::Pipe:
539 continue;
540
541 case DeclaratorChunk::Function:
542 considerDeclSpec = false;
543 goto done;
544 }
545 }
546 done:
547
548 // That might actually be the decl spec if we weren't blocked by
549 // anything in the declarator.
550 if (considerDeclSpec) {
551 if (handleObjCPointerTypeAttr(state, attr, declSpecType)) {
552 // Splice the attribute into the decl spec. Prevents the
553 // attribute from being applied multiple times and gives
554 // the source-location-filler something to work with.
555 state.saveDeclSpecAttrs();
556 declarator.getMutableDeclSpec().getAttributes().takeOneFrom(
557 declarator.getAttributes(), &attr);
558 return;
559 }
560 }
561
562 // Otherwise, if we found an appropriate chunk, splice the attribute
563 // into it.
564 if (innermost != -1U) {
565 moveAttrFromListToList(attr, declarator.getAttributes(),
566 declarator.getTypeObject(innermost).getAttrs());
567 return;
568 }
569
570 // Otherwise, diagnose when we're done building the type.
571 declarator.getAttributes().remove(&attr);
572 state.addIgnoredTypeAttr(attr);
573}
574
575/// A function type attribute was written somewhere in a declaration
576/// *other* than on the declarator itself or in the decl spec. Given
577/// that it didn't apply in whatever position it was written in, try
578/// to move it to a more appropriate position.
579static void distributeFunctionTypeAttr(TypeProcessingState &state,
580 ParsedAttr &attr, QualType type) {
581 Declarator &declarator = state.getDeclarator();
582
583 // Try to push the attribute from the return type of a function to
584 // the function itself.
585 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
586 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
587 switch (chunk.Kind) {
588 case DeclaratorChunk::Function:
589 moveAttrFromListToList(attr, state.getCurrentAttributes(),
590 chunk.getAttrs());
591 return;
592
593 case DeclaratorChunk::Paren:
594 case DeclaratorChunk::Pointer:
595 case DeclaratorChunk::BlockPointer:
596 case DeclaratorChunk::Array:
597 case DeclaratorChunk::Reference:
598 case DeclaratorChunk::MemberPointer:
599 case DeclaratorChunk::Pipe:
600 continue;
601 }
602 }
603
604 diagnoseBadTypeAttribute(state.getSema(), attr, type);
605}
606
607/// Try to distribute a function type attribute to the innermost
608/// function chunk or type. Returns true if the attribute was
609/// distributed, false if no location was found.
610static bool distributeFunctionTypeAttrToInnermost(
611 TypeProcessingState &state, ParsedAttr &attr,
612 ParsedAttributesView &attrList, QualType &declSpecType) {
613 Declarator &declarator = state.getDeclarator();
614
615 // Put it on the innermost function chunk, if there is one.
616 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
617 DeclaratorChunk &chunk = declarator.getTypeObject(i);
618 if (chunk.Kind != DeclaratorChunk::Function) continue;
619
620 moveAttrFromListToList(attr, attrList, chunk.getAttrs());
621 return true;
622 }
623
624 return handleFunctionTypeAttr(state, attr, declSpecType);
625}
626
627/// A function type attribute was written in the decl spec. Try to
628/// apply it somewhere.
629static void distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state,
630 ParsedAttr &attr,
631 QualType &declSpecType) {
632 state.saveDeclSpecAttrs();
633
634 // Try to distribute to the innermost.
635 if (distributeFunctionTypeAttrToInnermost(
636 state, attr, state.getCurrentAttributes(), declSpecType))
637 return;
638
639 // If that failed, diagnose the bad attribute when the declarator is
640 // fully built.
641 state.addIgnoredTypeAttr(attr);
642}
643
644/// A function type attribute was written on the declarator or declaration.
645/// Try to apply it somewhere.
646/// `Attrs` is the attribute list containing the declaration (either of the
647/// declarator or the declaration).
648static void distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state,
649 ParsedAttr &attr,
650 QualType &declSpecType) {
651 Declarator &declarator = state.getDeclarator();
652
653 // Try to distribute to the innermost.
654 if (distributeFunctionTypeAttrToInnermost(
655 state, attr, declarator.getAttributes(), declSpecType))
656 return;
657
658 // If that failed, diagnose the bad attribute when the declarator is
659 // fully built.
660 declarator.getAttributes().remove(&attr);
661 state.addIgnoredTypeAttr(attr);
662}
663
664/// Given that there are attributes written on the declarator or declaration
665/// itself, try to distribute any type attributes to the appropriate
666/// declarator chunk.
667///
668/// These are attributes like the following:
669/// int f ATTR;
670/// int (f ATTR)();
671/// but not necessarily this:
672/// int f() ATTR;
673///
674/// `Attrs` is the attribute list containing the declaration (either of the
675/// declarator or the declaration).
676static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state,
677 QualType &declSpecType) {
678 // The called functions in this loop actually remove things from the current
679 // list, so iterating over the existing list isn't possible. Instead, make a
680 // non-owning copy and iterate over that.
681 ParsedAttributesView AttrsCopy{state.getDeclarator().getAttributes()};
682 for (ParsedAttr &attr : AttrsCopy) {
683 // Do not distribute [[]] attributes. They have strict rules for what
684 // they appertain to.
685 if (attr.isStandardAttributeSyntax())
686 continue;
687
688 switch (attr.getKind()) {
689 OBJC_POINTER_TYPE_ATTRS_CASELISTcase ParsedAttr::AT_ObjCGC: case ParsedAttr::AT_ObjCOwnership:
690 distributeObjCPointerTypeAttrFromDeclarator(state, attr, declSpecType);
691 break;
692
693 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
:
694 distributeFunctionTypeAttrFromDeclarator(state, attr, declSpecType);
695 break;
696
697 MS_TYPE_ATTRS_CASELISTcase ParsedAttr::AT_Ptr32: case ParsedAttr::AT_Ptr64: case ParsedAttr
::AT_SPtr: case ParsedAttr::AT_UPtr
:
698 // Microsoft type attributes cannot go after the declarator-id.
699 continue;
700
701 NULLABILITY_TYPE_ATTRS_CASELISTcase ParsedAttr::AT_TypeNonNull: case ParsedAttr::AT_TypeNullable
: case ParsedAttr::AT_TypeNullableResult: case ParsedAttr::AT_TypeNullUnspecified
:
702 // Nullability specifiers cannot go after the declarator-id.
703
704 // Objective-C __kindof does not get distributed.
705 case ParsedAttr::AT_ObjCKindOf:
706 continue;
707
708 default:
709 break;
710 }
711 }
712}
713
714/// Add a synthetic '()' to a block-literal declarator if it is
715/// required, given the return type.
716static void maybeSynthesizeBlockSignature(TypeProcessingState &state,
717 QualType declSpecType) {
718 Declarator &declarator = state.getDeclarator();
719
720 // First, check whether the declarator would produce a function,
721 // i.e. whether the innermost semantic chunk is a function.
722 if (declarator.isFunctionDeclarator()) {
723 // If so, make that declarator a prototyped declarator.
724 declarator.getFunctionTypeInfo().hasPrototype = true;
725 return;
726 }
727
728 // If there are any type objects, the type as written won't name a
729 // function, regardless of the decl spec type. This is because a
730 // block signature declarator is always an abstract-declarator, and
731 // abstract-declarators can't just be parentheses chunks. Therefore
732 // we need to build a function chunk unless there are no type
733 // objects and the decl spec type is a function.
734 if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType())
735 return;
736
737 // Note that there *are* cases with invalid declarators where
738 // declarators consist solely of parentheses. In general, these
739 // occur only in failed efforts to make function declarators, so
740 // faking up the function chunk is still the right thing to do.
741
742 // Otherwise, we need to fake up a function declarator.
743 SourceLocation loc = declarator.getBeginLoc();
744
745 // ...and *prepend* it to the declarator.
746 SourceLocation NoLoc;
747 declarator.AddInnermostTypeInfo(DeclaratorChunk::getFunction(
748 /*HasProto=*/true,
749 /*IsAmbiguous=*/false,
750 /*LParenLoc=*/NoLoc,
751 /*ArgInfo=*/nullptr,
752 /*NumParams=*/0,
753 /*EllipsisLoc=*/NoLoc,
754 /*RParenLoc=*/NoLoc,
755 /*RefQualifierIsLvalueRef=*/true,
756 /*RefQualifierLoc=*/NoLoc,
757 /*MutableLoc=*/NoLoc, EST_None,
758 /*ESpecRange=*/SourceRange(),
759 /*Exceptions=*/nullptr,
760 /*ExceptionRanges=*/nullptr,
761 /*NumExceptions=*/0,
762 /*NoexceptExpr=*/nullptr,
763 /*ExceptionSpecTokens=*/nullptr,
764 /*DeclsInPrototype=*/None, loc, loc, declarator));
765
766 // For consistency, make sure the state still has us as processing
767 // the decl spec.
768 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", 768, __extension__ __PRETTY_FUNCTION__
))
;
769 state.setCurrentChunkIndex(declarator.getNumTypeObjects());
770}
771
772static void diagnoseAndRemoveTypeQualifiers(Sema &S, const DeclSpec &DS,
773 unsigned &TypeQuals,
774 QualType TypeSoFar,
775 unsigned RemoveTQs,
776 unsigned DiagID) {
777 // If this occurs outside a template instantiation, warn the user about
778 // it; they probably didn't mean to specify a redundant qualifier.
779 typedef std::pair<DeclSpec::TQ, SourceLocation> QualLoc;
780 for (QualLoc Qual : {QualLoc(DeclSpec::TQ_const, DS.getConstSpecLoc()),
781 QualLoc(DeclSpec::TQ_restrict, DS.getRestrictSpecLoc()),
782 QualLoc(DeclSpec::TQ_volatile, DS.getVolatileSpecLoc()),
783 QualLoc(DeclSpec::TQ_atomic, DS.getAtomicSpecLoc())}) {
784 if (!(RemoveTQs & Qual.first))
785 continue;
786
787 if (!S.inTemplateInstantiation()) {
788 if (TypeQuals & Qual.first)
789 S.Diag(Qual.second, DiagID)
790 << DeclSpec::getSpecifierName(Qual.first) << TypeSoFar
791 << FixItHint::CreateRemoval(Qual.second);
792 }
793
794 TypeQuals &= ~Qual.first;
795 }
796}
797
798/// Return true if this is omitted block return type. Also check type
799/// attributes and type qualifiers when returning true.
800static bool checkOmittedBlockReturnType(Sema &S, Declarator &declarator,
801 QualType Result) {
802 if (!isOmittedBlockReturnType(declarator))
803 return false;
804
805 // Warn if we see type attributes for omitted return type on a block literal.
806 SmallVector<ParsedAttr *, 2> ToBeRemoved;
807 for (ParsedAttr &AL : declarator.getMutableDeclSpec().getAttributes()) {
808 if (AL.isInvalid() || !AL.isTypeAttr())
809 continue;
810 S.Diag(AL.getLoc(),
811 diag::warn_block_literal_attributes_on_omitted_return_type)
812 << AL;
813 ToBeRemoved.push_back(&AL);
814 }
815 // Remove bad attributes from the list.
816 for (ParsedAttr *AL : ToBeRemoved)
817 declarator.getMutableDeclSpec().getAttributes().remove(AL);
818
819 // Warn if we see type qualifiers for omitted return type on a block literal.
820 const DeclSpec &DS = declarator.getDeclSpec();
821 unsigned TypeQuals = DS.getTypeQualifiers();
822 diagnoseAndRemoveTypeQualifiers(S, DS, TypeQuals, Result, (unsigned)-1,
823 diag::warn_block_literal_qualifiers_on_omitted_return_type);
824 declarator.getMutableDeclSpec().ClearTypeQualifiers();
825
826 return true;
827}
828
829/// Apply Objective-C type arguments to the given type.
830static QualType applyObjCTypeArgs(Sema &S, SourceLocation loc, QualType type,
831 ArrayRef<TypeSourceInfo *> typeArgs,
832 SourceRange typeArgsRange, bool failOnError,
833 bool rebuilding) {
834 // We can only apply type arguments to an Objective-C class type.
835 const auto *objcObjectType = type->getAs<ObjCObjectType>();
9
Assuming the object is a 'const class clang::ObjCObjectType *'
836 if (!objcObjectType || !objcObjectType->getInterface()) {
10
Assuming 'objcObjectType' is non-null
11
Assuming the condition is false
12
Taking false branch
837 S.Diag(loc, diag::err_objc_type_args_non_class)
838 << type
839 << typeArgsRange;
840
841 if (failOnError)
842 return QualType();
843 return type;
844 }
845
846 // The class type must be parameterized.
847 ObjCInterfaceDecl *objcClass = objcObjectType->getInterface();
848 ObjCTypeParamList *typeParams = objcClass->getTypeParamList();
849 if (!typeParams) {
13
Assuming 'typeParams' is non-null
14
Taking false branch
850 S.Diag(loc, diag::err_objc_type_args_non_parameterized_class)
851 << objcClass->getDeclName()
852 << FixItHint::CreateRemoval(typeArgsRange);
853
854 if (failOnError)
855 return QualType();
856
857 return type;
858 }
859
860 // The type must not already be specialized.
861 if (objcObjectType->isSpecialized()) {
15
Assuming the condition is false
16
Taking false branch
862 S.Diag(loc, diag::err_objc_type_args_specialized_class)
863 << type
864 << FixItHint::CreateRemoval(typeArgsRange);
865
866 if (failOnError)
867 return QualType();
868
869 return type;
870 }
871
872 // Check the type arguments.
873 SmallVector<QualType, 4> finalTypeArgs;
874 unsigned numTypeParams = typeParams->size();
875 bool anyPackExpansions = false;
876 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
877 TypeSourceInfo *typeArgInfo = typeArgs[i];
878 QualType typeArg = typeArgInfo->getType();
879
880 // Type arguments cannot have explicit qualifiers or nullability.
881 // We ignore indirect sources of these, e.g. behind typedefs or
882 // template arguments.
883 if (TypeLoc qual = typeArgInfo->getTypeLoc().findExplicitQualifierLoc()) {
19
Assuming the condition is false
20
Taking false branch
884 bool diagnosed = false;
885 SourceRange rangeToRemove;
886 if (auto attr = qual.getAs<AttributedTypeLoc>()) {
887 rangeToRemove = attr.getLocalSourceRange();
888 if (attr.getTypePtr()->getImmediateNullability()) {
889 typeArg = attr.getTypePtr()->getModifiedType();
890 S.Diag(attr.getBeginLoc(),
891 diag::err_objc_type_arg_explicit_nullability)
892 << typeArg << FixItHint::CreateRemoval(rangeToRemove);
893 diagnosed = true;
894 }
895 }
896
897 // When rebuilding, qualifiers might have gotten here through a
898 // final substitution.
899 if (!rebuilding && !diagnosed) {
900 S.Diag(qual.getBeginLoc(), diag::err_objc_type_arg_qualified)
901 << typeArg << typeArg.getQualifiers().getAsString()
902 << FixItHint::CreateRemoval(rangeToRemove);
903 }
904 }
905
906 // Remove qualifiers even if they're non-local.
907 typeArg = typeArg.getUnqualifiedType();
908
909 finalTypeArgs.push_back(typeArg);
910
911 if (typeArg->getAs<PackExpansionType>())
21
Assuming the object is not a 'const class clang::PackExpansionType *'
22
Taking false branch
912 anyPackExpansions = true;
913
914 // Find the corresponding type parameter, if there is one.
915 ObjCTypeParamDecl *typeParam = nullptr;
916 if (!anyPackExpansions
22.1
'anyPackExpansions' is false
) {
23
Taking true branch
917 if (i < numTypeParams) {
24
Assuming 'i' is < 'numTypeParams'
25
Taking true branch
918 typeParam = typeParams->begin()[i];
919 } else {
920 // Too many arguments.
921 S.Diag(loc, diag::err_objc_type_args_wrong_arity)
922 << false
923 << objcClass->getDeclName()
924 << (unsigned)typeArgs.size()
925 << numTypeParams;
926 S.Diag(objcClass->getLocation(), diag::note_previous_decl)
927 << objcClass;
928
929 if (failOnError)
930 return QualType();
931
932 return type;
933 }
934 }
935
936 // Objective-C object pointer types must be substitutable for the bounds.
937 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
938 // If we don't have a type parameter to match against, assume
939 // everything is fine. There was a prior pack expansion that
940 // means we won't be able to match anything.
941 if (!typeParam) {
29
Assuming 'typeParam' is non-null
30
Taking false branch
942 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", 942, __extension__ __PRETTY_FUNCTION__
))
;
943 continue;
944 }
945
946 // Retrieve the bound.
947 QualType bound = typeParam->getUnderlyingType();
948 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
949
950 // Determine whether the type argument is substitutable for the bound.
951 if (typeArgObjC->isObjCIdType()) {
33
Taking true branch
952 // When the type argument is 'id', the only acceptable type
953 // parameter bound is 'id'.
954 if (boundObjC->isObjCIdType())
34
Called C++ object pointer is null
955 continue;
956 } else if (S.Context.canAssignObjCInterfaces(boundObjC, typeArgObjC)) {
957 // Otherwise, we follow the assignability rules.
958 continue;
959 }
960
961 // Diagnose the mismatch.
962 S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(),
963 diag::err_objc_type_arg_does_not_match_bound)
964 << typeArg << bound << typeParam->getDeclName();
965 S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here)
966 << typeParam->getDeclName();
967
968 if (failOnError)
969 return QualType();
970
971 return type;
972 }
973
974 // Block pointer types are permitted for unqualified 'id' bounds.
975 if (typeArg->isBlockPointerType()) {
976 // If we don't have a type parameter to match against, assume
977 // everything is fine. There was a prior pack expansion that
978 // means we won't be able to match anything.
979 if (!typeParam) {
980 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", 980, __extension__ __PRETTY_FUNCTION__
))
;
981 continue;
982 }
983
984 // Retrieve the bound.
985 QualType bound = typeParam->getUnderlyingType();
986 if (bound->isBlockCompatibleObjCPointerType(S.Context))
987 continue;
988
989 // Diagnose the mismatch.
990 S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(),
991 diag::err_objc_type_arg_does_not_match_bound)
992 << typeArg << bound << typeParam->getDeclName();
993 S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here)
994 << typeParam->getDeclName();
995
996 if (failOnError)
997 return QualType();
998
999 return type;
1000 }
1001
1002 // Dependent types will be checked at instantiation time.
1003 if (typeArg->isDependentType()) {
1004 continue;
1005 }
1006
1007 // Diagnose non-id-compatible type arguments.
1008 S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(),
1009 diag::err_objc_type_arg_not_id_compatible)
1010 << typeArg << typeArgInfo->getTypeLoc().getSourceRange();
1011
1012 if (failOnError)
1013 return QualType();
1014
1015 return type;
1016 }
1017
1018 // Make sure we didn't have the wrong number of arguments.
1019 if (!anyPackExpansions && finalTypeArgs.size() != numTypeParams) {
1020 S.Diag(loc, diag::err_objc_type_args_wrong_arity)
1021 << (typeArgs.size() < typeParams->size())
1022 << objcClass->getDeclName()
1023 << (unsigned)finalTypeArgs.size()
1024 << (unsigned)numTypeParams;
1025 S.Diag(objcClass->getLocation(), diag::note_previous_decl)
1026 << objcClass;
1027
1028 if (failOnError)
1029 return QualType();
1030
1031 return type;
1032 }
1033
1034 // Success. Form the specialized type.
1035 return S.Context.getObjCObjectType(type, finalTypeArgs, { }, false);
1036}
1037
1038QualType Sema::BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
1039 SourceLocation ProtocolLAngleLoc,
1040 ArrayRef<ObjCProtocolDecl *> Protocols,
1041 ArrayRef<SourceLocation> ProtocolLocs,
1042 SourceLocation ProtocolRAngleLoc,
1043 bool FailOnError) {
1044 QualType Result = QualType(Decl->getTypeForDecl(), 0);
1045 if (!Protocols.empty()) {
1046 bool HasError;
1047 Result = Context.applyObjCProtocolQualifiers(Result, Protocols,
1048 HasError);
1049 if (HasError) {
1050 Diag(SourceLocation(), diag::err_invalid_protocol_qualifiers)
1051 << SourceRange(ProtocolLAngleLoc, ProtocolRAngleLoc);
1052 if (FailOnError) Result = QualType();
1053 }
1054 if (FailOnError && Result.isNull())
1055 return QualType();
1056 }
1057
1058 return Result;
1059}
1060
1061QualType Sema::BuildObjCObjectType(
1062 QualType BaseType, SourceLocation Loc, SourceLocation TypeArgsLAngleLoc,
1063 ArrayRef<TypeSourceInfo *> TypeArgs, SourceLocation TypeArgsRAngleLoc,
1064 SourceLocation ProtocolLAngleLoc, ArrayRef<ObjCProtocolDecl *> Protocols,
1065 ArrayRef<SourceLocation> ProtocolLocs, SourceLocation ProtocolRAngleLoc,
1066 bool FailOnError, bool Rebuilding) {
1067 QualType Result = BaseType;
1068 if (!TypeArgs.empty()) {
6
Assuming the condition is true
7
Taking true branch
1069 Result =
1070 applyObjCTypeArgs(*this, Loc, Result, TypeArgs,
8
Calling 'applyObjCTypeArgs'
1071 SourceRange(TypeArgsLAngleLoc, TypeArgsRAngleLoc),
1072 FailOnError, Rebuilding);
1073 if (FailOnError && Result.isNull())
1074 return QualType();
1075 }
1076
1077 if (!Protocols.empty()) {
1078 bool HasError;
1079 Result = Context.applyObjCProtocolQualifiers(Result, Protocols,
1080 HasError);
1081 if (HasError) {
1082 Diag(Loc, diag::err_invalid_protocol_qualifiers)
1083 << SourceRange(ProtocolLAngleLoc, ProtocolRAngleLoc);
1084 if (FailOnError) Result = QualType();
1085 }
1086 if (FailOnError && Result.isNull())
1087 return QualType();
1088 }
1089
1090 return Result;
1091}
1092
1093TypeResult Sema::actOnObjCProtocolQualifierType(
1094 SourceLocation lAngleLoc,
1095 ArrayRef<Decl *> protocols,
1096 ArrayRef<SourceLocation> protocolLocs,
1097 SourceLocation rAngleLoc) {
1098 // Form id<protocol-list>.
1099 QualType Result = Context.getObjCObjectType(
1100 Context.ObjCBuiltinIdTy, { },
1101 llvm::makeArrayRef(
1102 (ObjCProtocolDecl * const *)protocols.data(),
1103 protocols.size()),
1104 false);
1105 Result = Context.getObjCObjectPointerType(Result);
1106
1107 TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result);
1108 TypeLoc ResultTL = ResultTInfo->getTypeLoc();
1109
1110 auto ObjCObjectPointerTL = ResultTL.castAs<ObjCObjectPointerTypeLoc>();
1111 ObjCObjectPointerTL.setStarLoc(SourceLocation()); // implicit
1112
1113 auto ObjCObjectTL = ObjCObjectPointerTL.getPointeeLoc()
1114 .castAs<ObjCObjectTypeLoc>();
1115 ObjCObjectTL.setHasBaseTypeAsWritten(false);
1116 ObjCObjectTL.getBaseLoc().initialize(Context, SourceLocation());
1117
1118 // No type arguments.
1119 ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation());
1120 ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation());
1121
1122 // Fill in protocol qualifiers.
1123 ObjCObjectTL.setProtocolLAngleLoc(lAngleLoc);
1124 ObjCObjectTL.setProtocolRAngleLoc(rAngleLoc);
1125 for (unsigned i = 0, n = protocols.size(); i != n; ++i)
1126 ObjCObjectTL.setProtocolLoc(i, protocolLocs[i]);
1127
1128 // We're done. Return the completed type to the parser.
1129 return CreateParsedType(Result, ResultTInfo);
1130}
1131
1132TypeResult Sema::actOnObjCTypeArgsAndProtocolQualifiers(
1133 Scope *S,
1134 SourceLocation Loc,
1135 ParsedType BaseType,
1136 SourceLocation TypeArgsLAngleLoc,
1137 ArrayRef<ParsedType> TypeArgs,
1138 SourceLocation TypeArgsRAngleLoc,
1139 SourceLocation ProtocolLAngleLoc,
1140 ArrayRef<Decl *> Protocols,
1141 ArrayRef<SourceLocation> ProtocolLocs,
1142 SourceLocation ProtocolRAngleLoc) {
1143 TypeSourceInfo *BaseTypeInfo = nullptr;
1144 QualType T = GetTypeFromParser(BaseType, &BaseTypeInfo);
1145 if (T.isNull())
1
Taking false branch
1146 return true;
1147
1148 // Handle missing type-source info.
1149 if (!BaseTypeInfo
1.1
'BaseTypeInfo' is null
)
2
Taking true branch
1150 BaseTypeInfo = Context.getTrivialTypeSourceInfo(T, Loc);
1151
1152 // Extract type arguments.
1153 SmallVector<TypeSourceInfo *, 4> ActualTypeArgInfos;
1154 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 1167
1155 TypeSourceInfo *TypeArgInfo = nullptr;
1156 QualType TypeArg = GetTypeFromParser(TypeArgs[i], &TypeArgInfo);
1157 if (TypeArg.isNull()) {
1158 ActualTypeArgInfos.clear();
1159 break;
1160 }
1161
1162 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", 1162, __extension__ __PRETTY_FUNCTION__
))
;
1163 ActualTypeArgInfos.push_back(TypeArgInfo);
1164 }
1165
1166 // Build the object type.
1167 QualType Result = BuildObjCObjectType(
5
Calling 'Sema::BuildObjCObjectType'
1168 T, BaseTypeInfo->getTypeLoc().getSourceRange().getBegin(),
1169 TypeArgsLAngleLoc, ActualTypeArgInfos, TypeArgsRAngleLoc,
1170 ProtocolLAngleLoc,
1171 llvm::makeArrayRef((ObjCProtocolDecl *const *)Protocols.data(),
1172 Protocols.size()),
1173 ProtocolLocs, ProtocolRAngleLoc,
1174 /*FailOnError=*/false,
1175 /*Rebuilding=*/false);
1176
1177 if (Result == T)
1178 return BaseType;
1179
1180 // Create source information for this type.
1181 TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result);
1182 TypeLoc ResultTL = ResultTInfo->getTypeLoc();
1183
1184 // For id<Proto1, Proto2> or Class<Proto1, Proto2>, we'll have an
1185 // object pointer type. Fill in source information for it.
1186 if (auto ObjCObjectPointerTL = ResultTL.getAs<ObjCObjectPointerTypeLoc>()) {
1187 // The '*' is implicit.
1188 ObjCObjectPointerTL.setStarLoc(SourceLocation());
1189 ResultTL = ObjCObjectPointerTL.getPointeeLoc();
1190 }
1191
1192 if (auto OTPTL = ResultTL.getAs<ObjCTypeParamTypeLoc>()) {
1193 // Protocol qualifier information.
1194 if (OTPTL.getNumProtocols() > 0) {
1195 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", 1195, __extension__ __PRETTY_FUNCTION__
))
;
1196 OTPTL.setProtocolLAngleLoc(ProtocolLAngleLoc);
1197 OTPTL.setProtocolRAngleLoc(ProtocolRAngleLoc);
1198 for (unsigned i = 0, n = Protocols.size(); i != n; ++i)
1199 OTPTL.setProtocolLoc(i, ProtocolLocs[i]);
1200 }
1201
1202 // We're done. Return the completed type to the parser.
1203 return CreateParsedType(Result, ResultTInfo);
1204 }
1205
1206 auto ObjCObjectTL = ResultTL.castAs<ObjCObjectTypeLoc>();
1207
1208 // Type argument information.
1209 if (ObjCObjectTL.getNumTypeArgs() > 0) {
1210 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", 1210, __extension__ __PRETTY_FUNCTION__
))
;
1211 ObjCObjectTL.setTypeArgsLAngleLoc(TypeArgsLAngleLoc);
1212 ObjCObjectTL.setTypeArgsRAngleLoc(TypeArgsRAngleLoc);
1213 for (unsigned i = 0, n = ActualTypeArgInfos.size(); i != n; ++i)
1214 ObjCObjectTL.setTypeArgTInfo(i, ActualTypeArgInfos[i]);
1215 } else {
1216 ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation());
1217 ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation());
1218 }
1219
1220 // Protocol qualifier information.
1221 if (ObjCObjectTL.getNumProtocols() > 0) {
1222 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", 1222, __extension__ __PRETTY_FUNCTION__
))
;
1223 ObjCObjectTL.setProtocolLAngleLoc(ProtocolLAngleLoc);
1224 ObjCObjectTL.setProtocolRAngleLoc(ProtocolRAngleLoc);
1225 for (unsigned i = 0, n = Protocols.size(); i != n; ++i)
1226 ObjCObjectTL.setProtocolLoc(i, ProtocolLocs[i]);
1227 } else {
1228 ObjCObjectTL.setProtocolLAngleLoc(SourceLocation());
1229 ObjCObjectTL.setProtocolRAngleLoc(SourceLocation());
1230 }
1231
1232 // Base type.
1233 ObjCObjectTL.setHasBaseTypeAsWritten(true);
1234 if (ObjCObjectTL.getType() == T)
1235 ObjCObjectTL.getBaseLoc().initializeFullCopy(BaseTypeInfo->getTypeLoc());
1236 else
1237 ObjCObjectTL.getBaseLoc().initialize(Context, Loc);
1238
1239 // We're done. Return the completed type to the parser.
1240 return CreateParsedType(Result, ResultTInfo);
1241}
1242
1243static OpenCLAccessAttr::Spelling
1244getImageAccess(const ParsedAttributesView &Attrs) {
1245 for (const ParsedAttr &AL : Attrs)
1246 if (AL.getKind() == ParsedAttr::AT_OpenCLAccess)
1247 return static_cast<OpenCLAccessAttr::Spelling>(AL.getSemanticSpelling());
1248 return OpenCLAccessAttr::Keyword_read_only;
1249}
1250
1251static UnaryTransformType::UTTKind
1252TSTToUnaryTransformType(DeclSpec::TST SwitchTST) {
1253 switch (SwitchTST) {
1254#define TRANSFORM_TYPE_TRAIT_DEF(Enum, Trait) \
1255 case TST_##Trait: \
1256 return UnaryTransformType::Enum;
1257#include "clang/Basic/TransformTypeTraits.def"
1258 default:
1259 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", 1259)
;
1260 }
1261}
1262
1263/// Convert the specified declspec to the appropriate type
1264/// object.
1265/// \param state Specifies the declarator containing the declaration specifier
1266/// to be converted, along with other associated processing state.
1267/// \returns The type described by the declaration specifiers. This function
1268/// never returns null.
1269static QualType ConvertDeclSpecToType(TypeProcessingState &state) {
1270 // FIXME: Should move the logic from DeclSpec::Finish to here for validity
1271 // checking.
1272
1273 Sema &S = state.getSema();
1274 Declarator &declarator = state.getDeclarator();
1275 DeclSpec &DS = declarator.getMutableDeclSpec();
1276 SourceLocation DeclLoc = declarator.getIdentifierLoc();
1277 if (DeclLoc.isInvalid())
1278 DeclLoc = DS.getBeginLoc();
1279
1280 ASTContext &Context = S.Context;
1281
1282 QualType Result;
1283 switch (DS.getTypeSpecType()) {
1284 case DeclSpec::TST_void:
1285 Result = Context.VoidTy;
1286 break;
1287 case DeclSpec::TST_char:
1288 if (DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified)
1289 Result = Context.CharTy;
1290 else if (DS.getTypeSpecSign() == TypeSpecifierSign::Signed)
1291 Result = Context.SignedCharTy;
1292 else {
1293 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", 1294, __extension__ __PRETTY_FUNCTION__
))
1294 "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", 1294, __extension__ __PRETTY_FUNCTION__
))
;
1295 Result = Context.UnsignedCharTy;
1296 }
1297 break;
1298 case DeclSpec::TST_wchar:
1299 if (DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified)
1300 Result = Context.WCharTy;
1301 else if (DS.getTypeSpecSign() == TypeSpecifierSign::Signed) {
1302 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_wchar_t_sign_spec)
1303 << DS.getSpecifierName(DS.getTypeSpecType(),
1304 Context.getPrintingPolicy());
1305 Result = Context.getSignedWCharType();
1306 } else {
1307 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", 1308, __extension__ __PRETTY_FUNCTION__
))
1308 "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", 1308, __extension__ __PRETTY_FUNCTION__
))
;
1309 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_wchar_t_sign_spec)
1310 << DS.getSpecifierName(DS.getTypeSpecType(),
1311 Context.getPrintingPolicy());
1312 Result = Context.getUnsignedWCharType();
1313 }
1314 break;
1315 case DeclSpec::TST_char8:
1316 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", 1317, __extension__ __PRETTY_FUNCTION__
))
1317 "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", 1317, __extension__ __PRETTY_FUNCTION__
))
;
1318 Result = Context.Char8Ty;
1319 break;
1320 case DeclSpec::TST_char16:
1321 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", 1322, __extension__ __PRETTY_FUNCTION__
))
1322 "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", 1322, __extension__ __PRETTY_FUNCTION__
))
;
1323 Result = Context.Char16Ty;
1324 break;
1325 case DeclSpec::TST_char32:
1326 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", 1327, __extension__ __PRETTY_FUNCTION__
))
1327 "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", 1327, __extension__ __PRETTY_FUNCTION__
))
;
1328 Result = Context.Char32Ty;
1329 break;
1330 case DeclSpec::TST_unspecified:
1331 // If this is a missing declspec in a block literal return context, then it
1332 // is inferred from the return statements inside the block.
1333 // The declspec is always missing in a lambda expr context; it is either
1334 // specified with a trailing return type or inferred.
1335 if (S.getLangOpts().CPlusPlus14 &&
1336 declarator.getContext() == DeclaratorContext::LambdaExpr) {
1337 // In C++1y, a lambda's implicit return type is 'auto'.
1338 Result = Context.getAutoDeductType();
1339 break;
1340 } else if (declarator.getContext() == DeclaratorContext::LambdaExpr ||
1341 checkOmittedBlockReturnType(S, declarator,
1342 Context.DependentTy)) {
1343 Result = Context.DependentTy;
1344 break;
1345 }
1346
1347 // Unspecified typespec defaults to int in C90. However, the C90 grammar
1348 // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
1349 // type-qualifier, or storage-class-specifier. If not, emit an extwarn.
1350 // Note that the one exception to this is function definitions, which are
1351 // allowed to be completely missing a declspec. This is handled in the
1352 // parser already though by it pretending to have seen an 'int' in this
1353 // case.
1354 if (S.getLangOpts().isImplicitIntRequired()) {
1355 S.Diag(DeclLoc, diag::warn_missing_type_specifier)
1356 << DS.getSourceRange()
1357 << FixItHint::CreateInsertion(DS.getBeginLoc(), "int");
1358 } else if (!DS.hasTypeSpecifier()) {
1359 // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says:
1360 // "At least one type specifier shall be given in the declaration
1361 // specifiers in each declaration, and in the specifier-qualifier list in
1362 // each struct declaration and type name."
1363 if (!S.getLangOpts().isImplicitIntAllowed() && !DS.isTypeSpecPipe()) {
1364 S.Diag(DeclLoc, diag::err_missing_type_specifier)
1365 << DS.getSourceRange();
1366
1367 // When this occurs, often something is very broken with the value
1368 // being declared, poison it as invalid so we don't get chains of
1369 // errors.
1370 declarator.setInvalidType(true);
1371 } else if (S.getLangOpts().getOpenCLCompatibleVersion() >= 200 &&
1372 DS.isTypeSpecPipe()) {
1373 S.Diag(DeclLoc, diag::err_missing_actual_pipe_type)
1374 << DS.getSourceRange();
1375 declarator.setInvalidType(true);
1376 } else {
1377 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", 1378, __extension__ __PRETTY_FUNCTION__
))
1378 "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", 1378, __extension__ __PRETTY_FUNCTION__
))
;
1379 S.Diag(DeclLoc, diag::ext_missing_type_specifier)
1380 << DS.getSourceRange()
1381 << FixItHint::CreateInsertion(DS.getBeginLoc(), "int");
1382 }
1383 }
1384
1385 [[fallthrough]];
1386 case DeclSpec::TST_int: {
1387 if (DS.getTypeSpecSign() != TypeSpecifierSign::Unsigned) {
1388 switch (DS.getTypeSpecWidth()) {
1389 case TypeSpecifierWidth::Unspecified:
1390 Result = Context.IntTy;
1391 break;
1392 case TypeSpecifierWidth::Short:
1393 Result = Context.ShortTy;
1394 break;
1395 case TypeSpecifierWidth::Long:
1396 Result = Context.LongTy;
1397 break;
1398 case TypeSpecifierWidth::LongLong:
1399 Result = Context.LongLongTy;
1400
1401 // 'long long' is a C99 or C++11 feature.
1402 if (!S.getLangOpts().C99) {
1403 if (S.getLangOpts().CPlusPlus)
1404 S.Diag(DS.getTypeSpecWidthLoc(),
1405 S.getLangOpts().CPlusPlus11 ?
1406 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
1407 else
1408 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
1409 }
1410 break;
1411 }
1412 } else {
1413 switch (DS.getTypeSpecWidth()) {
1414 case TypeSpecifierWidth::Unspecified:
1415 Result = Context.UnsignedIntTy;
1416 break;
1417 case TypeSpecifierWidth::Short:
1418 Result = Context.UnsignedShortTy;
1419 break;
1420 case TypeSpecifierWidth::Long:
1421 Result = Context.UnsignedLongTy;
1422 break;
1423 case TypeSpecifierWidth::LongLong:
1424 Result = Context.UnsignedLongLongTy;
1425
1426 // 'long long' is a C99 or C++11 feature.
1427 if (!S.getLangOpts().C99) {
1428 if (S.getLangOpts().CPlusPlus)
1429 S.Diag(DS.getTypeSpecWidthLoc(),
1430 S.getLangOpts().CPlusPlus11 ?
1431 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
1432 else
1433 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
1434 }
1435 break;
1436 }
1437 }
1438 break;
1439 }
1440 case DeclSpec::TST_bitint: {
1441 if (!S.Context.getTargetInfo().hasBitIntType())
1442 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) << "_BitInt";
1443 Result =
1444 S.BuildBitIntType(DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned,
1445 DS.getRepAsExpr(), DS.getBeginLoc());
1446 if (Result.isNull()) {
1447 Result = Context.IntTy;
1448 declarator.setInvalidType(true);
1449 }
1450 break;
1451 }
1452 case DeclSpec::TST_accum: {
1453 switch (DS.getTypeSpecWidth()) {
1454 case TypeSpecifierWidth::Short:
1455 Result = Context.ShortAccumTy;
1456 break;
1457 case TypeSpecifierWidth::Unspecified:
1458 Result = Context.AccumTy;
1459 break;
1460 case TypeSpecifierWidth::Long:
1461 Result = Context.LongAccumTy;
1462 break;
1463 case TypeSpecifierWidth::LongLong:
1464 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", 1464)
;
1465 }
1466
1467 if (DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned)
1468 Result = Context.getCorrespondingUnsignedType(Result);
1469
1470 if (DS.isTypeSpecSat())
1471 Result = Context.getCorrespondingSaturatedType(Result);
1472
1473 break;
1474 }
1475 case DeclSpec::TST_fract: {
1476 switch (DS.getTypeSpecWidth()) {
1477 case TypeSpecifierWidth::Short:
1478 Result = Context.ShortFractTy;
1479 break;
1480 case TypeSpecifierWidth::Unspecified:
1481 Result = Context.FractTy;
1482 break;
1483 case TypeSpecifierWidth::Long:
1484 Result = Context.LongFractTy;
1485 break;
1486 case TypeSpecifierWidth::LongLong:
1487 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", 1487)
;
1488 }
1489
1490 if (DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned)
1491 Result = Context.getCorrespondingUnsignedType(Result);
1492
1493 if (DS.isTypeSpecSat())
1494 Result = Context.getCorrespondingSaturatedType(Result);
1495
1496 break;
1497 }
1498 case DeclSpec::TST_int128:
1499 if (!S.Context.getTargetInfo().hasInt128Type() &&
1500 !(S.getLangOpts().SYCLIsDevice || S.getLangOpts().CUDAIsDevice ||
1501 (S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsDevice)))
1502 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1503 << "__int128";
1504 if (DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned)
1505 Result = Context.UnsignedInt128Ty;
1506 else
1507 Result = Context.Int128Ty;
1508 break;
1509 case DeclSpec::TST_float16:
1510 // CUDA host and device may have different _Float16 support, therefore
1511 // do not diagnose _Float16 usage to avoid false alarm.
1512 // ToDo: more precise diagnostics for CUDA.
1513 if (!S.Context.getTargetInfo().hasFloat16Type() && !S.getLangOpts().CUDA &&
1514 !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsDevice))
1515 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1516 << "_Float16";
1517 Result = Context.Float16Ty;
1518 break;
1519 case DeclSpec::TST_half: Result = Context.HalfTy; break;
1520 case DeclSpec::TST_BFloat16:
1521 if (!S.Context.getTargetInfo().hasBFloat16Type())
1522 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1523 << "__bf16";
1524 Result = Context.BFloat16Ty;
1525 break;
1526 case DeclSpec::TST_float: Result = Context.FloatTy; break;
1527 case DeclSpec::TST_double:
1528 if (DS.getTypeSpecWidth() == TypeSpecifierWidth::Long)
1529 Result = Context.LongDoubleTy;
1530 else
1531 Result = Context.DoubleTy;
1532 if (S.getLangOpts().OpenCL) {
1533 if (!S.getOpenCLOptions().isSupported("cl_khr_fp64", S.getLangOpts()))
1534 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_opencl_requires_extension)
1535 << 0 << Result
1536 << (S.getLangOpts().getOpenCLCompatibleVersion() == 300
1537 ? "cl_khr_fp64 and __opencl_c_fp64"
1538 : "cl_khr_fp64");
1539 else if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp64", S.getLangOpts()))
1540 S.Diag(DS.getTypeSpecTypeLoc(), diag::ext_opencl_double_without_pragma);
1541 }
1542 break;
1543 case DeclSpec::TST_float128:
1544 if (!S.Context.getTargetInfo().hasFloat128Type() &&
1545 !S.getLangOpts().SYCLIsDevice &&
1546 !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsDevice))
1547 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1548 << "__float128";
1549 Result = Context.Float128Ty;
1550 break;
1551 case DeclSpec::TST_ibm128:
1552 if (!S.Context.getTargetInfo().hasIbm128Type() &&
1553 !S.getLangOpts().SYCLIsDevice &&
1554 !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsDevice))
1555 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) << "__ibm128";
1556 Result = Context.Ibm128Ty;
1557 break;
1558 case DeclSpec::TST_bool:
1559 Result = Context.BoolTy; // _Bool or bool
1560 break;
1561 case DeclSpec::TST_decimal32: // _Decimal32
1562 case DeclSpec::TST_decimal64: // _Decimal64
1563 case DeclSpec::TST_decimal128: // _Decimal128
1564 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
1565 Result = Context.IntTy;
1566 declarator.setInvalidType(true);
1567 break;
1568 case DeclSpec::TST_class:
1569 case DeclSpec::TST_enum:
1570 case DeclSpec::TST_union:
1571 case DeclSpec::TST_struct:
1572 case DeclSpec::TST_interface: {
1573 TagDecl *D = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl());
1574 if (!D) {
1575 // This can happen in C++ with ambiguous lookups.
1576 Result = Context.IntTy;
1577 declarator.setInvalidType(true);
1578 break;
1579 }
1580
1581 // If the type is deprecated or unavailable, diagnose it.
1582 S.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeNameLoc());
1583
1584 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", 1587, __extension__ __PRETTY_FUNCTION__
))
1585 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", 1587, __extension__ __PRETTY_FUNCTION__
))
1586 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", 1587, __extension__ __PRETTY_FUNCTION__
))
1587 "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", 1587, __extension__ __PRETTY_FUNCTION__
))
;
1588
1589 // TypeQuals handled by caller.
1590 Result = Context.getTypeDeclType(D);
1591
1592 // In both C and C++, make an ElaboratedType.
1593 ElaboratedTypeKeyword Keyword
1594 = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType());
1595 Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result,
1596 DS.isTypeSpecOwned() ? D : nullptr);
1597 break;
1598 }
1599 case DeclSpec::TST_typename: {
1600 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", 1603, __extension__ __PRETTY_FUNCTION__
))
1601 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", 1603, __extension__ __PRETTY_FUNCTION__
))
1602 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", 1603, __extension__ __PRETTY_FUNCTION__
))
1603 "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", 1603, __extension__ __PRETTY_FUNCTION__
))
;
1604 Result = S.GetTypeFromParser(DS.getRepAsType());
1605 if (Result.isNull()) {
1606 declarator.setInvalidType(true);
1607 }
1608
1609 // TypeQuals handled by caller.
1610 break;
1611 }
1612 case DeclSpec::TST_typeof_unqualType:
1613 case DeclSpec::TST_typeofType:
1614 // FIXME: Preserve type source info.
1615 Result = S.GetTypeFromParser(DS.getRepAsType());
1616 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", 1616, __extension__ __PRETTY_FUNCTION__
))
;
1617 if (!Result->isDependentType())
1618 if (const TagType *TT = Result->getAs<TagType>())
1619 S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc());
1620 // TypeQuals handled by caller.
1621 Result = Context.getTypeOfType(
1622 Result, DS.getTypeSpecType() == DeclSpec::TST_typeof_unqualType
1623 ? TypeOfKind::Unqualified
1624 : TypeOfKind::Qualified);
1625 break;
1626 case DeclSpec::TST_typeof_unqualExpr:
1627 case DeclSpec::TST_typeofExpr: {
1628 Expr *E = DS.getRepAsExpr();
1629 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", 1629, __extension__ __PRETTY_FUNCTION__
))
;
1630 // TypeQuals handled by caller.
1631 Result = S.BuildTypeofExprType(E, DS.getTypeSpecType() ==
1632 DeclSpec::TST_typeof_unqualExpr
1633 ? TypeOfKind::Unqualified
1634 : TypeOfKind::Qualified);
1635 if (Result.isNull()) {
1636 Result = Context.IntTy;
1637 declarator.setInvalidType(true);
1638 }
1639 break;
1640 }
1641 case DeclSpec::TST_decltype: {
1642 Expr *E = DS.getRepAsExpr();
1643 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", 1643, __extension__ __PRETTY_FUNCTION__
))
;
1644 // TypeQuals handled by caller.
1645 Result = S.BuildDecltypeType(E);
1646 if (Result.isNull()) {
1647 Result = Context.IntTy;
1648 declarator.setInvalidType(true);
1649 }
1650 break;
1651 }
1652#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
1653#include "clang/Basic/TransformTypeTraits.def"
1654 Result = S.GetTypeFromParser(DS.getRepAsType());
1655 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", 1655, __extension__ __PRETTY_FUNCTION__
))
;
1656 Result = S.BuildUnaryTransformType(
1657 Result, TSTToUnaryTransformType(DS.getTypeSpecType()),
1658 DS.getTypeSpecTypeLoc());
1659 if (Result.isNull()) {
1660 Result = Context.IntTy;
1661 declarator.setInvalidType(true);
1662 }
1663 break;
1664
1665 case DeclSpec::TST_auto:
1666 case DeclSpec::TST_decltype_auto: {
1667 auto AutoKW = DS.getTypeSpecType() == DeclSpec::TST_decltype_auto
1668 ? AutoTypeKeyword::DecltypeAuto
1669 : AutoTypeKeyword::Auto;
1670
1671 ConceptDecl *TypeConstraintConcept = nullptr;
1672 llvm::SmallVector<TemplateArgument, 8> TemplateArgs;
1673 if (DS.isConstrainedAuto()) {
1674 if (TemplateIdAnnotation *TemplateId = DS.getRepAsTemplateId()) {
1675 TypeConstraintConcept =
1676 cast<ConceptDecl>(TemplateId->Template.get().getAsTemplateDecl());
1677 TemplateArgumentListInfo TemplateArgsInfo;
1678 TemplateArgsInfo.setLAngleLoc(TemplateId->LAngleLoc);
1679 TemplateArgsInfo.setRAngleLoc(TemplateId->RAngleLoc);
1680 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1681 TemplateId->NumArgs);
1682 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo);
1683 for (const auto &ArgLoc : TemplateArgsInfo.arguments())
1684 TemplateArgs.push_back(ArgLoc.getArgument());
1685 } else {
1686 declarator.setInvalidType(true);
1687 }
1688 }
1689 Result = S.Context.getAutoType(QualType(), AutoKW,
1690 /*IsDependent*/ false, /*IsPack=*/false,
1691 TypeConstraintConcept, TemplateArgs);
1692 break;
1693 }
1694
1695 case DeclSpec::TST_auto_type:
1696 Result = Context.getAutoType(QualType(), AutoTypeKeyword::GNUAutoType, false);
1697 break;
1698
1699 case DeclSpec::TST_unknown_anytype:
1700 Result = Context.UnknownAnyTy;
1701 break;
1702
1703 case DeclSpec::TST_atomic:
1704 Result = S.GetTypeFromParser(DS.getRepAsType());
1705 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", 1705, __extension__ __PRETTY_FUNCTION__
))
;
1706 Result = S.BuildAtomicType(Result, DS.getTypeSpecTypeLoc());
1707 if (Result.isNull()) {
1708 Result = Context.IntTy;
1709 declarator.setInvalidType(true);
1710 }
1711 break;
1712
1713#define GENERIC_IMAGE_TYPE(ImgType, Id) \
1714 case DeclSpec::TST_##ImgType##_t: \
1715 switch (getImageAccess(DS.getAttributes())) { \
1716 case OpenCLAccessAttr::Keyword_write_only: \
1717 Result = Context.Id##WOTy; \
1718 break; \
1719 case OpenCLAccessAttr::Keyword_read_write: \
1720 Result = Context.Id##RWTy; \
1721 break; \
1722 case OpenCLAccessAttr::Keyword_read_only: \
1723 Result = Context.Id##ROTy; \
1724 break; \
1725 case OpenCLAccessAttr::SpellingNotCalculated: \
1726 llvm_unreachable("Spelling not yet calculated")::llvm::llvm_unreachable_internal("Spelling not yet calculated"
, "clang/lib/Sema/SemaType.cpp", 1726)
; \
1727 } \
1728 break;
1729#include "clang/Basic/OpenCLImageTypes.def"
1730
1731 case DeclSpec::TST_error:
1732 Result = Context.IntTy;
1733 declarator.setInvalidType(true);
1734 break;
1735 }
1736
1737 // FIXME: we want resulting declarations to be marked invalid, but claiming
1738 // the type is invalid is too strong - e.g. it causes ActOnTypeName to return
1739 // a null type.
1740 if (Result->containsErrors())
1741 declarator.setInvalidType();
1742
1743 if (S.getLangOpts().OpenCL) {
1744 const auto &OpenCLOptions = S.getOpenCLOptions();
1745 bool IsOpenCLC30Compatible =
1746 S.getLangOpts().getOpenCLCompatibleVersion() == 300;
1747 // OpenCL C v3.0 s6.3.3 - OpenCL image types require __opencl_c_images
1748 // support.
1749 // OpenCL C v3.0 s6.2.1 - OpenCL 3d image write types requires support
1750 // for OpenCL C 2.0, or OpenCL C 3.0 or newer and the
1751 // __opencl_c_3d_image_writes feature. OpenCL C v3.0 API s4.2 - For devices
1752 // that support OpenCL 3.0, cl_khr_3d_image_writes must be returned when and
1753 // only when the optional feature is supported
1754 if ((Result->isImageType() || Result->isSamplerT()) &&
1755 (IsOpenCLC30Compatible &&
1756 !OpenCLOptions.isSupported("__opencl_c_images", S.getLangOpts()))) {
1757 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_opencl_requires_extension)
1758 << 0 << Result << "__opencl_c_images";
1759 declarator.setInvalidType();
1760 } else if (Result->isOCLImage3dWOType() &&
1761 !OpenCLOptions.isSupported("cl_khr_3d_image_writes",
1762 S.getLangOpts())) {
1763 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_opencl_requires_extension)
1764 << 0 << Result
1765 << (IsOpenCLC30Compatible
1766 ? "cl_khr_3d_image_writes and __opencl_c_3d_image_writes"
1767 : "cl_khr_3d_image_writes");
1768 declarator.setInvalidType();
1769 }
1770 }
1771
1772 bool IsFixedPointType = DS.getTypeSpecType() == DeclSpec::TST_accum ||
1773 DS.getTypeSpecType() == DeclSpec::TST_fract;
1774
1775 // Only fixed point types can be saturated
1776 if (DS.isTypeSpecSat() && !IsFixedPointType)
1777 S.Diag(DS.getTypeSpecSatLoc(), diag::err_invalid_saturation_spec)
1778 << DS.getSpecifierName(DS.getTypeSpecType(),
1779 Context.getPrintingPolicy());
1780
1781 // Handle complex types.
1782 if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
1783 if (S.getLangOpts().Freestanding)
1784 S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
1785 Result = Context.getComplexType(Result);
1786 } else if (DS.isTypeAltiVecVector()) {
1787 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result));
1788 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", 1788, __extension__ __PRETTY_FUNCTION__
))
;
1789 VectorType::VectorKind VecKind = VectorType::AltiVecVector;
1790 if (DS.isTypeAltiVecPixel())
1791 VecKind = VectorType::AltiVecPixel;
1792 else if (DS.isTypeAltiVecBool())
1793 VecKind = VectorType::AltiVecBool;
1794 Result = Context.getVectorType(Result, 128/typeSize, VecKind);
1795 }
1796
1797 // FIXME: Imaginary.
1798 if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary)
1799 S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported);
1800
1801 // Before we process any type attributes, synthesize a block literal
1802 // function declarator if necessary.
1803 if (declarator.getContext() == DeclaratorContext::BlockLiteral)
1804 maybeSynthesizeBlockSignature(state, Result);
1805
1806 // Apply any type attributes from the decl spec. This may cause the
1807 // list of type attributes to be temporarily saved while the type
1808 // attributes are pushed around.
1809 // pipe attributes will be handled later ( at GetFullTypeForDeclarator )
1810 if (!DS.isTypeSpecPipe()) {
1811 // We also apply declaration attributes that "slide" to the decl spec.
1812 // Ordering can be important for attributes. The decalaration attributes
1813 // come syntactically before the decl spec attributes, so we process them
1814 // in that order.
1815 ParsedAttributesView SlidingAttrs;
1816 for (ParsedAttr &AL : declarator.getDeclarationAttributes()) {
1817 if (AL.slidesFromDeclToDeclSpecLegacyBehavior()) {
1818 SlidingAttrs.addAtEnd(&AL);
1819
1820 // For standard syntax attributes, which would normally appertain to the
1821 // declaration here, suggest moving them to the type instead. But only
1822 // do this for our own vendor attributes; moving other vendors'
1823 // attributes might hurt portability.
1824 // There's one special case that we need to deal with here: The
1825 // `MatrixType` attribute may only be used in a typedef declaration. If
1826 // it's being used anywhere else, don't output the warning as
1827 // ProcessDeclAttributes() will output an error anyway.
1828 if (AL.isStandardAttributeSyntax() && AL.isClangScope() &&
1829 !(AL.getKind() == ParsedAttr::AT_MatrixType &&
1830 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)) {
1831 S.Diag(AL.getLoc(), diag::warn_type_attribute_deprecated_on_decl)
1832 << AL;
1833 }
1834 }
1835 }
1836 // During this call to processTypeAttrs(),
1837 // TypeProcessingState::getCurrentAttributes() will erroneously return a
1838 // reference to the DeclSpec attributes, rather than the declaration
1839 // attributes. However, this doesn't matter, as getCurrentAttributes()
1840 // is only called when distributing attributes from one attribute list
1841 // to another. Declaration attributes are always C++11 attributes, and these
1842 // are never distributed.
1843 processTypeAttrs(state, Result, TAL_DeclSpec, SlidingAttrs);
1844 processTypeAttrs(state, Result, TAL_DeclSpec, DS.getAttributes());
1845 }
1846
1847 // Apply const/volatile/restrict qualifiers to T.
1848 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
1849 // Warn about CV qualifiers on function types.
1850 // C99 6.7.3p8:
1851 // If the specification of a function type includes any type qualifiers,
1852 // the behavior is undefined.
1853 // C++11 [dcl.fct]p7:
1854 // The effect of a cv-qualifier-seq in a function declarator is not the
1855 // same as adding cv-qualification on top of the function type. In the
1856 // latter case, the cv-qualifiers are ignored.
1857 if (Result->isFunctionType()) {
1858 diagnoseAndRemoveTypeQualifiers(
1859 S, DS, TypeQuals, Result, DeclSpec::TQ_const | DeclSpec::TQ_volatile,
1860 S.getLangOpts().CPlusPlus
1861 ? diag::warn_typecheck_function_qualifiers_ignored
1862 : diag::warn_typecheck_function_qualifiers_unspecified);
1863 // No diagnostic for 'restrict' or '_Atomic' applied to a
1864 // function type; we'll diagnose those later, in BuildQualifiedType.
1865 }
1866
1867 // C++11 [dcl.ref]p1:
1868 // Cv-qualified references are ill-formed except when the
1869 // cv-qualifiers are introduced through the use of a typedef-name
1870 // or decltype-specifier, in which case the cv-qualifiers are ignored.
1871 //
1872 // There don't appear to be any other contexts in which a cv-qualified
1873 // reference type could be formed, so the 'ill-formed' clause here appears
1874 // to never happen.
1875 if (TypeQuals && Result->isReferenceType()) {
1876 diagnoseAndRemoveTypeQualifiers(
1877 S, DS, TypeQuals, Result,
1878 DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic,
1879 diag::warn_typecheck_reference_qualifiers);
1880 }
1881
1882 // C90 6.5.3 constraints: "The same type qualifier shall not appear more
1883 // than once in the same specifier-list or qualifier-list, either directly
1884 // or via one or more typedefs."
1885 if (!S.getLangOpts().C99 && !S.getLangOpts().CPlusPlus
1886 && TypeQuals & Result.getCVRQualifiers()) {
1887 if (TypeQuals & DeclSpec::TQ_const && Result.isConstQualified()) {
1888 S.Diag(DS.getConstSpecLoc(), diag::ext_duplicate_declspec)
1889 << "const";
1890 }
1891
1892 if (TypeQuals & DeclSpec::TQ_volatile && Result.isVolatileQualified()) {
1893 S.Diag(DS.getVolatileSpecLoc(), diag::ext_duplicate_declspec)
1894 << "volatile";
1895 }
1896
1897 // C90 doesn't have restrict nor _Atomic, so it doesn't force us to
1898 // produce a warning in this case.
1899 }
1900
1901 QualType Qualified = S.BuildQualifiedType(Result, DeclLoc, TypeQuals, &DS);
1902
1903 // If adding qualifiers fails, just use the unqualified type.
1904 if (Qualified.isNull())
1905 declarator.setInvalidType(true);
1906 else
1907 Result = Qualified;
1908 }
1909
1910 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", 1910, __extension__ __PRETTY_FUNCTION__
))
;
1911 return Result;
1912}
1913
1914static std::string getPrintableNameForEntity(DeclarationName Entity) {
1915 if (Entity)
1916 return Entity.getAsString();
1917
1918 return "type name";
1919}
1920
1921static bool isDependentOrGNUAutoType(QualType T) {
1922 if (T->isDependentType())
1923 return true;
1924
1925 const auto *AT = dyn_cast<AutoType>(T);
1926 return AT && AT->isGNUAutoType();
1927}
1928
1929QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1930 Qualifiers Qs, const DeclSpec *DS) {
1931 if (T.isNull())
1932 return QualType();
1933
1934 // Ignore any attempt to form a cv-qualified reference.
1935 if (T->isReferenceType()) {
1936 Qs.removeConst();
1937 Qs.removeVolatile();
1938 }
1939
1940 // Enforce C99 6.7.3p2: "Types other than pointer types derived from
1941 // object or incomplete types shall not be restrict-qualified."
1942 if (Qs.hasRestrict()) {
1943 unsigned DiagID = 0;
1944 QualType ProblemTy;
1945
1946 if (T->isAnyPointerType() || T->isReferenceType() ||
1947 T->isMemberPointerType()) {
1948 QualType EltTy;
1949 if (T->isObjCObjectPointerType())
1950 EltTy = T;
1951 else if (const MemberPointerType *PTy = T->getAs<MemberPointerType>())
1952 EltTy = PTy->getPointeeType();
1953 else
1954 EltTy = T->getPointeeType();
1955
1956 // If we have a pointer or reference, the pointee must have an object
1957 // incomplete type.
1958 if (!EltTy->isIncompleteOrObjectType()) {
1959 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1960 ProblemTy = EltTy;
1961 }
1962 } else if (!isDependentOrGNUAutoType(T)) {
1963 // For an __auto_type variable, we may not have seen the initializer yet
1964 // and so have no idea whether the underlying type is a pointer type or
1965 // not.
1966 DiagID = diag::err_typecheck_invalid_restrict_not_pointer;
1967 ProblemTy = T;
1968 }
1969
1970 if (DiagID) {
1971 Diag(DS ? DS->getRestrictSpecLoc() : Loc, DiagID) << ProblemTy;
1972 Qs.removeRestrict();
1973 }
1974 }
1975
1976 return Context.getQualifiedType(T, Qs);
1977}
1978
1979QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1980 unsigned CVRAU, const DeclSpec *DS) {
1981 if (T.isNull())
1982 return QualType();
1983
1984 // Ignore any attempt to form a cv-qualified reference.
1985 if (T->isReferenceType())
1986 CVRAU &=
1987 ~(DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic);
1988
1989 // Convert from DeclSpec::TQ to Qualifiers::TQ by just dropping TQ_atomic and
1990 // TQ_unaligned;
1991 unsigned CVR = CVRAU & ~(DeclSpec::TQ_atomic | DeclSpec::TQ_unaligned);
1992
1993 // C11 6.7.3/5:
1994 // If the same qualifier appears more than once in the same
1995 // specifier-qualifier-list, either directly or via one or more typedefs,
1996 // the behavior is the same as if it appeared only once.
1997 //
1998 // It's not specified what happens when the _Atomic qualifier is applied to
1999 // a type specified with the _Atomic specifier, but we assume that this
2000 // should be treated as if the _Atomic qualifier appeared multiple times.
2001 if (CVRAU & DeclSpec::TQ_atomic && !T->isAtomicType()) {
2002 // C11 6.7.3/5:
2003 // If other qualifiers appear along with the _Atomic qualifier in a
2004 // specifier-qualifier-list, the resulting type is the so-qualified
2005 // atomic type.
2006 //
2007 // Don't need to worry about array types here, since _Atomic can't be
2008 // applied to such types.
2009 SplitQualType Split = T.getSplitUnqualifiedType();
2010 T = BuildAtomicType(QualType(Split.Ty, 0),
2011 DS ? DS->getAtomicSpecLoc() : Loc);
2012 if (T.isNull())
2013 return T;
2014 Split.Quals.addCVRQualifiers(CVR);
2015 return BuildQualifiedType(T, Loc, Split.Quals);
2016 }
2017
2018 Qualifiers Q = Qualifiers::fromCVRMask(CVR);
2019 Q.setUnaligned(CVRAU & DeclSpec::TQ_unaligned);
2020 return BuildQualifiedType(T, Loc, Q, DS);
2021}
2022
2023/// Build a paren type including \p T.
2024QualType Sema::BuildParenType(QualType T) {
2025 return Context.getParenType(T);
2026}
2027
2028/// Given that we're building a pointer or reference to the given
2029static QualType inferARCLifetimeForPointee(Sema &S, QualType type,
2030 SourceLocation loc,
2031 bool isReference) {
2032 // Bail out if retention is unrequired or already specified.
2033 if (!type->isObjCLifetimeType() ||
2034 type.getObjCLifetime() != Qualifiers::OCL_None)
2035 return type;
2036
2037 Qualifiers::ObjCLifetime implicitLifetime = Qualifiers::OCL_None;
2038
2039 // If the object type is const-qualified, we can safely use
2040 // __unsafe_unretained. This is safe (because there are no read
2041 // barriers), and it'll be safe to coerce anything but __weak* to
2042 // the resulting type.
2043 if (type.isConstQualified()) {
2044 implicitLifetime = Qualifiers::OCL_ExplicitNone;
2045
2046 // Otherwise, check whether the static type does not require
2047 // retaining. This currently only triggers for Class (possibly
2048 // protocol-qualifed, and arrays thereof).
2049 } else if (type->isObjCARCImplicitlyUnretainedType()) {
2050 implicitLifetime = Qualifiers::OCL_ExplicitNone;
2051
2052 // If we are in an unevaluated context, like sizeof, skip adding a
2053 // qualification.
2054 } else if (S.isUnevaluatedContext()) {
2055 return type;
2056
2057 // If that failed, give an error and recover using __strong. __strong
2058 // is the option most likely to prevent spurious second-order diagnostics,
2059 // like when binding a reference to a field.
2060 } else {
2061 // These types can show up in private ivars in system headers, so
2062 // we need this to not be an error in those cases. Instead we
2063 // want to delay.
2064 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
2065 S.DelayedDiagnostics.add(
2066 sema::DelayedDiagnostic::makeForbiddenType(loc,
2067 diag::err_arc_indirect_no_ownership, type, isReference));
2068 } else {
2069 S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference;
2070 }
2071 implicitLifetime = Qualifiers::OCL_Strong;
2072 }
2073 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", 2073, __extension__ __PRETTY_FUNCTION__
))
;
2074
2075 Qualifiers qs;
2076 qs.addObjCLifetime(implicitLifetime);
2077 return S.Context.getQualifiedType(type, qs);
2078}
2079
2080static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){
2081 std::string Quals = FnTy->getMethodQuals().getAsString();
2082
2083 switch (FnTy->getRefQualifier()) {
2084 case RQ_None:
2085 break;
2086
2087 case RQ_LValue:
2088 if (!Quals.empty())
2089 Quals += ' ';
2090 Quals += '&';
2091 break;
2092
2093 case RQ_RValue:
2094 if (!Quals.empty())
2095 Quals += ' ';
2096 Quals += "&&";
2097 break;
2098 }
2099
2100 return Quals;
2101}
2102
2103namespace {
2104/// Kinds of declarator that cannot contain a qualified function type.
2105///
2106/// C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6:
2107/// a function type with a cv-qualifier or a ref-qualifier can only appear
2108/// at the topmost level of a type.
2109///
2110/// Parens and member pointers are permitted. We don't diagnose array and
2111/// function declarators, because they don't allow function types at all.
2112///
2113/// The values of this enum are used in diagnostics.
2114enum QualifiedFunctionKind { QFK_BlockPointer, QFK_Pointer, QFK_Reference };
2115} // end anonymous namespace
2116
2117/// Check whether the type T is a qualified function type, and if it is,
2118/// diagnose that it cannot be contained within the given kind of declarator.
2119static bool checkQualifiedFunction(Sema &S, QualType T, SourceLocation Loc,
2120 QualifiedFunctionKind QFK) {
2121 // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
2122 const FunctionProtoType *FPT = T->getAs<FunctionProtoType>();
2123 if (!FPT ||
2124 (FPT->getMethodQuals().empty() && FPT->getRefQualifier() == RQ_None))
2125 return false;
2126
2127 S.Diag(Loc, diag::err_compound_qualified_function_type)
2128 << QFK << isa<FunctionType>(T.IgnoreParens()) << T
2129 << getFunctionQualifiersAsString(FPT);
2130 return true;
2131}
2132
2133bool Sema::CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc) {
2134 const FunctionProtoType *FPT = T->getAs<FunctionProtoType>();
2135 if (!FPT ||
2136 (FPT->getMethodQuals().empty() && FPT->getRefQualifier() == RQ_None))
2137 return false;
2138
2139 Diag(Loc, diag::err_qualified_function_typeid)
2140 << T << getFunctionQualifiersAsString(FPT);
2141 return true;
2142}
2143
2144// Helper to deduce addr space of a pointee type in OpenCL mode.
2145static QualType deduceOpenCLPointeeAddrSpace(Sema &S, QualType PointeeType) {
2146 if (!PointeeType->isUndeducedAutoType() && !PointeeType->isDependentType() &&
2147 !PointeeType->isSamplerT() &&
2148 !PointeeType.hasAddressSpace())
2149 PointeeType = S.getASTContext().getAddrSpaceQualType(
2150 PointeeType, S.getASTContext().getDefaultOpenCLPointeeAddrSpace());
2151 return PointeeType;
2152}
2153
2154/// Build a pointer type.
2155///
2156/// \param T The type to which we'll be building a pointer.
2157///
2158/// \param Loc The location of the entity whose type involves this
2159/// pointer type or, if there is no such entity, the location of the
2160/// type that will have pointer type.
2161///
2162/// \param Entity The name of the entity that involves the pointer
2163/// type, if known.
2164///
2165/// \returns A suitable pointer type, if there are no
2166/// errors. Otherwise, returns a NULL type.
2167QualType Sema::BuildPointerType(QualType T,
2168 SourceLocation Loc, DeclarationName Entity) {
2169 if (T->isReferenceType()) {
2170 // C++ 8.3.2p4: There shall be no ... pointers to references ...
2171 Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
2172 << getPrintableNameForEntity(Entity) << T;
2173 return QualType();
2174 }
2175
2176 if (T->isFunctionType() && getLangOpts().OpenCL &&
2177 !getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
2178 getLangOpts())) {
2179 Diag(Loc, diag::err_opencl_function_pointer) << /*pointer*/ 0;
2180 return QualType();
2181 }
2182
2183 if (getLangOpts().HLSL && Loc.isValid()) {
2184 Diag(Loc, diag::err_hlsl_pointers_unsupported) << 0;
2185 return QualType();
2186 }
2187
2188 if (checkQualifiedFunction(*this, T, Loc, QFK_Pointer))
2189 return QualType();
2190
2191 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", 2191, __extension__ __PRETTY_FUNCTION__
))
;
2192
2193 // In ARC, it is forbidden to build pointers to unqualified pointers.
2194 if (getLangOpts().ObjCAutoRefCount)
2195 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false);
2196
2197 if (getLangOpts().OpenCL)
2198 T = deduceOpenCLPointeeAddrSpace(*this, T);
2199
2200 // Build the pointer type.
2201 return Context.getPointerType(T);
2202}
2203
2204/// Build a reference type.
2205///
2206/// \param T The type to which we'll be building a reference.
2207///
2208/// \param Loc The location of the entity whose type involves this
2209/// reference type or, if there is no such entity, the location of the
2210/// type that will have reference type.
2211///
2212/// \param Entity The name of the entity that involves the reference
2213/// type, if known.
2214///
2215/// \returns A suitable reference type, if there are no
2216/// errors. Otherwise, returns a NULL type.
2217QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue,
2218 SourceLocation Loc,
2219 DeclarationName Entity) {
2220 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", 2221, __extension__ __PRETTY_FUNCTION__
))
2221 "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", 2221, __extension__ __PRETTY_FUNCTION__
))
;
2222
2223 // C++0x [dcl.ref]p6:
2224 // If a typedef (7.1.3), a type template-parameter (14.3.1), or a
2225 // decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a
2226 // type T, an attempt to create the type "lvalue reference to cv TR" creates
2227 // the type "lvalue reference to T", while an attempt to create the type
2228 // "rvalue reference to cv TR" creates the type TR.
2229 bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
2230
2231 // C++ [dcl.ref]p4: There shall be no references to references.
2232 //
2233 // According to C++ DR 106, references to references are only
2234 // diagnosed when they are written directly (e.g., "int & &"),
2235 // but not when they happen via a typedef:
2236 //
2237 // typedef int& intref;
2238 // typedef intref& intref2;
2239 //
2240 // Parser::ParseDeclaratorInternal diagnoses the case where
2241 // references are written directly; here, we handle the
2242 // collapsing of references-to-references as described in C++0x.
2243 // DR 106 and 540 introduce reference-collapsing into C++98/03.
2244
2245 // C++ [dcl.ref]p1:
2246 // A declarator that specifies the type "reference to cv void"
2247 // is ill-formed.
2248 if (T->isVoidType()) {
2249 Diag(Loc, diag::err_reference_to_void);
2250 return QualType();
2251 }
2252
2253 if (getLangOpts().HLSL && Loc.isValid()) {
2254 Diag(Loc, diag::err_hlsl_pointers_unsupported) << 1;
2255 return QualType();
2256 }
2257
2258 if (checkQualifiedFunction(*this, T, Loc, QFK_Reference))
2259 return QualType();
2260
2261 if (T->isFunctionType() && getLangOpts().OpenCL &&
2262 !getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
2263 getLangOpts())) {
2264 Diag(Loc, diag::err_opencl_function_pointer) << /*reference*/ 1;
2265 return QualType();
2266 }
2267
2268 // In ARC, it is forbidden to build references to unqualified pointers.
2269 if (getLangOpts().ObjCAutoRefCount)
2270 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true);
2271
2272 if (getLangOpts().OpenCL)
2273 T = deduceOpenCLPointeeAddrSpace(*this, T);
2274
2275 // Handle restrict on references.
2276 if (LValueRef)
2277 return Context.getLValueReferenceType(T, SpelledAsLValue);
2278 return Context.getRValueReferenceType(T);
2279}
2280
2281/// Build a Read-only Pipe type.
2282///
2283/// \param T The type to which we'll be building a Pipe.
2284///
2285/// \param Loc We do not use it for now.
2286///
2287/// \returns A suitable pipe type, if there are no errors. Otherwise, returns a
2288/// NULL type.
2289QualType Sema::BuildReadPipeType(QualType T, SourceLocation Loc) {
2290 return Context.getReadPipeType(T);
2291}
2292
2293/// Build a Write-only Pipe type.
2294///
2295/// \param T The type to which we'll be building a Pipe.
2296///
2297/// \param Loc We do not use it for now.
2298///
2299/// \returns A suitable pipe type, if there are no errors. Otherwise, returns a
2300/// NULL type.
2301QualType Sema::BuildWritePipeType(QualType T, SourceLocation Loc) {
2302 return Context.getWritePipeType(T);
2303}
2304
2305/// Build a bit-precise integer type.
2306///
2307/// \param IsUnsigned Boolean representing the signedness of the type.
2308///
2309/// \param BitWidth Size of this int type in bits, or an expression representing
2310/// that.
2311///
2312/// \param Loc Location of the keyword.
2313QualType Sema::BuildBitIntType(bool IsUnsigned, Expr *BitWidth,
2314 SourceLocation Loc) {
2315 if (BitWidth->isInstantiationDependent())
2316 return Context.getDependentBitIntType(IsUnsigned, BitWidth);
2317
2318 llvm::APSInt Bits(32);
2319 ExprResult ICE =
2320 VerifyIntegerConstantExpression(BitWidth, &Bits, /*FIXME*/ AllowFold);
2321
2322 if (ICE.isInvalid())
2323 return QualType();
2324
2325 size_t NumBits = Bits.getZExtValue();
2326 if (!IsUnsigned && NumBits < 2) {
2327 Diag(Loc, diag::err_bit_int_bad_size) << 0;
2328 return QualType();
2329 }
2330
2331 if (IsUnsigned && NumBits < 1) {
2332 Diag(Loc, diag::err_bit_int_bad_size) << 1;
2333 return QualType();
2334 }
2335
2336 const TargetInfo &TI = getASTContext().getTargetInfo();
2337 if (NumBits > TI.getMaxBitIntWidth()) {
2338 Diag(Loc, diag::err_bit_int_max_size)
2339 << IsUnsigned << static_cast<uint64_t>(TI.getMaxBitIntWidth());
2340 return QualType();
2341 }
2342
2343 return Context.getBitIntType(IsUnsigned, NumBits);
2344}
2345
2346/// Check whether the specified array bound can be evaluated using the relevant
2347/// language rules. If so, returns the possibly-converted expression and sets
2348/// SizeVal to the size. If not, but the expression might be a VLA bound,
2349/// returns ExprResult(). Otherwise, produces a diagnostic and returns
2350/// ExprError().
2351static ExprResult checkArraySize(Sema &S, Expr *&ArraySize,
2352 llvm::APSInt &SizeVal, unsigned VLADiag,
2353 bool VLAIsError) {
2354 if (S.getLangOpts().CPlusPlus14 &&
2355 (VLAIsError ||
2356 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType())) {
2357 // C++14 [dcl.array]p1:
2358 // The constant-expression shall be a converted constant expression of
2359 // type std::size_t.
2360 //
2361 // Don't apply this rule if we might be forming a VLA: in that case, we
2362 // allow non-constant expressions and constant-folding. We only need to use
2363 // the converted constant expression rules (to properly convert the source)
2364 // when the source expression is of class type.
2365 return S.CheckConvertedConstantExpression(
2366 ArraySize, S.Context.getSizeType(), SizeVal, Sema::CCEK_ArrayBound);
2367 }
2368
2369 // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode
2370 // (like gnu99, but not c99) accept any evaluatable value as an extension.
2371 class VLADiagnoser : public Sema::VerifyICEDiagnoser {
2372 public:
2373 unsigned VLADiag;
2374 bool VLAIsError;
2375 bool IsVLA = false;
2376
2377 VLADiagnoser(unsigned VLADiag, bool VLAIsError)
2378 : VLADiag(VLADiag), VLAIsError(VLAIsError) {}
2379
2380 Sema::SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
2381 QualType T) override {
2382 return S.Diag(Loc, diag::err_array_size_non_int) << T;
2383 }
2384
2385 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
2386 SourceLocation Loc) override {
2387 IsVLA = !VLAIsError;
2388 return S.Diag(Loc, VLADiag);
2389 }
2390
2391 Sema::SemaDiagnosticBuilder diagnoseFold(Sema &S,
2392 SourceLocation Loc) override {
2393 return S.Diag(Loc, diag::ext_vla_folded_to_constant);
2394 }
2395 } Diagnoser(VLADiag, VLAIsError);
2396
2397 ExprResult R =
2398 S.VerifyIntegerConstantExpression(ArraySize, &SizeVal, Diagnoser);
2399 if (Diagnoser.IsVLA)
2400 return ExprResult();
2401 return R;
2402}
2403
2404bool Sema::checkArrayElementAlignment(QualType EltTy, SourceLocation Loc) {
2405 EltTy = Context.getBaseElementType(EltTy);
2406 if (EltTy->isIncompleteType() || EltTy->isDependentType() ||
2407 EltTy->isUndeducedType())
2408 return true;
2409
2410 CharUnits Size = Context.getTypeSizeInChars(EltTy);
2411 CharUnits Alignment = Context.getTypeAlignInChars(EltTy);
2412
2413 if (Size.isMultipleOf(Alignment))
2414 return true;
2415
2416 Diag(Loc, diag::err_array_element_alignment)
2417 << EltTy << Size.getQuantity() << Alignment.getQuantity();
2418 return false;
2419}
2420
2421/// Build an array type.
2422///
2423/// \param T The type of each element in the array.
2424///
2425/// \param ASM C99 array size modifier (e.g., '*', 'static').
2426///
2427/// \param ArraySize Expression describing the size of the array.
2428///
2429/// \param Brackets The range from the opening '[' to the closing ']'.
2430///
2431/// \param Entity The name of the entity that involves the array
2432/// type, if known.
2433///
2434/// \returns A suitable array type, if there are no errors. Otherwise,
2435/// returns a NULL type.
2436QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
2437 Expr *ArraySize, unsigned Quals,
2438 SourceRange Brackets, DeclarationName Entity) {
2439
2440 SourceLocation Loc = Brackets.getBegin();
2441 if (getLangOpts().CPlusPlus) {
2442 // C++ [dcl.array]p1:
2443 // T is called the array element type; this type shall not be a reference
2444 // type, the (possibly cv-qualified) type void, a function type or an
2445 // abstract class type.
2446 //
2447 // C++ [dcl.array]p3:
2448 // When several "array of" specifications are adjacent, [...] only the
2449 // first of the constant expressions that specify the bounds of the arrays
2450 // may be omitted.
2451 //
2452 // Note: function types are handled in the common path with C.
2453 if (T->isReferenceType()) {
2454 Diag(Loc, diag::err_illegal_decl_array_of_references)
2455 << getPrintableNameForEntity(Entity) << T;
2456 return QualType();
2457 }
2458
2459 if (T->isVoidType() || T->isIncompleteArrayType()) {
2460 Diag(Loc, diag::err_array_incomplete_or_sizeless_type) << 0 << T;
2461 return QualType();
2462 }
2463
2464 if (RequireNonAbstractType(Brackets.getBegin(), T,
2465 diag::err_array_of_abstract_type))
2466 return QualType();
2467
2468 // Mentioning a member pointer type for an array type causes us to lock in
2469 // an inheritance model, even if it's inside an unused typedef.
2470 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
2471 if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>())
2472 if (!MPTy->getClass()->isDependentType())
2473 (void)isCompleteType(Loc, T);
2474
2475 } else {
2476 // C99 6.7.5.2p1: If the element type is an incomplete or function type,
2477 // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
2478 if (RequireCompleteSizedType(Loc, T,
2479 diag::err_array_incomplete_or_sizeless_type))
2480 return QualType();
2481 }
2482
2483 if (T->isSizelessType()) {
2484 Diag(Loc, diag::err_array_incomplete_or_sizeless_type) << 1 << T;
2485 return QualType();
2486 }
2487
2488 if (T->isFunctionType()) {
2489 Diag(Loc, diag::err_illegal_decl_array_of_functions)
2490 << getPrintableNameForEntity(Entity) << T;
2491 return QualType();
2492 }
2493
2494 if (const RecordType *EltTy = T->getAs<RecordType>()) {
2495 // If the element type is a struct or union that contains a variadic
2496 // array, accept it as a GNU extension: C99 6.7.2.1p2.
2497 if (EltTy->getDecl()->hasFlexibleArrayMember())
2498 Diag(Loc, diag::ext_flexible_array_in_array) << T;
2499 } else if (T->isObjCObjectType()) {
2500 Diag(Loc, diag::err_objc_array_of_interfaces) << T;
2501 return QualType();
2502 }
2503
2504 if (!checkArrayElementAlignment(T, Loc))
2505 return QualType();
2506
2507 // Do placeholder conversions on the array size expression.
2508 if (ArraySize && ArraySize->hasPlaceholderType()) {
2509 ExprResult Result = CheckPlaceholderExpr(ArraySize);
2510 if (Result.isInvalid()) return QualType();
2511 ArraySize = Result.get();
2512 }
2513
2514 // Do lvalue-to-rvalue conversions on the array size expression.
2515 if (ArraySize && !ArraySize->isPRValue()) {
2516 ExprResult Result = DefaultLvalueConversion(ArraySize);
2517 if (Result.isInvalid())
2518 return QualType();
2519
2520 ArraySize = Result.get();
2521 }
2522
2523 // C99 6.7.5.2p1: The size expression shall have integer type.
2524 // C++11 allows contextual conversions to such types.
2525 if (!getLangOpts().CPlusPlus11 &&
2526 ArraySize && !ArraySize->isTypeDependent() &&
2527 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
2528 Diag(ArraySize->getBeginLoc(), diag::err_array_size_non_int)
2529 << ArraySize->getType() << ArraySize->getSourceRange();
2530 return QualType();
2531 }
2532
2533 // VLAs always produce at least a -Wvla diagnostic, sometimes an error.
2534 unsigned VLADiag;
2535 bool VLAIsError;
2536 if (getLangOpts().OpenCL) {
2537 // OpenCL v1.2 s6.9.d: variable length arrays are not supported.
2538 VLADiag = diag::err_opencl_vla;
2539 VLAIsError = true;
2540 } else if (getLangOpts().C99) {
2541 VLADiag = diag::warn_vla_used;
2542 VLAIsError = false;
2543 } else if (isSFINAEContext()) {
2544 VLADiag = diag::err_vla_in_sfinae;
2545 VLAIsError = true;
2546 } else if (getLangOpts().OpenMP && isInOpenMPTaskUntiedContext()) {
2547 VLADiag = diag::err_openmp_vla_in_task_untied;
2548 VLAIsError = true;
2549 } else {
2550 VLADiag = diag::ext_vla;
2551 VLAIsError = false;
2552 }
2553
2554 llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType()));
2555 if (!ArraySize) {
2556 if (ASM == ArrayType::Star) {
2557 Diag(Loc, VLADiag);
2558 if (VLAIsError)
2559 return QualType();
2560
2561 T = Context.getVariableArrayType(T, nullptr, ASM, Quals, Brackets);
2562 } else {
2563 T = Context.getIncompleteArrayType(T, ASM, Quals);
2564 }
2565 } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) {
2566 T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets);
2567 } else {
2568 ExprResult R =
2569 checkArraySize(*this, ArraySize, ConstVal, VLADiag, VLAIsError);
2570 if (R.isInvalid())
2571 return QualType();
2572
2573 if (!R.isUsable()) {
2574 // C99: an array with a non-ICE size is a VLA. We accept any expression
2575 // that we can fold to a non-zero positive value as a non-VLA as an
2576 // extension.
2577 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
2578 } else if (!T->isDependentType() && !T->isIncompleteType() &&
2579 !T->isConstantSizeType()) {
2580 // C99: an array with an element type that has a non-constant-size is a
2581 // VLA.
2582 // FIXME: Add a note to explain why this isn't a VLA.
2583 Diag(Loc, VLADiag);
2584 if (VLAIsError)
2585 return QualType();
2586 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
2587 } else {
2588 // C99 6.7.5.2p1: If the expression is a constant expression, it shall
2589 // have a value greater than zero.
2590 // In C++, this follows from narrowing conversions being disallowed.
2591 if (ConstVal.isSigned() && ConstVal.isNegative()) {
2592 if (Entity)
2593 Diag(ArraySize->getBeginLoc(), diag::err_decl_negative_array_size)
2594 << getPrintableNameForEntity(Entity)
2595 << ArraySize->getSourceRange();
2596 else
2597 Diag(ArraySize->getBeginLoc(),
2598 diag::err_typecheck_negative_array_size)
2599 << ArraySize->getSourceRange();
2600 return QualType();
2601 }
2602 if (ConstVal == 0) {
2603 // GCC accepts zero sized static arrays. We allow them when
2604 // we're not in a SFINAE context.
2605 Diag(ArraySize->getBeginLoc(),
2606 isSFINAEContext() ? diag::err_typecheck_zero_array_size
2607 : diag::ext_typecheck_zero_array_size)
2608 << 0 << ArraySize->getSourceRange();
2609 }
2610
2611 // Is the array too large?
2612 unsigned ActiveSizeBits =
2613 (!T->isDependentType() && !T->isVariablyModifiedType() &&
2614 !T->isIncompleteType() && !T->isUndeducedType())
2615 ? ConstantArrayType::getNumAddressingBits(Context, T, ConstVal)
2616 : ConstVal.getActiveBits();
2617 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
2618 Diag(ArraySize->getBeginLoc(), diag::err_array_too_large)
2619 << toString(ConstVal, 10) << ArraySize->getSourceRange();
2620 return QualType();
2621 }
2622
2623 T = Context.getConstantArrayType(T, ConstVal, ArraySize, ASM, Quals);
2624 }
2625 }
2626
2627 if (T->isVariableArrayType() && !Context.getTargetInfo().isVLASupported()) {
2628 // CUDA device code and some other targets don't support VLAs.
2629 bool IsCUDADevice = (getLangOpts().CUDA && getLangOpts().CUDAIsDevice);
2630 targetDiag(Loc,
2631 IsCUDADevice ? diag::err_cuda_vla : diag::err_vla_unsupported)
2632 << (IsCUDADevice ? CurrentCUDATarget() : 0);
2633 }
2634
2635 // If this is not C99, diagnose array size modifiers on non-VLAs.
2636 if (!getLangOpts().C99 && !T->isVariableArrayType() &&
2637 (ASM != ArrayType::Normal || Quals != 0)) {
2638 Diag(Loc, getLangOpts().CPlusPlus ? diag::err_c99_array_usage_cxx
2639 : diag::ext_c99_array_usage)
2640 << ASM;
2641 }
2642
2643 // OpenCL v2.0 s6.12.5 - Arrays of blocks are not supported.
2644 // OpenCL v2.0 s6.16.13.1 - Arrays of pipe type are not supported.
2645 // OpenCL v2.0 s6.9.b - Arrays of image/sampler type are not supported.
2646 if (getLangOpts().OpenCL) {
2647 const QualType ArrType = Context.getBaseElementType(T);
2648 if (ArrType->isBlockPointerType() || ArrType->isPipeType() ||
2649 ArrType->isSamplerT() || ArrType->isImageType()) {
2650 Diag(Loc, diag::err_opencl_invalid_type_array) << ArrType;
2651 return QualType();
2652 }
2653 }
2654
2655 return T;
2656}
2657
2658QualType Sema::BuildVectorType(QualType CurType, Expr *SizeExpr,
2659 SourceLocation AttrLoc) {
2660 // The base type must be integer (not Boolean or enumeration) or float, and
2661 // can't already be a vector.
2662 if ((!CurType->isDependentType() &&
2663 (!CurType->isBuiltinType() || CurType->isBooleanType() ||
2664 (!CurType->isIntegerType() && !CurType->isRealFloatingType())) &&
2665 !CurType->isBitIntType()) ||
2666 CurType->isArrayType()) {
2667 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << CurType;
2668 return QualType();
2669 }
2670 // Only support _BitInt elements with byte-sized power of 2 NumBits.
2671 if (CurType->isBitIntType()) {
2672 unsigned NumBits = CurType->getAs<BitIntType>()->getNumBits();
2673 if (!llvm::isPowerOf2_32(NumBits) || NumBits < 8) {
2674 Diag(AttrLoc, diag::err_attribute_invalid_bitint_vector_type)
2675 << (NumBits < 8);
2676 return QualType();
2677 }
2678 }
2679
2680 if (SizeExpr->isTypeDependent() || SizeExpr->isValueDependent())
2681 return Context.getDependentVectorType(CurType, SizeExpr, AttrLoc,
2682 VectorType::GenericVector);
2683
2684 Optional<llvm::APSInt> VecSize = SizeExpr->getIntegerConstantExpr(Context);
2685 if (!VecSize) {
2686 Diag(AttrLoc, diag::err_attribute_argument_type)
2687 << "vector_size" << AANT_ArgumentIntegerConstant
2688 << SizeExpr->getSourceRange();
2689 return QualType();
2690 }
2691
2692 if (CurType->isDependentType())
2693 return Context.getDependentVectorType(CurType, SizeExpr, AttrLoc,
2694 VectorType::GenericVector);
2695
2696 // vecSize is specified in bytes - convert to bits.
2697 if (!VecSize->isIntN(61)) {
2698 // Bit size will overflow uint64.
2699 Diag(AttrLoc, diag::err_attribute_size_too_large)
2700 << SizeExpr->getSourceRange() << "vector";
2701 return QualType();
2702 }
2703 uint64_t VectorSizeBits = VecSize->getZExtValue() * 8;
2704 unsigned TypeSize = static_cast<unsigned>(Context.getTypeSize(CurType));
2705
2706 if (VectorSizeBits == 0) {
2707 Diag(AttrLoc, diag::err_attribute_zero_size)
2708 << SizeExpr->getSourceRange() << "vector";
2709 return QualType();
2710 }
2711
2712 if (!TypeSize || VectorSizeBits % TypeSize) {
2713 Diag(AttrLoc, diag::err_attribute_invalid_size)
2714 << SizeExpr->getSourceRange();
2715 return QualType();
2716 }
2717
2718 if (VectorSizeBits / TypeSize > std::numeric_limits<uint32_t>::max()) {
2719 Diag(AttrLoc, diag::err_attribute_size_too_large)
2720 << SizeExpr->getSourceRange() << "vector";
2721 return QualType();
2722 }
2723
2724 return Context.getVectorType(CurType, VectorSizeBits / TypeSize,
2725 VectorType::GenericVector);
2726}
2727
2728/// Build an ext-vector type.
2729///
2730/// Run the required checks for the extended vector type.
2731QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize,
2732 SourceLocation AttrLoc) {
2733 // Unlike gcc's vector_size attribute, we do not allow vectors to be defined
2734 // in conjunction with complex types (pointers, arrays, functions, etc.).
2735 //
2736 // Additionally, OpenCL prohibits vectors of booleans (they're considered a
2737 // reserved data type under OpenCL v2.0 s6.1.4), we don't support selects
2738 // on bitvectors, and we have no well-defined ABI for bitvectors, so vectors
2739 // of bool aren't allowed.
2740 //
2741 // We explictly allow bool elements in ext_vector_type for C/C++.
2742 bool IsNoBoolVecLang = getLangOpts().OpenCL || getLangOpts().OpenCLCPlusPlus;
2743 if ((!T->isDependentType() && !T->isIntegerType() &&
2744 !T->isRealFloatingType()) ||
2745 (IsNoBoolVecLang && T->isBooleanType())) {
2746 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
2747 return QualType();
2748 }
2749
2750 // Only support _BitInt elements with byte-sized power of 2 NumBits.
2751 if (T->isBitIntType()) {
2752 unsigned NumBits = T->getAs<BitIntType>()->getNumBits();
2753 if (!llvm::isPowerOf2_32(NumBits) || NumBits < 8) {
2754 Diag(AttrLoc, diag::err_attribute_invalid_bitint_vector_type)
2755 << (NumBits < 8);
2756 return QualType();
2757 }
2758 }
2759
2760 if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) {
2761 Optional<llvm::APSInt> vecSize = ArraySize->getIntegerConstantExpr(Context);
2762 if (!vecSize) {
2763 Diag(AttrLoc, diag::err_attribute_argument_type)
2764 << "ext_vector_type" << AANT_ArgumentIntegerConstant
2765 << ArraySize->getSourceRange();
2766 return QualType();
2767 }
2768
2769 if (!vecSize->isIntN(32)) {
2770 Diag(AttrLoc, diag::err_attribute_size_too_large)
2771 << ArraySize->getSourceRange() << "vector";
2772 return QualType();
2773 }
2774 // Unlike gcc's vector_size attribute, the size is specified as the
2775 // number of elements, not the number of bytes.
2776 unsigned vectorSize = static_cast<unsigned>(vecSize->getZExtValue());
2777
2778 if (vectorSize == 0) {
2779 Diag(AttrLoc, diag::err_attribute_zero_size)
2780 << ArraySize->getSourceRange() << "vector";
2781 return QualType();
2782 }
2783
2784 return Context.getExtVectorType(T, vectorSize);
2785 }
2786
2787 return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc);
2788}
2789
2790QualType Sema::BuildMatrixType(QualType ElementTy, Expr *NumRows, Expr *NumCols,
2791 SourceLocation AttrLoc) {
2792 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", 2793, __extension__ __PRETTY_FUNCTION__
))
2793 "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", 2793, __extension__ __PRETTY_FUNCTION__
))
;
2794
2795 // Check element type, if it is not dependent.
2796 if (!ElementTy->isDependentType() &&
2797 !MatrixType::isValidElementType(ElementTy)) {
2798 Diag(AttrLoc, diag::err_attribute_invalid_matrix_type) << ElementTy;
2799 return QualType();
2800 }
2801
2802 if (NumRows->isTypeDependent() || NumCols->isTypeDependent() ||
2803 NumRows->isValueDependent() || NumCols->isValueDependent())
2804 return Context.getDependentSizedMatrixType(ElementTy, NumRows, NumCols,
2805 AttrLoc);
2806
2807 Optional<llvm::APSInt> ValueRows = NumRows->getIntegerConstantExpr(Context);
2808 Optional<llvm::APSInt> ValueColumns =
2809 NumCols->getIntegerConstantExpr(Context);
2810
2811 auto const RowRange = NumRows->getSourceRange();
2812 auto const ColRange = NumCols->getSourceRange();
2813
2814 // Both are row and column expressions are invalid.
2815 if (!ValueRows && !ValueColumns) {
2816 Diag(AttrLoc, diag::err_attribute_argument_type)
2817 << "matrix_type" << AANT_ArgumentIntegerConstant << RowRange
2818 << ColRange;
2819 return QualType();
2820 }
2821
2822 // Only the row expression is invalid.
2823 if (!ValueRows) {
2824 Diag(AttrLoc, diag::err_attribute_argument_type)
2825 << "matrix_type" << AANT_ArgumentIntegerConstant << RowRange;
2826 return QualType();
2827 }
2828
2829 // Only the column expression is invalid.
2830 if (!ValueColumns) {
2831 Diag(AttrLoc, diag::err_attribute_argument_type)
2832 << "matrix_type" << AANT_ArgumentIntegerConstant << ColRange;
2833 return QualType();
2834 }
2835
2836 // Check the matrix dimensions.
2837 unsigned MatrixRows = static_cast<unsigned>(ValueRows->getZExtValue());
2838 unsigned MatrixColumns = static_cast<unsigned>(ValueColumns->getZExtValue());
2839 if (MatrixRows == 0 && MatrixColumns == 0) {
2840 Diag(AttrLoc, diag::err_attribute_zero_size)
2841 << "matrix" << RowRange << ColRange;
2842 return QualType();
2843 }
2844 if (MatrixRows == 0) {
2845 Diag(AttrLoc, diag::err_attribute_zero_size) << "matrix" << RowRange;
2846 return QualType();
2847 }
2848 if (MatrixColumns == 0) {
2849 Diag(AttrLoc, diag::err_attribute_zero_size) << "matrix" << ColRange;
2850 return QualType();
2851 }
2852 if (!ConstantMatrixType::isDimensionValid(MatrixRows)) {
2853 Diag(AttrLoc, diag::err_attribute_size_too_large)
2854 << RowRange << "matrix row";
2855 return QualType();
2856 }
2857 if (!ConstantMatrixType::isDimensionValid(MatrixColumns)) {
2858 Diag(AttrLoc, diag::err_attribute_size_too_large)
2859 << ColRange << "matrix column";
2860 return QualType();
2861 }
2862 return Context.getConstantMatrixType(ElementTy, MatrixRows, MatrixColumns);
2863}
2864
2865bool Sema::CheckFunctionReturnType(QualType T, SourceLocation Loc) {
2866 if (T->isArrayType() || T->isFunctionType()) {
2867 Diag(Loc, diag::err_func_returning_array_function)
2868 << T->isFunctionType() << T;
2869 return true;
2870 }
2871
2872 // Functions cannot return half FP.
2873 if (T->isHalfType() && !getLangOpts().NativeHalfArgsAndReturns &&
2874 !Context.getTargetInfo().allowHalfArgsAndReturns()) {
2875 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 <<
2876 FixItHint::CreateInsertion(Loc, "*");
2877 return true;
2878 }
2879
2880 // Methods cannot return interface types. All ObjC objects are
2881 // passed by reference.
2882 if (T->isObjCObjectType()) {
2883 Diag(Loc, diag::err_object_cannot_be_passed_returned_by_value)
2884 << 0 << T << FixItHint::CreateInsertion(Loc, "*");
2885 return true;
2886 }
2887
2888 if (T.hasNonTrivialToPrimitiveDestructCUnion() ||
2889 T.hasNonTrivialToPrimitiveCopyCUnion())
2890 checkNonTrivialCUnion(T, Loc, NTCUC_FunctionReturn,
2891 NTCUK_Destruct|NTCUK_Copy);
2892
2893 // C++2a [dcl.fct]p12:
2894 // A volatile-qualified return type is deprecated
2895 if (T.isVolatileQualified() && getLangOpts().CPlusPlus20)
2896 Diag(Loc, diag::warn_deprecated_volatile_return) << T;
2897
2898 if (T.getAddressSpace() != LangAS::Default && getLangOpts().HLSL)
2899 return true;
2900 return false;
2901}
2902
2903/// Check the extended parameter information. Most of the necessary
2904/// checking should occur when applying the parameter attribute; the
2905/// only other checks required are positional restrictions.
2906static void checkExtParameterInfos(Sema &S, ArrayRef<QualType> paramTypes,
2907 const FunctionProtoType::ExtProtoInfo &EPI,
2908 llvm::function_ref<SourceLocation(unsigned)> getParamLoc) {
2909 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", 2909, __extension__ __PRETTY_FUNCTION__
))
;
2910
2911 bool emittedError = false;
2912 auto actualCC = EPI.ExtInfo.getCC();
2913 enum class RequiredCC { OnlySwift, SwiftOrSwiftAsync };
2914 auto checkCompatible = [&](unsigned paramIndex, RequiredCC required) {
2915 bool isCompatible =
2916 (required == RequiredCC::OnlySwift)
2917 ? (actualCC == CC_Swift)
2918 : (actualCC == CC_Swift || actualCC == CC_SwiftAsync);
2919 if (isCompatible || emittedError)
2920 return;
2921 S.Diag(getParamLoc(paramIndex), diag::err_swift_param_attr_not_swiftcall)
2922 << getParameterABISpelling(EPI.ExtParameterInfos[paramIndex].getABI())
2923 << (required == RequiredCC::OnlySwift);
2924 emittedError = true;
2925 };
2926 for (size_t paramIndex = 0, numParams = paramTypes.size();
2927 paramIndex != numParams; ++paramIndex) {
2928 switch (EPI.ExtParameterInfos[paramIndex].getABI()) {
2929 // Nothing interesting to check for orindary-ABI parameters.
2930 case ParameterABI::Ordinary:
2931 continue;
2932
2933 // swift_indirect_result parameters must be a prefix of the function
2934 // arguments.
2935 case ParameterABI::SwiftIndirectResult:
2936 checkCompatible(paramIndex, RequiredCC::SwiftOrSwiftAsync);
2937 if (paramIndex != 0 &&
2938 EPI.ExtParameterInfos[paramIndex - 1].getABI()
2939 != ParameterABI::SwiftIndirectResult) {
2940 S.Diag(getParamLoc(paramIndex),
2941 diag::err_swift_indirect_result_not_first);
2942 }
2943 continue;
2944
2945 case ParameterABI::SwiftContext:
2946 checkCompatible(paramIndex, RequiredCC::SwiftOrSwiftAsync);
2947 continue;
2948
2949 // SwiftAsyncContext is not limited to swiftasynccall functions.
2950 case ParameterABI::SwiftAsyncContext:
2951 continue;
2952
2953 // swift_error parameters must be preceded by a swift_context parameter.
2954 case ParameterABI::SwiftErrorResult:
2955 checkCompatible(paramIndex, RequiredCC::OnlySwift);
2956 if (paramIndex == 0 ||
2957 EPI.ExtParameterInfos[paramIndex - 1].getABI() !=
2958 ParameterABI::SwiftContext) {
2959 S.Diag(getParamLoc(paramIndex),
2960 diag::err_swift_error_result_not_after_swift_context);
2961 }
2962 continue;
2963 }
2964 llvm_unreachable("bad ABI kind")::llvm::llvm_unreachable_internal("bad ABI kind", "clang/lib/Sema/SemaType.cpp"
, 2964)
;
2965 }
2966}
2967
2968QualType Sema::BuildFunctionType(QualType T,
2969 MutableArrayRef<QualType> ParamTypes,
2970 SourceLocation Loc, DeclarationName Entity,
2971 const FunctionProtoType::ExtProtoInfo &EPI) {
2972 bool Invalid = false;
2973
2974 Invalid |= CheckFunctionReturnType(T, Loc);
2975
2976 for (unsigned Idx = 0, Cnt = ParamTypes.size(); Idx < Cnt; ++Idx) {
2977 // FIXME: Loc is too inprecise here, should use proper locations for args.
2978 QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]);
2979 if (ParamType->isVoidType()) {
2980 Diag(Loc, diag::err_param_with_void_type);
2981 Invalid = true;
2982 } else if (ParamType->isHalfType() && !getLangOpts().NativeHalfArgsAndReturns &&
2983 !Context.getTargetInfo().allowHalfArgsAndReturns()) {
2984 // Disallow half FP arguments.
2985 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 <<
2986 FixItHint::CreateInsertion(Loc, "*");
2987 Invalid = true;
2988 }
2989
2990 // C++2a [dcl.fct]p4:
2991 // A parameter with volatile-qualified type is deprecated
2992 if (ParamType.isVolatileQualified() && getLangOpts().CPlusPlus20)
2993 Diag(Loc, diag::warn_deprecated_volatile_param) << ParamType;
2994
2995 ParamTypes[Idx] = ParamType;
2996 }
2997
2998 if (EPI.ExtParameterInfos) {
2999 checkExtParameterInfos(*this, ParamTypes, EPI,
3000 [=](unsigned i) { return Loc; });
3001 }
3002
3003 if (EPI.ExtInfo.getProducesResult()) {
3004 // This is just a warning, so we can't fail to build if we see it.
3005 checkNSReturnsRetainedReturnType(Loc, T);
3006 }
3007
3008 if (Invalid)
3009 return QualType();
3010
3011 return Context.getFunctionType(T, ParamTypes, EPI);
3012}
3013
3014/// Build a member pointer type \c T Class::*.
3015///
3016/// \param T the type to which the member pointer refers.
3017/// \param Class the class type into which the member pointer points.
3018/// \param Loc the location where this type begins
3019/// \param Entity the name of the entity that will have this member pointer type
3020///
3021/// \returns a member pointer type, if successful, or a NULL type if there was
3022/// an error.
3023QualType Sema::BuildMemberPointerType(QualType T, QualType Class,
3024 SourceLocation Loc,
3025 DeclarationName Entity) {
3026 // Verify that we're not building a pointer to pointer to function with
3027 // exception specification.
3028 if (CheckDistantExceptionSpec(T)) {
3029 Diag(Loc, diag::err_distant_exception_spec);
3030 return QualType();
3031 }
3032
3033 // C++ 8.3.3p3: A pointer to member shall not point to ... a member
3034 // with reference type, or "cv void."
3035 if (T->isReferenceType()) {
3036 Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
3037 << getPrintableNameForEntity(Entity) << T;
3038 return QualType();
3039 }
3040
3041 if (T->isVoidType()) {
3042 Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
3043 << getPrintableNameForEntity(Entity);
3044 return QualType();
3045 }
3046
3047 if (!Class->isDependentType() && !Class->isRecordType()) {
3048 Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
3049 return QualType();
3050 }
3051
3052 if (T->isFunctionType() && getLangOpts().OpenCL &&
3053 !getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
3054 getLangOpts())) {
3055 Diag(Loc, diag::err_opencl_function_pointer) << /*pointer*/ 0;
3056 return QualType();
3057 }
3058
3059 if (getLangOpts().HLSL && Loc.isValid()) {
3060 Diag(Loc, diag::err_hlsl_pointers_unsupported) << 0;
3061 return QualType();
3062 }
3063
3064 // Adjust the default free function calling convention to the default method
3065 // calling convention.
3066 bool IsCtorOrDtor =
3067 (Entity.getNameKind() == DeclarationName::CXXConstructorName) ||
3068 (Entity.getNameKind() == DeclarationName::CXXDestructorName);
3069 if (T->isFunctionType())
3070 adjustMemberFunctionCC(T, /*IsStatic=*/false, IsCtorOrDtor, Loc);
3071
3072 return Context.getMemberPointerType(T, Class.getTypePtr());
3073}
3074
3075/// Build a block pointer type.
3076///
3077/// \param T The type to which we'll be building a block pointer.
3078///
3079/// \param Loc The source location, used for diagnostics.
3080///
3081/// \param Entity The name of the entity that involves the block pointer
3082/// type, if known.
3083///
3084/// \returns A suitable block pointer type, if there are no
3085/// errors. Otherwise, returns a NULL type.
3086QualType Sema::BuildBlockPointerType(QualType T,
3087 SourceLocation Loc,
3088 DeclarationName Entity) {
3089 if (!T->isFunctionType()) {
3090 Diag(Loc, diag::err_nonfunction_block_type);
3091 return QualType();
3092 }
3093
3094 if (checkQualifiedFunction(*this, T, Loc, QFK_BlockPointer))
3095 return QualType();
3096
3097 if (getLangOpts().OpenCL)
3098 T = deduceOpenCLPointeeAddrSpace(*this, T);
3099
3100 return Context.getBlockPointerType(T);
3101}
3102
3103QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) {
3104 QualType QT = Ty.get();
3105 if (QT.isNull()) {
3106 if (TInfo) *TInfo = nullptr;
3107 return QualType();
3108 }
3109
3110 TypeSourceInfo *DI = nullptr;
3111 if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
3112 QT = LIT->getType();
3113 DI = LIT->getTypeSourceInfo();
3114 }
3115
3116 if (TInfo) *TInfo = DI;
3117 return QT;
3118}
3119
3120static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
3121 Qualifiers::ObjCLifetime ownership,
3122 unsigned chunkIndex);
3123
3124/// Given that this is the declaration of a parameter under ARC,
3125/// attempt to infer attributes and such for pointer-to-whatever
3126/// types.
3127static void inferARCWriteback(TypeProcessingState &state,
3128 QualType &declSpecType) {
3129 Sema &S = state.getSema();
3130 Declarator &declarator = state.getDeclarator();
3131
3132 // TODO: should we care about decl qualifiers?
3133
3134 // Check whether the declarator has the expected form. We walk
3135 // from the inside out in order to make the block logic work.
3136 unsigned outermostPointerIndex = 0;
3137 bool isBlockPointer = false;
3138 unsigned numPointers = 0;
3139 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
3140 unsigned chunkIndex = i;
3141 DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex);
3142 switch (chunk.Kind) {
3143 case DeclaratorChunk::Paren:
3144 // Ignore parens.
3145 break;
3146
3147 case DeclaratorChunk::Reference:
3148 case DeclaratorChunk::Pointer:
3149 // Count the number of pointers. Treat references
3150 // interchangeably as pointers; if they're mis-ordered, normal
3151 // type building will discover that.
3152 outermostPointerIndex = chunkIndex;
3153 numPointers++;
3154 break;
3155
3156 case DeclaratorChunk::BlockPointer:
3157 // If we have a pointer to block pointer, that's an acceptable
3158 // indirect reference; anything else is not an application of
3159 // the rules.
3160 if (numPointers != 1) return;
3161 numPointers++;
3162 outermostPointerIndex = chunkIndex;
3163 isBlockPointer = true;
3164
3165 // We don't care about pointer structure in return values here.
3166 goto done;
3167
3168 case DeclaratorChunk::Array: // suppress if written (id[])?
3169 case DeclaratorChunk::Function:
3170 case DeclaratorChunk::MemberPointer:
3171 case DeclaratorChunk::Pipe:
3172 return;
3173 }
3174 }
3175 done:
3176
3177 // If we have *one* pointer, then we want to throw the qualifier on
3178 // the declaration-specifiers, which means that it needs to be a
3179 // retainable object type.
3180 if (numPointers == 1) {
3181 // If it's not a retainable object type, the rule doesn't apply.
3182 if (!declSpecType->isObjCRetainableType()) return;
3183
3184 // If it already has lifetime, don't do anything.
3185 if (declSpecType.getObjCLifetime()) return;
3186
3187 // Otherwise, modify the type in-place.
3188 Qualifiers qs;
3189
3190 if (declSpecType->isObjCARCImplicitlyUnretainedType())
3191 qs.addObjCLifetime(Qualifiers::OCL_ExplicitNone);
3192 else
3193 qs.addObjCLifetime(Qualifiers::OCL_Autoreleasing);
3194 declSpecType = S.Context.getQualifiedType(declSpecType, qs);
3195
3196 // If we have *two* pointers, then we want to throw the qualifier on
3197 // the outermost pointer.
3198 } else if (numPointers == 2) {
3199 // If we don't have a block pointer, we need to check whether the
3200 // declaration-specifiers gave us something that will turn into a
3201 // retainable object pointer after we slap the first pointer on it.
3202 if (!isBlockPointer && !declSpecType->isObjCObjectType())
3203 return;
3204
3205 // Look for an explicit lifetime attribute there.
3206 DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex);
3207 if (chunk.Kind != DeclaratorChunk::Pointer &&
3208 chunk.Kind != DeclaratorChunk::BlockPointer)
3209 return;
3210 for (const ParsedAttr &AL : chunk.getAttrs())
3211 if (AL.getKind() == ParsedAttr::AT_ObjCOwnership)
3212 return;
3213
3214 transferARCOwnershipToDeclaratorChunk(state, Qualifiers::OCL_Autoreleasing,
3215 outermostPointerIndex);
3216
3217 // Any other number of pointers/references does not trigger the rule.
3218 } else return;
3219
3220 // TODO: mark whether we did this inference?
3221}
3222
3223void Sema::diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
3224 SourceLocation FallbackLoc,
3225 SourceLocation ConstQualLoc,
3226 SourceLocation VolatileQualLoc,
3227 SourceLocation RestrictQualLoc,
3228 SourceLocation AtomicQualLoc,
3229 SourceLocation UnalignedQualLoc) {
3230 if (!Quals)
3231 return;
3232
3233 struct Qual {
3234 const char *Name;
3235 unsigned Mask;
3236 SourceLocation Loc;
3237 } const QualKinds[5] = {
3238 { "const", DeclSpec::TQ_const, ConstQualLoc },
3239 { "volatile", DeclSpec::TQ_volatile, VolatileQualLoc },
3240 { "restrict", DeclSpec::TQ_restrict, RestrictQualLoc },
3241 { "__unaligned", DeclSpec::TQ_unaligned, UnalignedQualLoc },
3242 { "_Atomic", DeclSpec::TQ_atomic, AtomicQualLoc }
3243 };
3244
3245 SmallString<32> QualStr;
3246 unsigned NumQuals = 0;
3247 SourceLocation Loc;
3248 FixItHint FixIts[5];
3249
3250 // Build a string naming the redundant qualifiers.
3251 for (auto &E : QualKinds) {
3252 if (Quals & E.Mask) {
3253 if (!QualStr.empty()) QualStr += ' ';
3254 QualStr += E.Name;
3255
3256 // If we have a location for the qualifier, offer a fixit.
3257 SourceLocation QualLoc = E.Loc;
3258 if (QualLoc.isValid()) {
3259 FixIts[NumQuals] = FixItHint::CreateRemoval(QualLoc);
3260 if (Loc.isInvalid() ||
3261 getSourceManager().isBeforeInTranslationUnit(QualLoc, Loc))
3262 Loc = QualLoc;
3263 }
3264
3265 ++NumQuals;
3266 }
3267 }
3268
3269 Diag(Loc.isInvalid() ? FallbackLoc : Loc, DiagID)
3270 << QualStr << NumQuals << FixIts[0] << FixIts[1] << FixIts[2] << FixIts[3];
3271}
3272
3273// Diagnose pointless type qualifiers on the return type of a function.
3274static void diagnoseRedundantReturnTypeQualifiers(Sema &S, QualType RetTy,
3275 Declarator &D,
3276 unsigned FunctionChunkIndex) {
3277 const DeclaratorChunk::FunctionTypeInfo &FTI =
3278 D.getTypeObject(FunctionChunkIndex).Fun;
3279 if (FTI.hasTrailingReturnType()) {
3280 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
3281 RetTy.getLocalCVRQualifiers(),
3282 FTI.getTrailingReturnTypeLoc());
3283 return;
3284 }
3285
3286 for (unsigned OuterChunkIndex = FunctionChunkIndex + 1,
3287 End = D.getNumTypeObjects();
3288 OuterChunkIndex != End; ++OuterChunkIndex) {
3289 DeclaratorChunk &OuterChunk = D.getTypeObject(OuterChunkIndex);
3290 switch (OuterChunk.Kind) {
3291 case DeclaratorChunk::Paren:
3292 continue;
3293
3294 case DeclaratorChunk::Pointer: {
3295 DeclaratorChunk::PointerTypeInfo &PTI = OuterChunk.Ptr;
3296 S.diagnoseIgnoredQualifiers(
3297 diag::warn_qual_return_type,
3298 PTI.TypeQuals,
3299 SourceLocation(),
3300 PTI.ConstQualLoc,
3301 PTI.VolatileQualLoc,
3302 PTI.RestrictQualLoc,
3303 PTI.AtomicQualLoc,
3304 PTI.UnalignedQualLoc);
3305 return;
3306 }
3307
3308 case DeclaratorChunk::Function:
3309 case DeclaratorChunk::BlockPointer:
3310 case DeclaratorChunk::Reference:
3311 case DeclaratorChunk::Array:
3312 case DeclaratorChunk::MemberPointer:
3313 case DeclaratorChunk::Pipe:
3314 // FIXME: We can't currently provide an accurate source location and a
3315 // fix-it hint for these.
3316 unsigned AtomicQual = RetTy->isAtomicType() ? DeclSpec::TQ_atomic : 0;
3317 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
3318 RetTy.getCVRQualifiers() | AtomicQual,
3319 D.getIdentifierLoc());
3320 return;
3321 }
3322
3323 llvm_unreachable("unknown declarator chunk kind")::llvm::llvm_unreachable_internal("unknown declarator chunk kind"
, "clang/lib/Sema/SemaType.cpp", 3323)
;
3324 }
3325
3326 // If the qualifiers come from a conversion function type, don't diagnose
3327 // them -- they're not necessarily redundant, since such a conversion
3328 // operator can be explicitly called as "x.operator const int()".
3329 if (D.getName().getKind() == UnqualifiedIdKind::IK_ConversionFunctionId)
3330 return;
3331
3332 // Just parens all the way out to the decl specifiers. Diagnose any qualifiers
3333 // which are present there.
3334 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
3335 D.getDeclSpec().getTypeQualifiers(),
3336 D.getIdentifierLoc(),
3337 D.getDeclSpec().getConstSpecLoc(),
3338 D.getDeclSpec().getVolatileSpecLoc(),
3339 D.getDeclSpec().getRestrictSpecLoc(),
3340 D.getDeclSpec().getAtomicSpecLoc(),
3341 D.getDeclSpec().getUnalignedSpecLoc());
3342}
3343
3344static std::pair<QualType, TypeSourceInfo *>
3345InventTemplateParameter(TypeProcessingState &state, QualType T,
3346 TypeSourceInfo *TrailingTSI, AutoType *Auto,
3347 InventedTemplateParameterInfo &Info) {
3348 Sema &S = state.getSema();
3349 Declarator &D = state.getDeclarator();
3350
3351 const unsigned TemplateParameterDepth = Info.AutoTemplateParameterDepth;
3352 const unsigned AutoParameterPosition = Info.TemplateParams.size();
3353 const bool IsParameterPack = D.hasEllipsis();
3354
3355 // If auto is mentioned in a lambda parameter or abbreviated function
3356 // template context, convert it to a template parameter type.
3357
3358 // Create the TemplateTypeParmDecl here to retrieve the corresponding
3359 // template parameter type. Template parameters are temporarily added
3360 // to the TU until the associated TemplateDecl is created.
3361 TemplateTypeParmDecl *InventedTemplateParam =
3362 TemplateTypeParmDecl::Create(
3363 S.Context, S.Context.getTranslationUnitDecl(),
3364 /*KeyLoc=*/D.getDeclSpec().getTypeSpecTypeLoc(),
3365 /*NameLoc=*/D.getIdentifierLoc(),
3366 TemplateParameterDepth, AutoParameterPosition,
3367 S.InventAbbreviatedTemplateParameterTypeName(
3368 D.getIdentifier(), AutoParameterPosition), false,
3369 IsParameterPack, /*HasTypeConstraint=*/Auto->isConstrained());
3370 InventedTemplateParam->setImplicit();
3371 Info.TemplateParams.push_back(InventedTemplateParam);
3372
3373 // Attach type constraints to the new parameter.
3374 if (Auto->isConstrained()) {
3375 if (TrailingTSI) {
3376 // The 'auto' appears in a trailing return type we've already built;
3377 // extract its type constraints to attach to the template parameter.
3378 AutoTypeLoc AutoLoc = TrailingTSI->getTypeLoc().getContainedAutoTypeLoc();
3379 TemplateArgumentListInfo TAL(AutoLoc.getLAngleLoc(), AutoLoc.getRAngleLoc());
3380 bool Invalid = false;
3381 for (unsigned Idx = 0; Idx < AutoLoc.getNumArgs(); ++Idx) {
3382 if (D.getEllipsisLoc().isInvalid() && !Invalid &&
3383 S.DiagnoseUnexpandedParameterPack(AutoLoc.getArgLoc(Idx),
3384 Sema::UPPC_TypeConstraint))
3385 Invalid = true;
3386 TAL.addArgument(AutoLoc.getArgLoc(Idx));
3387 }
3388
3389 if (!Invalid) {
3390 S.AttachTypeConstraint(
3391 AutoLoc.getNestedNameSpecifierLoc(), AutoLoc.getConceptNameInfo(),
3392 AutoLoc.getNamedConcept(),
3393 AutoLoc.hasExplicitTemplateArgs() ? &TAL : nullptr,
3394 InventedTemplateParam, D.getEllipsisLoc());
3395 }
3396 } else {
3397 // The 'auto' appears in the decl-specifiers; we've not finished forming
3398 // TypeSourceInfo for it yet.
3399 TemplateIdAnnotation *TemplateId = D.getDeclSpec().getRepAsTemplateId();
3400 TemplateArgumentListInfo TemplateArgsInfo;
3401 bool Invalid = false;
3402 if (TemplateId->LAngleLoc.isValid()) {
3403 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
3404 TemplateId->NumArgs);
3405 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo);
3406
3407 if (D.getEllipsisLoc().isInvalid()) {
3408 for (TemplateArgumentLoc Arg : TemplateArgsInfo.arguments()) {
3409 if (S.DiagnoseUnexpandedParameterPack(Arg,
3410 Sema::UPPC_TypeConstraint)) {
3411 Invalid = true;
3412 break;
3413 }
3414 }
3415 }
3416 }
3417 if (!Invalid) {
3418 S.AttachTypeConstraint(
3419 D.getDeclSpec().getTypeSpecScope().getWithLocInContext(S.Context),
3420 DeclarationNameInfo(DeclarationName(TemplateId->Name),
3421 TemplateId->TemplateNameLoc),
3422 cast<ConceptDecl>(TemplateId->Template.get().getAsTemplateDecl()),
3423 TemplateId->LAngleLoc.isValid() ? &TemplateArgsInfo : nullptr,
3424 InventedTemplateParam, D.getEllipsisLoc());
3425 }
3426 }
3427 }
3428
3429 // Replace the 'auto' in the function parameter with this invented
3430 // template type parameter.
3431 // FIXME: Retain some type sugar to indicate that this was written
3432 // as 'auto'?
3433 QualType Replacement(InventedTemplateParam->getTypeForDecl(), 0);
3434 QualType NewT = state.ReplaceAutoType(T, Replacement);
3435 TypeSourceInfo *NewTSI =
3436 TrailingTSI ? S.ReplaceAutoTypeSourceInfo(TrailingTSI, Replacement)
3437 : nullptr;
3438 return {NewT, NewTSI};
3439}
3440
3441static TypeSourceInfo *
3442GetTypeSourceInfoForDeclarator(TypeProcessingState &State,
3443 QualType T, TypeSourceInfo *ReturnTypeInfo);
3444
3445static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state,
3446 TypeSourceInfo *&ReturnTypeInfo) {
3447 Sema &SemaRef = state.getSema();
3448 Declarator &D = state.getDeclarator();
3449 QualType T;
3450 ReturnTypeInfo = nullptr;
3451
3452 // The TagDecl owned by the DeclSpec.
3453 TagDecl *OwnedTagDecl = nullptr;
3454
3455 switch (D.getName().getKind()) {
3456 case UnqualifiedIdKind::IK_ImplicitSelfParam:
3457 case UnqualifiedIdKind::IK_OperatorFunctionId:
3458 case UnqualifiedIdKind::IK_Identifier:
3459 case UnqualifiedIdKind::IK_LiteralOperatorId:
3460 case UnqualifiedIdKind::IK_TemplateId:
3461 T = ConvertDeclSpecToType(state);
3462
3463 if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) {
3464 OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
3465 // Owned declaration is embedded in declarator.
3466 OwnedTagDecl->setEmbeddedInDeclarator(true);
3467 }
3468 break;
3469
3470 case UnqualifiedIdKind::IK_ConstructorName:
3471 case UnqualifiedIdKind::IK_ConstructorTemplateId:
3472 case UnqualifiedIdKind::IK_DestructorName:
3473 // Constructors and destructors don't have return types. Use
3474 // "void" instead.
3475 T = SemaRef.Context.VoidTy;
3476 processTypeAttrs(state, T, TAL_DeclSpec,
3477 D.getMutableDeclSpec().getAttributes());
3478 break;
3479
3480 case UnqualifiedIdKind::IK_DeductionGuideName:
3481 // Deduction guides have a trailing return type and no type in their
3482 // decl-specifier sequence. Use a placeholder return type for now.
3483 T = SemaRef.Context.DependentTy;
3484 break;
3485
3486 case UnqualifiedIdKind::IK_ConversionFunctionId:
3487 // The result type of a conversion function is the type that it
3488 // converts to.
3489 T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId,
3490 &ReturnTypeInfo);
3491 break;
3492 }
3493
3494 // Note: We don't need to distribute declaration attributes (i.e.
3495 // D.getDeclarationAttributes()) because those are always C++11 attributes,
3496 // and those don't get distributed.
3497 distributeTypeAttrsFromDeclarator(state, T);
3498
3499 // Find the deduced type in this type. Look in the trailing return type if we
3500 // have one, otherwise in the DeclSpec type.
3501 // FIXME: The standard wording doesn't currently describe this.
3502 DeducedType *Deduced = T->getContainedDeducedType();
3503 bool DeducedIsTrailingReturnType = false;
3504 if (Deduced && isa<AutoType>(Deduced) && D.hasTrailingReturnType()) {
3505 QualType T = SemaRef.GetTypeFromParser(D.getTrailingReturnType());
3506 Deduced = T.isNull() ? nullptr : T->getContainedDeducedType();
3507 DeducedIsTrailingReturnType = true;
3508 }
3509
3510 // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context.
3511 if (Deduced) {
3512 AutoType *Auto = dyn_cast<AutoType>(Deduced);
3513 int Error = -1;
3514
3515 // Is this a 'auto' or 'decltype(auto)' type (as opposed to __auto_type or
3516 // class template argument deduction)?
3517 bool IsCXXAutoType =
3518 (Auto && Auto->getKeyword() != AutoTypeKeyword::GNUAutoType);
3519 bool IsDeducedReturnType = false;
3520
3521 switch (D.getContext()) {
3522 case DeclaratorContext::LambdaExpr:
3523 // Declared return type of a lambda-declarator is implicit and is always
3524 // 'auto'.
3525 break;
3526 case DeclaratorContext::ObjCParameter:
3527 case DeclaratorContext::ObjCResult:
3528 Error = 0;
3529 break;
3530 case DeclaratorContext::RequiresExpr:
3531 Error = 22;
3532 break;
3533 case DeclaratorContext::Prototype:
3534 case DeclaratorContext::LambdaExprParameter: {
3535 InventedTemplateParameterInfo *Info = nullptr;
3536 if (D.getContext() == DeclaratorContext::Prototype) {
3537 // With concepts we allow 'auto' in function parameters.
3538 if (!SemaRef.getLangOpts().CPlusPlus20 || !Auto ||
3539 Auto->getKeyword() != AutoTypeKeyword::Auto) {
3540 Error = 0;
3541 break;
3542 } else if (!SemaRef.getCurScope()->isFunctionDeclarationScope()) {
3543 Error = 21;
3544 break;
3545 }
3546
3547 Info = &SemaRef.InventedParameterInfos.back();
3548 } else {
3549 // In C++14, generic lambdas allow 'auto' in their parameters.
3550 if (!SemaRef.getLangOpts().CPlusPlus14 || !Auto ||
3551 Auto->getKeyword() != AutoTypeKeyword::Auto) {
3552 Error = 16;
3553 break;
3554 }
3555 Info = SemaRef.getCurLambda();
3556 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", 3556, __extension__ __PRETTY_FUNCTION__
))
;
3557 }
3558
3559 // We'll deal with inventing template parameters for 'auto' in trailing
3560 // return types when we pick up the trailing return type when processing
3561 // the function chunk.
3562 if (!DeducedIsTrailingReturnType)
3563 T = InventTemplateParameter(state, T, nullptr, Auto, *Info).first;
3564 break;
3565 }
3566 case DeclaratorContext::Member: {
3567 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static ||
3568 D.isFunctionDeclarator())
3569 break;
3570 bool Cxx = SemaRef.getLangOpts().CPlusPlus;
3571 if (isa<ObjCContainerDecl>(SemaRef.CurContext)) {
3572 Error = 6; // Interface member.
3573 } else {
3574 switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) {
3575 case TTK_Enum: llvm_unreachable("unhandled tag kind")::llvm::llvm_unreachable_internal("unhandled tag kind", "clang/lib/Sema/SemaType.cpp"
, 3575)
;
3576 case TTK_Struct: Error = Cxx ? 1 : 2; /* Struct member */ break;
3577 case TTK_Union: Error = Cxx ? 3 : 4; /* Union member */ break;
3578 case TTK_Class: Error = 5; /* Class member */ break;
3579 case TTK_Interface: Error = 6; /* Interface member */ break;
3580 }
3581 }
3582 if (D.getDeclSpec().isFriendSpecified())
3583 Error = 20; // Friend type
3584 break;
3585 }
3586 case DeclaratorContext::CXXCatch:
3587 case DeclaratorContext::ObjCCatch:
3588 Error = 7; // Exception declaration
3589 break;
3590 case DeclaratorContext::TemplateParam:
3591 if (isa<DeducedTemplateSpecializationType>(Deduced) &&
3592 !SemaRef.getLangOpts().CPlusPlus20)
3593 Error = 19; // Template parameter (until C++20)
3594 else if (!SemaRef.getLangOpts().CPlusPlus17)
3595 Error = 8; // Template parameter (until C++17)
3596 break;
3597 case DeclaratorContext::BlockLiteral:
3598 Error = 9; // Block literal
3599 break;
3600 case DeclaratorContext::TemplateArg:
3601 // Within a template argument list, a deduced template specialization
3602 // type will be reinterpreted as a template template argument.
3603 if (isa<DeducedTemplateSpecializationType>(Deduced) &&
3604 !D.getNumTypeObjects() &&
3605 D.getDeclSpec().getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier)
3606 break;
3607 [[fallthrough]];
3608 case DeclaratorContext::TemplateTypeArg:
3609 Error = 10; // Template type argument
3610 break;
3611 case DeclaratorContext::AliasDecl:
3612 case DeclaratorContext::AliasTemplate:
3613 Error = 12; // Type alias
3614 break;
3615 case DeclaratorContext::TrailingReturn:
3616 case DeclaratorContext::TrailingReturnVar:
3617 if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType)
3618 Error = 13; // Function return type
3619 IsDeducedReturnType = true;
3620 break;
3621 case DeclaratorContext::ConversionId:
3622 if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType)
3623 Error = 14; // conversion-type-id
3624 IsDeducedReturnType = true;
3625 break;
3626 case DeclaratorContext::FunctionalCast:
3627 if (isa<DeducedTemplateSpecializationType>(Deduced))
3628 break;
3629 if (SemaRef.getLangOpts().CPlusPlus2b && IsCXXAutoType &&
3630 !Auto->isDecltypeAuto())
3631 break; // auto(x)
3632 [[fallthrough]];
3633 case DeclaratorContext::TypeName:
3634 case DeclaratorContext::Association:
3635 Error = 15; // Generic
3636 break;
3637 case DeclaratorContext::File:
3638 case DeclaratorContext::Block:
3639 case DeclaratorContext::ForInit:
3640 case DeclaratorContext::SelectionInit:
3641 case DeclaratorContext::Condition:
3642 // FIXME: P0091R3 (erroneously) does not permit class template argument
3643 // deduction in conditions, for-init-statements, and other declarations
3644 // that are not simple-declarations.
3645 break;
3646 case DeclaratorContext::CXXNew:
3647 // FIXME: P0091R3 does not permit class template argument deduction here,
3648 // but we follow GCC and allow it anyway.
3649 if (!IsCXXAutoType && !isa<DeducedTemplateSpecializationType>(Deduced))
3650 Error = 17; // 'new' type
3651 break;
3652 case DeclaratorContext::KNRTypeList:
3653 Error = 18; // K&R function parameter
3654 break;
3655 }
3656
3657 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
3658 Error = 11;
3659
3660 // In Objective-C it is an error to use 'auto' on a function declarator
3661 // (and everywhere for '__auto_type').
3662 if (D.isFunctionDeclarator() &&
3663 (!SemaRef.getLangOpts().CPlusPlus11 || !IsCXXAutoType))
3664 Error = 13;
3665
3666 SourceRange AutoRange = D.getDeclSpec().getTypeSpecTypeLoc();
3667 if (D.getName().getKind() == UnqualifiedIdKind::IK_ConversionFunctionId)
3668 AutoRange = D.getName().getSourceRange();
3669
3670 if (Error != -1) {
3671 unsigned Kind;
3672 if (Auto) {
3673 switch (Auto->getKeyword()) {
3674 case AutoTypeKeyword::Auto: Kind = 0; break;
3675 case AutoTypeKeyword::DecltypeAuto: Kind = 1; break;
3676 case AutoTypeKeyword::GNUAutoType: Kind = 2; break;
3677 }
3678 } else {
3679 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", 3680, __extension__ __PRETTY_FUNCTION__
))
3680 "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", 3680, __extension__ __PRETTY_FUNCTION__
))
;
3681 Kind = 3;
3682 }
3683
3684 auto *DTST = dyn_cast<DeducedTemplateSpecializationType>(Deduced);
3685 TemplateName TN = DTST ? DTST->getTemplateName() : TemplateName();
3686
3687 SemaRef.Diag(AutoRange.getBegin(), diag::err_auto_not_allowed)
3688 << Kind << Error << (int)SemaRef.getTemplateNameKindForDiagnostics(TN)
3689 << QualType(Deduced, 0) << AutoRange;
3690 if (auto *TD = TN.getAsTemplateDecl())
3691 SemaRef.Diag(TD->getLocation(), diag::note_template_decl_here);
3692
3693 T = SemaRef.Context.IntTy;
3694 D.setInvalidType(true);
3695 } else if (Auto && D.getContext() != DeclaratorContext::LambdaExpr) {
3696 // If there was a trailing return type, we already got
3697 // warn_cxx98_compat_trailing_return_type in the parser.
3698 SemaRef.Diag(AutoRange.getBegin(),
3699 D.getContext() == DeclaratorContext::LambdaExprParameter
3700 ? diag::warn_cxx11_compat_generic_lambda
3701 : IsDeducedReturnType
3702 ? diag::warn_cxx11_compat_deduced_return_type
3703 : diag::warn_cxx98_compat_auto_type_specifier)
3704 << AutoRange;
3705 }
3706 }
3707
3708 if (SemaRef.getLangOpts().CPlusPlus &&
3709 OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) {
3710 // Check the contexts where C++ forbids the declaration of a new class
3711 // or enumeration in a type-specifier-seq.
3712 unsigned DiagID = 0;
3713 switch (D.getContext()) {
3714 case DeclaratorContext::TrailingReturn:
3715 case DeclaratorContext::TrailingReturnVar:
3716 // Class and enumeration definitions are syntactically not allowed in
3717 // trailing return types.
3718 llvm_unreachable("parser should not have allowed this")::llvm::llvm_unreachable_internal("parser should not have allowed this"
, "clang/lib/Sema/SemaType.cpp", 3718)
;
3719 break;
3720 case DeclaratorContext::File:
3721 case DeclaratorContext::Member:
3722 case DeclaratorContext::Block:
3723 case DeclaratorContext::ForInit:
3724 case DeclaratorContext::SelectionInit:
3725 case DeclaratorContext::BlockLiteral:
3726 case DeclaratorContext::LambdaExpr:
3727 // C++11 [dcl.type]p3:
3728 // A type-specifier-seq shall not define a class or enumeration unless
3729 // it appears in the type-id of an alias-declaration (7.1.3) that is not
3730 // the declaration of a template-declaration.
3731 case DeclaratorContext::AliasDecl:
3732 break;
3733 case DeclaratorContext::AliasTemplate:
3734 DiagID = diag::err_type_defined_in_alias_template;
3735 break;
3736 case DeclaratorContext::TypeName:
3737 case DeclaratorContext::FunctionalCast:
3738 case DeclaratorContext::ConversionId:
3739 case DeclaratorContext::TemplateParam:
3740 case DeclaratorContext::CXXNew:
3741 case DeclaratorContext::CXXCatch:
3742 case DeclaratorContext::ObjCCatch:
3743 case DeclaratorContext::TemplateArg:
3744 case DeclaratorContext::TemplateTypeArg:
3745 case DeclaratorContext::Association:
3746 DiagID = diag::err_type_defined_in_type_specifier;
3747 break;
3748 case DeclaratorContext::Prototype:
3749 case DeclaratorContext::LambdaExprParameter:
3750 case DeclaratorContext::ObjCParameter:
3751 case DeclaratorContext::ObjCResult:
3752 case DeclaratorContext::KNRTypeList:
3753 case DeclaratorContext::RequiresExpr:
3754 // C++ [dcl.fct]p6:
3755 // Types shall not be defined in return or parameter types.
3756 DiagID = diag::err_type_defined_in_param_type;
3757 break;
3758 case DeclaratorContext::Condition:
3759 // C++ 6.4p2:
3760 // The type-specifier-seq shall not contain typedef and shall not declare
3761 // a new class or enumeration.
3762 DiagID = diag::err_type_defined_in_condition;
3763 break;
3764 }
3765
3766 if (DiagID != 0) {
3767 SemaRef.Diag(OwnedTagDecl->getLocation(), DiagID)
3768 << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
3769 D.setInvalidType(true);
3770 }
3771 }
3772
3773 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", 3773, __extension__ __PRETTY_FUNCTION__
))
;
3774 return T;
3775}
3776
3777/// Produce an appropriate diagnostic for an ambiguity between a function
3778/// declarator and a C++ direct-initializer.
3779static void warnAboutAmbiguousFunction(Sema &S, Declarator &D,
3780 DeclaratorChunk &DeclType, QualType RT) {
3781 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
3782 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", 3782, __extension__ __PRETTY_FUNCTION__
))
;
3783
3784 // If the return type is void there is no ambiguity.
3785 if (RT->isVoidType())
3786 return;
3787
3788 // An initializer for a non-class type can have at most one argument.
3789 if (!RT->isRecordType() && FTI.NumParams > 1)
3790 return;
3791
3792 // An initializer for a reference must have exactly one argument.
3793 if (RT->isReferenceType() && FTI.NumParams != 1)
3794 return;
3795
3796 // Only warn if this declarator is declaring a function at block scope, and
3797 // doesn't have a storage class (such as 'extern') specified.
3798 if (!D.isFunctionDeclarator() ||
3799 D.getFunctionDefinitionKind() != FunctionDefinitionKind::Declaration ||
3800 !S.CurContext->isFunctionOrMethod() ||
3801 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_unspecified)
3802 return;
3803
3804 // Inside a condition, a direct initializer is not permitted. We allow one to
3805 // be parsed in order to give better diagnostics in condition parsing.
3806 if (D.getContext() == DeclaratorContext::Condition)
3807 return;
3808
3809 SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc);
3810
3811 S.Diag(DeclType.Loc,
3812 FTI.NumParams ? diag::warn_parens_disambiguated_as_function_declaration
3813 : diag::warn_empty_parens_are_function_decl)
3814 << ParenRange;
3815
3816 // If the declaration looks like:
3817 // T var1,
3818 // f();
3819 // and name lookup finds a function named 'f', then the ',' was
3820 // probably intended to be a ';'.
3821 if (!D.isFirstDeclarator() && D.getIdentifier()) {
3822 FullSourceLoc Comma(D.getCommaLoc(), S.SourceMgr);
3823 FullSourceLoc Name(D.getIdentifierLoc(), S.SourceMgr);
3824 if (Comma.getFileID() != Name.getFileID() ||
3825 Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) {
3826 LookupResult Result(S, D.getIdentifier(), SourceLocation(),
3827 Sema::LookupOrdinaryName);
3828 if (S.LookupName(Result, S.getCurScope()))
3829 S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call)
3830 << FixItHint::CreateReplacement(D.getCommaLoc(), ";")
3831 << D.getIdentifier();
3832 Result.suppressDiagnostics();
3833 }
3834 }
3835
3836 if (FTI.NumParams > 0) {
3837 // For a declaration with parameters, eg. "T var(T());", suggest adding
3838 // parens around the first parameter to turn the declaration into a
3839 // variable declaration.
3840 SourceRange Range = FTI.Params[0].Param->getSourceRange();
3841 SourceLocation B = Range.getBegin();
3842 SourceLocation E = S.getLocForEndOfToken(Range.getEnd());
3843 // FIXME: Maybe we should suggest adding braces instead of parens
3844 // in C++11 for classes that don't have an initializer_list constructor.
3845 S.Diag(B, diag::note_additional_parens_for_variable_declaration)
3846 << FixItHint::CreateInsertion(B, "(")
3847 << FixItHint::CreateInsertion(E, ")");
3848 } else {
3849 // For a declaration without parameters, eg. "T var();", suggest replacing
3850 // the parens with an initializer to turn the declaration into a variable
3851 // declaration.
3852 const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
3853
3854 // Empty parens mean value-initialization, and no parens mean
3855 // default initialization. These are equivalent if the default
3856 // constructor is user-provided or if zero-initialization is a
3857 // no-op.
3858 if (RD && RD->hasDefinition() &&
3859 (RD->isEmpty() || RD->hasUserProvidedDefaultConstructor()))
3860 S.Diag(DeclType.Loc, diag::note_empty_parens_default_ctor)
3861 << FixItHint::CreateRemoval(ParenRange);
3862 else {
3863 std::string Init =
3864 S.getFixItZeroInitializerForType(RT, ParenRange.getBegin());
3865 if (Init.empty() && S.LangOpts.CPlusPlus11)
3866 Init = "{}";
3867 if (!Init.empty())
3868 S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize)
3869 << FixItHint::CreateReplacement(ParenRange, Init);
3870 }
3871 }
3872}
3873
3874/// Produce an appropriate diagnostic for a declarator with top-level
3875/// parentheses.
3876static void warnAboutRedundantParens(Sema &S, Declarator &D, QualType T) {
3877 DeclaratorChunk &Paren = D.getTypeObject(D.getNumTypeObjects() - 1);
3878 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", 3879, __extension__ __PRETTY_FUNCTION__
))
3879 "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", 3879, __extension__ __PRETTY_FUNCTION__
))
;
3880
3881 // This is a syntactic check; we're not interested in cases that arise
3882 // during template instantiation.
3883 if (S.inTemplateInstantiation())
3884 return;
3885
3886 // Check whether this could be intended to be a construction of a temporary
3887 // object in C++ via a function-style cast.
3888 bool CouldBeTemporaryObject =
3889 S.getLangOpts().CPlusPlus && D.isExpressionContext() &&
3890 !D.isInvalidType() && D.getIdentifier() &&
3891 D.getDeclSpec().getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier &&
3892 (T->isRecordType() || T->isDependentType()) &&
3893 D.getDeclSpec().getTypeQualifiers() == 0 && D.isFirstDeclarator();
3894
3895 bool StartsWithDeclaratorId = true;
3896 for (auto &C : D.type_objects()) {
3897 switch (C.Kind) {
3898 case DeclaratorChunk::Paren:
3899 if (&C == &Paren)
3900 continue;
3901 [[fallthrough]];
3902 case DeclaratorChunk::Pointer:
3903 StartsWithDeclaratorId = false;
3904 continue;
3905
3906 case DeclaratorChunk::Array:
3907 if (!C.Arr.NumElts)
3908 CouldBeTemporaryObject = false;
3909 continue;
3910
3911 case DeclaratorChunk::Reference:
3912 // FIXME: Suppress the warning here if there is no initializer; we're
3913 // going to give an error anyway.
3914 // We assume that something like 'T (&x) = y;' is highly likely to not
3915 // be intended to be a temporary object.
3916 CouldBeTemporaryObject = false;
3917 StartsWithDeclaratorId = false;
3918 continue;
3919
3920 case DeclaratorChunk::Function:
3921 // In a new-type-id, function chunks require parentheses.
3922 if (D.getContext() == DeclaratorContext::CXXNew)
3923 return;
3924 // FIXME: "A(f())" deserves a vexing-parse warning, not just a
3925 // redundant-parens warning, but we don't know whether the function
3926 // chunk was syntactically valid as an expression here.
3927 CouldBeTemporaryObject = false;
3928 continue;
3929
3930 case DeclaratorChunk::BlockPointer:
3931 case DeclaratorChunk::MemberPointer:
3932 case DeclaratorChunk::Pipe:
3933 // These cannot appear in expressions.
3934 CouldBeTemporaryObject = false;
3935 StartsWithDeclaratorId = false;
3936 continue;
3937 }
3938 }
3939
3940 // FIXME: If there is an initializer, assume that this is not intended to be
3941 // a construction of a temporary object.
3942
3943 // Check whether the name has already been declared; if not, this is not a
3944 // function-style cast.
3945 if (CouldBeTemporaryObject) {
3946 LookupResult Result(S, D.getIdentifier(), SourceLocation(),
3947 Sema::LookupOrdinaryName);
3948 if (!S.LookupName(Result, S.getCurScope()))
3949 CouldBeTemporaryObject = false;
3950 Result.suppressDiagnostics();
3951 }
3952
3953 SourceRange ParenRange(Paren.Loc, Paren.EndLoc);
3954
3955 if (!CouldBeTemporaryObject) {
3956 // If we have A (::B), the parentheses affect the meaning of the program.
3957 // Suppress the warning in that case. Don't bother looking at the DeclSpec
3958 // here: even (e.g.) "int ::x" is visually ambiguous even though it's
3959 // formally unambiguous.
3960 if (StartsWithDeclaratorId && D.getCXXScopeSpec().isValid()) {
3961 for (NestedNameSpecifier *NNS = D.getCXXScopeSpec().getScopeRep(); NNS;
3962 NNS = NNS->getPrefix()) {
3963 if (NNS->getKind() == NestedNameSpecifier::Global)
3964 return;
3965 }
3966 }
3967
3968 S.Diag(Paren.Loc, diag::warn_redundant_parens_around_declarator)
3969 << ParenRange << FixItHint::CreateRemoval(Paren.Loc)
3970 << FixItHint::CreateRemoval(Paren.EndLoc);
3971 return;
3972 }
3973
3974 S.Diag(Paren.Loc, diag::warn_parens_disambiguated_as_variable_declaration)
3975 << ParenRange << D.getIdentifier();
3976 auto *RD = T->getAsCXXRecordDecl();
3977 if (!RD || !RD->hasDefinition() || RD->hasNonTrivialDestructor())
3978 S.Diag(Paren.Loc, diag::note_raii_guard_add_name)
3979 << FixItHint::CreateInsertion(Paren.Loc, " varname") << T
3980 << D.getIdentifier();
3981 // FIXME: A cast to void is probably a better suggestion in cases where it's
3982 // valid (when there is no initializer and we're not in a condition).
3983 S.Diag(D.getBeginLoc(), diag::note_function_style_cast_add_parentheses)
3984 << FixItHint::CreateInsertion(D.getBeginLoc(), "(")
3985 << FixItHint::CreateInsertion(S.getLocForEndOfToken(D.getEndLoc()), ")");
3986 S.Diag(Paren.Loc, diag::note_remove_parens_for_variable_declaration)
3987 << FixItHint::CreateRemoval(Paren.Loc)
3988 << FixItHint::CreateRemoval(Paren.EndLoc);
3989}
3990
3991/// Helper for figuring out the default CC for a function declarator type. If
3992/// this is the outermost chunk, then we can determine the CC from the
3993/// declarator context. If not, then this could be either a member function
3994/// type or normal function type.
3995static CallingConv getCCForDeclaratorChunk(
3996 Sema &S, Declarator &D, const ParsedAttributesView &AttrList,
3997 const DeclaratorChunk::FunctionTypeInfo &FTI, unsigned ChunkIndex) {
3998 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", 3998, __extension__ __PRETTY_FUNCTION__
))
;
3999
4000 // Check for an explicit CC attribute.
4001 for (const ParsedAttr &AL : AttrList) {
4002 switch (AL.getKind()) {
4003 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
: {
4004 // Ignore attributes that don't validate or can't apply to the
4005 // function type. We'll diagnose the failure to apply them in
4006 // handleFunctionTypeAttr.
4007 CallingConv CC;
4008 if (!S.CheckCallingConvAttr(AL, CC) &&
4009 (!FTI.isVariadic || supportsVariadicCall(CC))) {
4010 return CC;
4011 }
4012 break;
4013 }
4014
4015 default:
4016 break;
4017 }
4018 }
4019
4020 bool IsCXXInstanceMethod = false;
4021
4022 if (S.getLangOpts().CPlusPlus) {
4023 // Look inwards through parentheses to see if this chunk will form a
4024 // member pointer type or if we're the declarator. Any type attributes
4025 // between here and there will override the CC we choose here.
4026 unsigned I = ChunkIndex;
4027 bool FoundNonParen = false;
4028 while (I && !FoundNonParen) {
4029 --I;
4030 if (D.getTypeObject(I).Kind != DeclaratorChunk::Paren)
4031 FoundNonParen = true;
4032 }
4033
4034 if (FoundNonParen) {
4035 // If we're not the declarator, we're a regular function type unless we're
4036 // in a member pointer.
4037 IsCXXInstanceMethod =
4038 D.getTypeObject(I).Kind == DeclaratorChunk::MemberPointer;
4039 } else if (D.getContext() == DeclaratorContext::LambdaExpr) {
4040 // This can only be a call operator for a lambda, which is an instance
4041 // method.
4042 IsCXXInstanceMethod = true;
4043 } else {
4044 // We're the innermost decl chunk, so must be a function declarator.
4045 assert(D.isFunctionDeclarator())(static_cast <bool> (D.isFunctionDeclarator()) ? void (
0) : __assert_fail ("D.isFunctionDeclarator()", "clang/lib/Sema/SemaType.cpp"
, 4045, __extension__ __PRETTY_FUNCTION__))
;
4046
4047 // If we're inside a record, we're declaring a method, but it could be
4048 // explicitly or implicitly static.
4049 IsCXXInstanceMethod =
4050 D.isFirstDeclarationOfMember() &&
4051 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
4052 !D.isStaticMember();
4053 }
4054 }
4055
4056 CallingConv CC = S.Context.getDefaultCallingConvention(FTI.isVariadic,
4057 IsCXXInstanceMethod);
4058
4059 // Attribute AT_OpenCLKernel affects the calling convention for SPIR
4060 // and AMDGPU targets, hence it cannot be treated as a calling
4061 // convention attribute. This is the simplest place to infer
4062 // calling convention for OpenCL kernels.
4063 if (S.getLangOpts().OpenCL) {
4064 for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) {
4065 if (AL.getKind() == ParsedAttr::AT_OpenCLKernel) {
4066 CC = CC_OpenCLKernel;
4067 break;
4068 }
4069 }
4070 } else if (S.getLangOpts().CUDA) {
4071 // If we're compiling CUDA/HIP code and targeting SPIR-V we need to make
4072 // sure the kernels will be marked with the right calling convention so that
4073 // they will be visible by the APIs that ingest SPIR-V.
4074 llvm::Triple Triple = S.Context.getTargetInfo().getTriple();
4075 if (Triple.getArch() == llvm::Triple::spirv32 ||
4076 Triple.getArch() == llvm::Triple::spirv64) {
4077 for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) {
4078 if (AL.getKind() == ParsedAttr::AT_CUDAGlobal) {
4079 CC = CC_OpenCLKernel;
4080 break;
4081 }
4082 }
4083 }
4084 }
4085
4086 return CC;
4087}
4088
4089namespace {
4090 /// A simple notion of pointer kinds, which matches up with the various
4091 /// pointer declarators.
4092 enum class SimplePointerKind {
4093 Pointer,
4094 BlockPointer,
4095 MemberPointer,
4096 Array,
4097 };
4098} // end anonymous namespace
4099
4100IdentifierInfo *Sema::getNullabilityKeyword(NullabilityKind nullability) {
4101 switch (nullability) {
4102 case NullabilityKind::NonNull:
4103 if (!Ident__Nonnull)
4104 Ident__Nonnull = PP.getIdentifierInfo("_Nonnull");
4105 return Ident__Nonnull;
4106
4107 case NullabilityKind::Nullable:
4108 if (!Ident__Nullable)
4109 Ident__Nullable = PP.getIdentifierInfo("_Nullable");
4110 return Ident__Nullable;
4111
4112 case NullabilityKind::NullableResult:
4113 if (!Ident__Nullable_result)
4114 Ident__Nullable_result = PP.getIdentifierInfo("_Nullable_result");
4115 return Ident__Nullable_result;
4116
4117 case NullabilityKind::Unspecified:
4118 if (!Ident__Null_unspecified)
4119 Ident__Null_unspecified = PP.getIdentifierInfo("_Null_unspecified");
4120 return Ident__Null_unspecified;
4121 }
4122 llvm_unreachable("Unknown nullability kind.")::llvm::llvm_unreachable_internal("Unknown nullability kind."
, "clang/lib/Sema/SemaType.cpp", 4122)
;
4123}
4124
4125/// Retrieve the identifier "NSError".
4126IdentifierInfo *Sema::getNSErrorIdent() {
4127 if (!Ident_NSError)
4128 Ident_NSError = PP.getIdentifierInfo("NSError");
4129
4130 return Ident_NSError;
4131}
4132
4133/// Check whether there is a nullability attribute of any kind in the given
4134/// attribute list.
4135static bool hasNullabilityAttr(const ParsedAttributesView &attrs) {
4136 for (const ParsedAttr &AL : attrs) {
4137 if (AL.getKind() == ParsedAttr::AT_TypeNonNull ||
4138 AL.getKind() == ParsedAttr::AT_TypeNullable ||
4139 AL.getKind() == ParsedAttr::AT_TypeNullableResult ||
4140 AL.getKind() == ParsedAttr::AT_TypeNullUnspecified)
4141 return true;
4142 }
4143
4144 return false;
4145}
4146
4147namespace {
4148 /// Describes the kind of a pointer a declarator describes.
4149 enum class PointerDeclaratorKind {
4150 // Not a pointer.
4151 NonPointer,
4152 // Single-level pointer.
4153 SingleLevelPointer,
4154 // Multi-level pointer (of any pointer kind).
4155 MultiLevelPointer,
4156 // CFFooRef*
4157 MaybePointerToCFRef,
4158 // CFErrorRef*
4159 CFErrorRefPointer,
4160 // NSError**
4161 NSErrorPointerPointer,
4162 };
4163
4164 /// Describes a declarator chunk wrapping a pointer that marks inference as
4165 /// unexpected.
4166 // These values must be kept in sync with diagnostics.
4167 enum class PointerWrappingDeclaratorKind {
4168 /// Pointer is top-level.
4169 None = -1,
4170 /// Pointer is an array element.
4171 Array = 0,
4172 /// Pointer is the referent type of a C++ reference.
4173 Reference = 1
4174 };
4175} // end anonymous namespace
4176
4177/// Classify the given declarator, whose type-specified is \c type, based on
4178/// what kind of pointer it refers to.
4179///
4180/// This is used to determine the default nullability.
4181static PointerDeclaratorKind
4182classifyPointerDeclarator(Sema &S, QualType type, Declarator &declarator,
4183 PointerWrappingDeclaratorKind &wrappingKind) {
4184 unsigned numNormalPointers = 0;
4185
4186 // For any dependent type, we consider it a non-pointer.
4187 if (type->isDependentType())
4188 return PointerDeclaratorKind::NonPointer;
4189
4190 // Look through the declarator chunks to identify pointers.
4191 for (unsigned i = 0, n = declarator.getNumTypeObjects(); i != n; ++i) {
4192 DeclaratorChunk &chunk = declarator.getTypeObject(i);
4193 switch (chunk.Kind) {
4194 case DeclaratorChunk::Array:
4195 if (numNormalPointers == 0)
4196 wrappingKind = PointerWrappingDeclaratorKind::Array;
4197 break;
4198
4199 case DeclaratorChunk::Function:
4200 case DeclaratorChunk::Pipe:
4201 break;
4202
4203 case DeclaratorChunk::BlockPointer:
4204 case DeclaratorChunk::MemberPointer:
4205 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
4206 : PointerDeclaratorKind::SingleLevelPointer;
4207
4208 case DeclaratorChunk::Paren:
4209 break;
4210
4211 case DeclaratorChunk::Reference:
4212 if (numNormalPointers == 0)
4213 wrappingKind = PointerWrappingDeclaratorKind::Reference;
4214 break;
4215
4216 case DeclaratorChunk::Pointer:
4217 ++numNormalPointers;
4218 if (numNormalPointers > 2)
4219 return PointerDeclaratorKind::MultiLevelPointer;
4220 break;
4221 }
4222 }
4223
4224 // Then, dig into the type specifier itself.
4225 unsigned numTypeSpecifierPointers = 0;
4226 do {
4227 // Decompose normal pointers.
4228 if (auto ptrType = type->getAs<PointerType>()) {
4229 ++numNormalPointers;
4230
4231 if (numNormalPointers > 2)
4232 return PointerDeclaratorKind::MultiLevelPointer;
4233
4234 type = ptrType->getPointeeType();
4235 ++numTypeSpecifierPointers;
4236 continue;
4237 }
4238
4239 // Decompose block pointers.
4240 if (type->getAs<BlockPointerType>()) {
4241 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
4242 : PointerDeclaratorKind::SingleLevelPointer;
4243 }
4244
4245 // Decompose member pointers.
4246 if (type->getAs<MemberPointerType>()) {
4247 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
4248 : PointerDeclaratorKind::SingleLevelPointer;
4249 }
4250
4251 // Look at Objective-C object pointers.
4252 if (auto objcObjectPtr = type->getAs<ObjCObjectPointerType>()) {
4253 ++numNormalPointers;
4254 ++numTypeSpecifierPointers;
4255
4256 // If this is NSError**, report that.
4257 if (auto objcClassDecl = objcObjectPtr->getInterfaceDecl()) {
4258 if (objcClassDecl->getIdentifier() == S.getNSErrorIdent() &&
4259 numNormalPointers == 2 && numTypeSpecifierPointers < 2) {
4260 return PointerDeclaratorKind::NSErrorPointerPointer;
4261 }
4262 }
4263
4264 break;
4265 }
4266
4267 // Look at Objective-C class types.
4268 if (auto objcClass = type->getAs<ObjCInterfaceType>()) {
4269 if (objcClass->getInterface()->getIdentifier() == S.getNSErrorIdent()) {
4270 if (numNormalPointers == 2 && numTypeSpecifierPointers < 2)
4271 return PointerDeclaratorKind::NSErrorPointerPointer;
4272 }
4273
4274 break;
4275 }
4276
4277 // If at this point we haven't seen a pointer, we won't see one.
4278 if (numNormalPointers == 0)
4279 return PointerDeclaratorKind::NonPointer;
4280
4281 if (auto recordType = type->getAs<RecordType>()) {
4282 RecordDecl *recordDecl = recordType->getDecl();
4283
4284 // If this is CFErrorRef*, report it as such.
4285 if (numNormalPointers == 2 && numTypeSpecifierPointers < 2 &&
4286 S.isCFError(recordDecl)) {
4287 return PointerDeclaratorKind::CFErrorRefPointer;
4288 }
4289 break;
4290 }
4291
4292 break;
4293 } while (true);
4294
4295 switch (numNormalPointers) {
4296 case 0:
4297 return PointerDeclaratorKind::NonPointer;
4298
4299 case 1:
4300 return PointerDeclaratorKind::SingleLevelPointer;
4301
4302 case 2:
4303 return PointerDeclaratorKind::MaybePointerToCFRef;
4304
4305 default:
4306 return PointerDeclaratorKind::MultiLevelPointer;
4307 }
4308}
4309
4310bool Sema::isCFError(RecordDecl *RD) {
4311 // If we already know about CFError, test it directly.
4312 if (CFError)
4313 return CFError == RD;
4314
4315 // Check whether this is CFError, which we identify based on its bridge to
4316 // NSError. CFErrorRef used to be declared with "objc_bridge" but is now
4317 // declared with "objc_bridge_mutable", so look for either one of the two
4318 // attributes.
4319 if (RD->getTagKind() == TTK_Struct) {
4320 IdentifierInfo *bridgedType = nullptr;
4321 if (auto bridgeAttr = RD->getAttr<ObjCBridgeAttr>())
4322 bridgedType = bridgeAttr->getBridgedType();
4323 else if (auto bridgeAttr = RD->getAttr<ObjCBridgeMutableAttr>())
4324 bridgedType = bridgeAttr->getBridgedType();
4325
4326 if (bridgedType == getNSErrorIdent()) {
4327 CFError = RD;
4328 return true;
4329 }
4330 }
4331
4332 return false;
4333}
4334
4335static FileID getNullabilityCompletenessCheckFileID(Sema &S,
4336 SourceLocation loc) {
4337 // If we're anywhere in a function, method, or closure context, don't perform
4338 // completeness checks.
4339 for (DeclContext *ctx = S.CurContext; ctx; ctx = ctx->getParent()) {
4340 if (ctx->isFunctionOrMethod())
4341 return FileID();
4342
4343 if (ctx->isFileContext())
4344 break;
4345 }
4346
4347 // We only care about the expansion location.
4348 loc = S.SourceMgr.getExpansionLoc(loc);
4349 FileID file = S.SourceMgr.getFileID(loc);
4350 if (file.isInvalid())
4351 return FileID();
4352
4353 // Retrieve file information.
4354 bool invalid = false;
4355 const SrcMgr::SLocEntry &sloc = S.SourceMgr.getSLocEntry(file, &invalid);
4356 if (invalid || !sloc.isFile())
4357 return FileID();
4358
4359 // We don't want to perform completeness checks on the main file or in
4360 // system headers.
4361 const SrcMgr::FileInfo &fileInfo = sloc.getFile();
4362 if (fileInfo.getIncludeLoc().isInvalid())
4363 return FileID();
4364 if (fileInfo.getFileCharacteristic() != SrcMgr::C_User &&
4365 S.Diags.getSuppressSystemWarnings()) {
4366 return FileID();
4367 }
4368
4369 return file;
4370}
4371
4372/// Creates a fix-it to insert a C-style nullability keyword at \p pointerLoc,
4373/// taking into account whitespace before and after.
4374template <typename DiagBuilderT>
4375static void fixItNullability(Sema &S, DiagBuilderT &Diag,
4376 SourceLocation PointerLoc,
4377 NullabilityKind Nullability) {
4378 assert(PointerLoc.isValid())(static_cast <bool> (PointerLoc.isValid()) ? void (0) :
__assert_fail ("PointerLoc.isValid()", "clang/lib/Sema/SemaType.cpp"
, 4378, __extension__ __PRETTY_FUNCTION__))
;
4379 if (PointerLoc.isMacroID())
4380 return;
4381
4382 SourceLocation FixItLoc = S.getLocForEndOfToken(PointerLoc);
4383 if (!FixItLoc.isValid() || FixItLoc == PointerLoc)
4384 return;
4385
4386 const char *NextChar = S.SourceMgr.getCharacterData(FixItLoc);
4387 if (!NextChar)
4388 return;
4389
4390 SmallString<32> InsertionTextBuf{" "};
4391 InsertionTextBuf += getNullabilitySpelling(Nullability);
4392 InsertionTextBuf += " ";
4393 StringRef InsertionText = InsertionTextBuf.str();
4394
4395 if (isWhitespace(*NextChar)) {
4396 InsertionText = InsertionText.drop_back();
4397 } else if (NextChar[-1] == '[') {
4398 if (NextChar[0] == ']')
4399 InsertionText = InsertionText.drop_back().drop_front();
4400 else
4401 InsertionText = InsertionText.drop_front();
4402 } else if (!isAsciiIdentifierContinue(NextChar[0], /*allow dollar*/ true) &&
4403 !isAsciiIdentifierContinue(NextChar[-1], /*allow dollar*/ true)) {
4404 InsertionText = InsertionText.drop_back().drop_front();
4405 }
4406
4407 Diag << FixItHint::CreateInsertion(FixItLoc, InsertionText);
4408}
4409
4410static void emitNullabilityConsistencyWarning(Sema &S,
4411 SimplePointerKind PointerKind,
4412 SourceLocation PointerLoc,
4413 SourceLocation PointerEndLoc) {
4414 assert(PointerLoc.isValid())(static_cast <bool> (PointerLoc.isValid()) ? void (0) :
__assert_fail ("PointerLoc.isValid()", "clang/lib/Sema/SemaType.cpp"
, 4414, __extension__ __PRETTY_FUNCTION__))
;
4415
4416 if (PointerKind == SimplePointerKind::Array) {
4417 S.Diag(PointerLoc, diag::warn_nullability_missing_array);
4418 } else {
4419 S.Diag(PointerLoc, diag::warn_nullability_missing)
4420 << static_cast<unsigned>(PointerKind);
4421 }
4422
4423 auto FixItLoc = PointerEndLoc.isValid() ? PointerEndLoc : PointerLoc;
4424 if (FixItLoc.isMacroID())
4425 return;
4426
4427 auto addFixIt = [&](NullabilityKind Nullability) {
4428 auto Diag = S.Diag(FixItLoc, diag::note_nullability_fix_it);
4429 Diag << static_cast<unsigned>(Nullability);
4430 Diag << static_cast<unsigned>(PointerKind);
4431 fixItNullability(S, Diag, FixItLoc, Nullability);
4432 };
4433 addFixIt(NullabilityKind::Nullable);
4434 addFixIt(NullabilityKind::NonNull);
4435}
4436
4437/// Complains about missing nullability if the file containing \p pointerLoc
4438/// has other uses of nullability (either the keywords or the \c assume_nonnull
4439/// pragma).
4440///
4441/// If the file has \e not seen other uses of nullability, this particular
4442/// pointer is saved for possible later diagnosis. See recordNullabilitySeen().
4443static void
4444checkNullabilityConsistency(Sema &S, SimplePointerKind pointerKind,
4445 SourceLocation pointerLoc,
4446 SourceLocation pointerEndLoc = SourceLocation()) {
4447 // Determine which file we're performing consistency checking for.
4448 FileID file = getNullabilityCompletenessCheckFileID(S, pointerLoc);
4449 if (file.isInvalid())
4450 return;
4451
4452 // If we haven't seen any type nullability in this file, we won't warn now
4453 // about anything.
4454 FileNullability &fileNullability = S.NullabilityMap[file];
4455 if (!fileNullability.SawTypeNullability) {
4456 // If this is the first pointer declarator in the file, and the appropriate
4457 // warning is on, record it in case we need to diagnose it retroactively.
4458 diag::kind diagKind;
4459 if (pointerKind == SimplePointerKind::Array)
4460 diagKind = diag::warn_nullability_missing_array;
4461 else
4462 diagKind = diag::warn_nullability_missing;
4463
4464 if (fileNullability.PointerLoc.isInvalid() &&
4465 !S.Context.getDiagnostics().isIgnored(diagKind, pointerLoc)) {
4466 fileNullability.PointerLoc = pointerLoc;
4467 fileNullability.PointerEndLoc = pointerEndLoc;
4468 fileNullability.PointerKind = static_cast<unsigned>(pointerKind);
4469 }
4470
4471 return;
4472 }
4473
4474 // Complain about missing nullability.
4475 emitNullabilityConsistencyWarning(S, pointerKind, pointerLoc, pointerEndLoc);
4476}
4477
4478/// Marks that a nullability feature has been used in the file containing
4479/// \p loc.
4480///
4481/// If this file already had pointer types in it that were missing nullability,
4482/// the first such instance is retroactively diagnosed.
4483///
4484/// \sa checkNullabilityConsistency
4485static void recordNullabilitySeen(Sema &S, SourceLocation loc) {
4486 FileID file = getNullabilityCompletenessCheckFileID(S, loc);
4487 if (file.isInvalid())
4488 return;
4489
4490 FileNullability &fileNullability = S.NullabilityMap[file];
4491 if (fileNullability.SawTypeNullability)
4492 return;
4493 fileNullability.SawTypeNullability = true;
4494
4495 // If we haven't seen any type nullability before, now we have. Retroactively
4496 // diagnose the first unannotated pointer, if there was one.
4497 if (fileNullability.PointerLoc.isInvalid())
4498 return;
4499
4500 auto kind = static_cast<SimplePointerKind>(fileNullability.PointerKind);
4501 emitNullabilityConsistencyWarning(S, kind, fileNullability.PointerLoc,
4502 fileNullability.PointerEndLoc);
4503}
4504
4505/// Returns true if any of the declarator chunks before \p endIndex include a
4506/// level of indirection: array, pointer, reference, or pointer-to-member.
4507///
4508/// Because declarator chunks are stored in outer-to-inner order, testing
4509/// every chunk before \p endIndex is testing all chunks that embed the current
4510/// chunk as part of their type.
4511///
4512/// It is legal to pass the result of Declarator::getNumTypeObjects() as the
4513/// end index, in which case all chunks are tested.
4514static bool hasOuterPointerLikeChunk(const Declarator &D, unsigned endIndex) {
4515 unsigned i = endIndex;
4516 while (i != 0) {
4517 // Walk outwards along the declarator chunks.
4518 --i;
4519 const DeclaratorChunk &DC = D.getTypeObject(i);
4520 switch (DC.Kind) {
4521 case DeclaratorChunk::Paren:
4522 break;
4523 case DeclaratorChunk::Array:
4524 case DeclaratorChunk::Pointer:
4525 case DeclaratorChunk::Reference:
4526 case DeclaratorChunk::MemberPointer:
4527 return true;
4528 case DeclaratorChunk::Function:
4529 case DeclaratorChunk::BlockPointer:
4530 case DeclaratorChunk::Pipe:
4531 // These are invalid anyway, so just ignore.
4532 break;
4533 }
4534 }
4535 return false;
4536}
4537
4538static bool IsNoDerefableChunk(DeclaratorChunk Chunk) {
4539 return (Chunk.Kind == DeclaratorChunk::Pointer ||
4540 Chunk.Kind == DeclaratorChunk::Array);
4541}
4542
4543template<typename AttrT>
4544static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4545 AL.setUsedAsTypeAttr();
4546 return ::new (Ctx) AttrT(Ctx, AL);
4547}
4548
4549static Attr *createNullabilityAttr(ASTContext &Ctx, ParsedAttr &Attr,
4550 NullabilityKind NK) {
4551 switch (NK) {
4552 case NullabilityKind::NonNull:
4553 return createSimpleAttr<TypeNonNullAttr>(Ctx, Attr);
4554
4555 case NullabilityKind::Nullable:
4556 return createSimpleAttr<TypeNullableAttr>(Ctx, Attr);
4557
4558 case NullabilityKind::NullableResult:
4559 return createSimpleAttr<TypeNullableResultAttr>(Ctx, Attr);
4560
4561 case NullabilityKind::Unspecified:
4562 return createSimpleAttr<TypeNullUnspecifiedAttr>(Ctx, Attr);
4563 }
4564 llvm_unreachable("unknown NullabilityKind")::llvm::llvm_unreachable_internal("unknown NullabilityKind", "clang/lib/Sema/SemaType.cpp"
, 4564)
;
4565}
4566
4567// Diagnose whether this is a case with the multiple addr spaces.
4568// Returns true if this is an invalid case.
4569// ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified
4570// by qualifiers for two or more different address spaces."
4571static bool DiagnoseMultipleAddrSpaceAttributes(Sema &S, LangAS ASOld,
4572 LangAS ASNew,
4573 SourceLocation AttrLoc) {
4574 if (ASOld != LangAS::Default) {
4575 if (ASOld != ASNew) {
4576 S.Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers);
4577 return true;
4578 }
4579 // Emit a warning if they are identical; it's likely unintended.
4580 S.Diag(AttrLoc,
4581 diag::warn_attribute_address_multiple_identical_qualifiers);
4582 }
4583 return false;
4584}
4585
4586static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
4587 QualType declSpecType,
4588 TypeSourceInfo *TInfo) {
4589 // The TypeSourceInfo that this function returns will not be a null type.
4590 // If there is an error, this function will fill in a dummy type as fallback.
4591 QualType T = declSpecType;
4592 Declarator &D = state.getDeclarator();
4593 Sema &S = state.getSema();
4594 ASTContext &Context = S.Context;
4595 const LangOptions &LangOpts = S.getLangOpts();
4596
4597 // The name we're declaring, if any.
4598 DeclarationName Name;
4599 if (D.getIdentifier())
4600 Name = D.getIdentifier();
4601
4602 // Does this declaration declare a typedef-name?
4603 bool IsTypedefName =
4604 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef ||
4605 D.getContext() == DeclaratorContext::AliasDecl ||
4606 D.getContext() == DeclaratorContext::AliasTemplate;
4607
4608 // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
4609 bool IsQualifiedFunction = T->isFunctionProtoType() &&
4610 (!T->castAs<FunctionProtoType>()->getMethodQuals().empty() ||
4611 T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None);
4612
4613 // If T is 'decltype(auto)', the only declarators we can have are parens
4614 // and at most one function declarator if this is a function declaration.
4615 // If T is a deduced class template specialization type, we can have no
4616 // declarator chunks at all.
4617 if (auto *DT = T->getAs<DeducedType>()) {
4618 const AutoType *AT = T->getAs<AutoType>();
4619 bool IsClassTemplateDeduction = isa<DeducedTemplateSpecializationType>(DT);
4620 if ((AT && AT->isDecltypeAuto()) || IsClassTemplateDeduction) {
4621 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4622 unsigned Index = E - I - 1;
4623 DeclaratorChunk &DeclChunk = D.getTypeObject(Index);
4624 unsigned DiagId = IsClassTemplateDeduction
4625 ? diag::err_deduced_class_template_compound_type
4626 : diag::err_decltype_auto_compound_type;
4627 unsigned DiagKind = 0;
4628 switch (DeclChunk.Kind) {
4629 case DeclaratorChunk::Paren:
4630 // FIXME: Rejecting this is a little silly.
4631 if (IsClassTemplateDeduction) {
4632 DiagKind = 4;
4633 break;
4634 }
4635 continue;
4636 case DeclaratorChunk::Function: {
4637 if (IsClassTemplateDeduction) {
4638 DiagKind = 3;
4639 break;
4640 }
4641 unsigned FnIndex;
4642 if (D.isFunctionDeclarationContext() &&
4643 D.isFunctionDeclarator(FnIndex) && FnIndex == Index)
4644 continue;
4645 DiagId = diag::err_decltype_auto_function_declarator_not_declaration;
4646 break;
4647 }
4648 case DeclaratorChunk::Pointer:
4649 case DeclaratorChunk::BlockPointer:
4650 case DeclaratorChunk::MemberPointer:
4651 DiagKind = 0;
4652 break;
4653 case DeclaratorChunk::Reference:
4654 DiagKind = 1;
4655 break;
4656 case DeclaratorChunk::Array:
4657 DiagKind = 2;
4658 break;
4659 case DeclaratorChunk::Pipe:
4660 break;
4661 }
4662
4663 S.Diag(DeclChunk.Loc, DiagId) << DiagKind;
4664 D.setInvalidType(true);
4665 break;
4666 }
4667 }
4668 }
4669
4670 // Determine whether we should infer _Nonnull on pointer types.
4671 Optional<NullabilityKind> inferNullability;
4672 bool inferNullabilityCS = false;
4673 bool inferNullabilityInnerOnly = false;
4674 bool inferNullabilityInnerOnlyComplete = false;
4675
4676 // Are we in an assume-nonnull region?
4677 bool inAssumeNonNullRegion = false;
4678 SourceLocation assumeNonNullLoc = S.PP.getPragmaAssumeNonNullLoc();
4679 if (assumeNonNullLoc.isValid()) {
4680 inAssumeNonNullRegion = true;
4681 recordNullabilitySeen(S, assumeNonNullLoc);
4682 }
4683
4684 // Whether to complain about missing nullability specifiers or not.
4685 enum {
4686 /// Never complain.
4687 CAMN_No,
4688 /// Complain on the inner pointers (but not the outermost
4689 /// pointer).
4690 CAMN_InnerPointers,
4691 /// Complain about any pointers that don't have nullability
4692 /// specified or inferred.
4693 CAMN_Yes
4694 } complainAboutMissingNullability = CAMN_No;
4695 unsigned NumPointersRemaining = 0;
4696 auto complainAboutInferringWithinChunk = PointerWrappingDeclaratorKind::None;
4697
4698 if (IsTypedefName) {
4699 // For typedefs, we do not infer any nullability (the default),
4700 // and we only complain about missing nullability specifiers on
4701 // inner pointers.
4702 complainAboutMissingNullability = CAMN_InnerPointers;
4703
4704 if (T->canHaveNullability(/*ResultIfUnknown*/false) &&
4705 !T->getNullability(S.Context)) {
4706 // Note that we allow but don't require nullability on dependent types.
4707 ++NumPointersRemaining;
4708 }
4709
4710 for (unsigned i = 0, n = D.getNumTypeObjects(); i != n; ++i) {
4711 DeclaratorChunk &chunk = D.getTypeObject(i);
4712 switch (chunk.Kind) {
4713 case DeclaratorChunk::Array:
4714 case DeclaratorChunk::Function:
4715 case DeclaratorChunk::Pipe:
4716 break;
4717
4718 case DeclaratorChunk::BlockPointer:
4719 case DeclaratorChunk::MemberPointer:
4720 ++NumPointersRemaining;
4721 break;
4722
4723 case DeclaratorChunk::Paren:
4724 case DeclaratorChunk::Reference:
4725 continue;
4726
4727 case DeclaratorChunk::Pointer:
4728 ++NumPointersRemaining;
4729 continue;
4730 }
4731 }
4732 } else {
4733 bool isFunctionOrMethod = false;
4734 switch (auto context = state.getDeclarator().getContext()) {
4735 case DeclaratorContext::ObjCParameter:
4736 case DeclaratorContext::ObjCResult:
4737 case DeclaratorContext::Prototype:
4738 case DeclaratorContext::TrailingReturn:
4739 case DeclaratorContext::TrailingReturnVar:
4740 isFunctionOrMethod = true;
4741 [[fallthrough]];
4742
4743 case DeclaratorContext::Member:
4744 if (state.getDeclarator().isObjCIvar() && !isFunctionOrMethod) {
4745 complainAboutMissingNullability = CAMN_No;
4746 break;
4747 }
4748
4749 // Weak properties are inferred to be nullable.
4750 if (state.getDeclarator().isObjCWeakProperty()) {
4751 // Weak properties cannot be nonnull, and should not complain about
4752 // missing nullable attributes during completeness checks.
4753 complainAboutMissingNullability = CAMN_No;
4754 if (inAssumeNonNullRegion) {
4755 inferNullability = NullabilityKind::Nullable;
4756 }
4757 break;
4758 }
4759
4760 [[fallthrough]];
4761
4762 case DeclaratorContext::File:
4763 case DeclaratorContext::KNRTypeList: {
4764 complainAboutMissingNullability = CAMN_Yes;
4765
4766 // Nullability inference depends on the type and declarator.
4767 auto wrappingKind = PointerWrappingDeclaratorKind::None;
4768 switch (classifyPointerDeclarator(S, T, D, wrappingKind)) {
4769 case PointerDeclaratorKind::NonPointer:
4770 case PointerDeclaratorKind::MultiLevelPointer:
4771 // Cannot infer nullability.
4772 break;
4773
4774 case PointerDeclaratorKind::SingleLevelPointer:
4775 // Infer _Nonnull if we are in an assumes-nonnull region.
4776 if (inAssumeNonNullRegion) {
4777 complainAboutInferringWithinChunk = wrappingKind;
4778 inferNullability = NullabilityKind::NonNull;
4779 inferNullabilityCS = (context == DeclaratorContext::ObjCParameter ||
4780 context == DeclaratorContext::ObjCResult);
4781 }
4782 break;
4783
4784 case PointerDeclaratorKind::CFErrorRefPointer:
4785 case PointerDeclaratorKind::NSErrorPointerPointer:
4786 // Within a function or method signature, infer _Nullable at both
4787 // levels.
4788 if (isFunctionOrMethod && inAssumeNonNullRegion)
4789 inferNullability = NullabilityKind::Nullable;
4790 break;
4791
4792 case PointerDeclaratorKind::MaybePointerToCFRef:
4793 if (isFunctionOrMethod) {
4794 // On pointer-to-pointer parameters marked cf_returns_retained or
4795 // cf_returns_not_retained, if the outer pointer is explicit then
4796 // infer the inner pointer as _Nullable.
4797 auto hasCFReturnsAttr =
4798 [](const ParsedAttributesView &AttrList) -> bool {
4799 return AttrList.hasAttribute(ParsedAttr::AT_CFReturnsRetained) ||
4800 AttrList.hasAttribute(ParsedAttr::AT_CFReturnsNotRetained);
4801 };
4802 if (const auto *InnermostChunk = D.getInnermostNonParenChunk()) {
4803 if (hasCFReturnsAttr(D.getDeclarationAttributes()) ||
4804 hasCFReturnsAttr(D.getAttributes()) ||
4805 hasCFReturnsAttr(InnermostChunk->getAttrs()) ||
4806 hasCFReturnsAttr(D.getDeclSpec().getAttributes())) {
4807 inferNullability = NullabilityKind::Nullable;
4808 inferNullabilityInnerOnly = true;
4809 }
4810 }
4811 }
4812 break;
4813 }
4814 break;
4815 }
4816
4817 case DeclaratorContext::ConversionId:
4818 complainAboutMissingNullability = CAMN_Yes;
4819 break;
4820
4821 case DeclaratorContext::AliasDecl:
4822 case DeclaratorContext::AliasTemplate:
4823 case DeclaratorContext::Block:
4824 case DeclaratorContext::BlockLiteral:
4825 case DeclaratorContext::Condition:
4826 case DeclaratorContext::CXXCatch:
4827 case DeclaratorContext::CXXNew:
4828 case DeclaratorContext::ForInit:
4829 case DeclaratorContext::SelectionInit:
4830 case DeclaratorContext::LambdaExpr:
4831 case DeclaratorContext::LambdaExprParameter:
4832 case DeclaratorContext::ObjCCatch:
4833 case DeclaratorContext::TemplateParam:
4834 case DeclaratorContext::TemplateArg:
4835 case DeclaratorContext::TemplateTypeArg:
4836 case DeclaratorContext::TypeName:
4837 case DeclaratorContext::FunctionalCast:
4838 case DeclaratorContext::RequiresExpr:
4839 case DeclaratorContext::Association:
4840 // Don't infer in these contexts.
4841 break;
4842 }
4843 }
4844
4845 // Local function that returns true if its argument looks like a va_list.
4846 auto isVaList = [&S](QualType T) -> bool {
4847 auto *typedefTy = T->getAs<TypedefType>();
4848 if (!typedefTy)
4849 return false;
4850 TypedefDecl *vaListTypedef = S.Context.getBuiltinVaListDecl();
4851 do {
4852 if (typedefTy->getDecl() == vaListTypedef)
4853 return true;
4854 if (auto *name = typedefTy->getDecl()->getIdentifier())
4855 if (name->isStr("va_list"))
4856 return true;
4857 typedefTy = typedefTy->desugar()->getAs<TypedefType>();
4858 } while (typedefTy);
4859 return false;
4860 };
4861
4862 // Local function that checks the nullability for a given pointer declarator.
4863 // Returns true if _Nonnull was inferred.
4864 auto inferPointerNullability =
4865 [&](SimplePointerKind pointerKind, SourceLocation pointerLoc,
4866 SourceLocation pointerEndLoc,
4867 ParsedAttributesView &attrs, AttributePool &Pool) -> ParsedAttr * {
4868 // We've seen a pointer.
4869 if (NumPointersRemaining > 0)
4870 --NumPointersRemaining;
4871
4872 // If a nullability attribute is present, there's nothing to do.
4873 if (hasNullabilityAttr(attrs))
4874 return nullptr;
4875
4876 // If we're supposed to infer nullability, do so now.
4877 if (inferNullability && !inferNullabilityInnerOnlyComplete) {
4878 ParsedAttr::Syntax syntax = inferNullabilityCS
4879 ? ParsedAttr::AS_ContextSensitiveKeyword
4880 : ParsedAttr::AS_Keyword;
4881 ParsedAttr *nullabilityAttr = Pool.create(
4882 S.getNullabilityKeyword(*inferNullability), SourceRange(pointerLoc),
4883 nullptr, SourceLocation(), nullptr, 0, syntax);
4884
4885 attrs.addAtEnd(nullabilityAttr);
4886
4887 if (inferNullabilityCS) {
4888 state.getDeclarator().getMutableDeclSpec().getObjCQualifiers()
4889 ->setObjCDeclQualifier(ObjCDeclSpec::DQ_CSNullability);
4890 }
4891
4892 if (pointerLoc.isValid() &&
4893 complainAboutInferringWithinChunk !=
4894 PointerWrappingDeclaratorKind::None) {
4895 auto Diag =
4896 S.Diag(pointerLoc, diag::warn_nullability_inferred_on_nested_type);
4897 Diag << static_cast<int>(complainAboutInferringWithinChunk);
4898 fixItNullability(S, Diag, pointerLoc, NullabilityKind::NonNull);
4899 }
4900
4901 if (inferNullabilityInnerOnly)
4902 inferNullabilityInnerOnlyComplete = true;
4903 return nullabilityAttr;
4904 }
4905
4906 // If we're supposed to complain about missing nullability, do so
4907 // now if it's truly missing.
4908 switch (complainAboutMissingNullability) {
4909 case CAMN_No:
4910 break;
4911
4912 case CAMN_InnerPointers:
4913 if (NumPointersRemaining == 0)
4914 break;
4915 [[fallthrough]];
4916
4917 case CAMN_Yes:
4918 checkNullabilityConsistency(S, pointerKind, pointerLoc, pointerEndLoc);
4919 }
4920 return nullptr;
4921 };
4922
4923 // If the type itself could have nullability but does not, infer pointer
4924 // nullability and perform consistency checking.
4925 if (S.CodeSynthesisContexts.empty()) {
4926 if (T->canHaveNullability(/*ResultIfUnknown*/false) &&
4927 !T->getNullability(S.Context)) {
4928 if (isVaList(T)) {
4929 // Record that we've seen a pointer, but do nothing else.
4930 if (NumPointersRemaining > 0)
4931 --NumPointersRemaining;
4932 } else {
4933 SimplePointerKind pointerKind = SimplePointerKind::Pointer;
4934 if (T->isBlockPointerType())
4935 pointerKind = SimplePointerKind::BlockPointer;
4936 else if (T->isMemberPointerType())
4937 pointerKind = SimplePointerKind::MemberPointer;
4938
4939 if (auto *attr = inferPointerNullability(
4940 pointerKind, D.getDeclSpec().getTypeSpecTypeLoc(),
4941 D.getDeclSpec().getEndLoc(),
4942 D.getMutableDeclSpec().getAttributes(),
4943 D.getMutableDeclSpec().getAttributePool())) {
4944 T = state.getAttributedType(
4945 createNullabilityAttr(Context, *attr, *inferNullability), T, T);
4946 }
4947 }
4948 }
4949
4950 if (complainAboutMissingNullability == CAMN_Yes &&
4951 T->isArrayType() && !T->getNullability(S.Context) && !isVaList(T) &&
4952 D.isPrototypeContext() &&
4953 !hasOuterPointerLikeChunk(D, D.getNumTypeObjects())) {
4954 checkNullabilityConsistency(S, SimplePointerKind::Array,
4955 D.getDeclSpec().getTypeSpecTypeLoc());
4956 }
4957 }
4958
4959 bool ExpectNoDerefChunk =
4960 state.getCurrentAttributes().hasAttribute(ParsedAttr::AT_NoDeref);
4961
4962 // Walk the DeclTypeInfo, building the recursive type as we go.
4963 // DeclTypeInfos are ordered from the identifier out, which is
4964 // opposite of what we want :).
4965 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
4966 unsigned chunkIndex = e - i - 1;
4967 state.setCurrentChunkIndex(chunkIndex);
4968 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
4969 IsQualifiedFunction &= DeclType.Kind == DeclaratorChunk::Paren;
4970 switch (DeclType.Kind) {
4971 case DeclaratorChunk::Paren:
4972 if (i == 0)
4973 warnAboutRedundantParens(S, D, T);
4974 T = S.BuildParenType(T);
4975 break;
4976 case DeclaratorChunk::BlockPointer:
4977 // If blocks are disabled, emit an error.
4978 if (!LangOpts.Blocks)
4979 S.Diag(DeclType.Loc, diag::err_blocks_disable) << LangOpts.OpenCL;
4980
4981 // Handle pointer nullability.
4982 inferPointerNullability(SimplePointerKind::BlockPointer, DeclType.Loc,
4983 DeclType.EndLoc, DeclType.getAttrs(),
4984 state.getDeclarator().getAttributePool());
4985
4986 T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name);
4987 if (DeclType.Cls.TypeQuals || LangOpts.OpenCL) {
4988 // OpenCL v2.0, s6.12.5 - Block variable declarations are implicitly
4989 // qualified with const.
4990 if (LangOpts.OpenCL)
4991 DeclType.Cls.TypeQuals |= DeclSpec::TQ_const;
4992 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals);
4993 }
4994 break;
4995 case DeclaratorChunk::Pointer:
4996 // Verify that we're not building a pointer to pointer to function with
4997 // exception specification.
4998 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4999 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
5000 D.setInvalidType(true);
5001 // Build the type anyway.
5002 }
5003
5004 // Handle pointer nullability
5005 inferPointerNullability(SimplePointerKind::Pointer, DeclType.Loc,
5006 DeclType.EndLoc, DeclType.getAttrs(),
5007 state.getDeclarator().getAttributePool());
5008
5009 if (LangOpts.ObjC && T->getAs<ObjCObjectType>()) {
5010 T = Context.getObjCObjectPointerType(T);
5011 if (DeclType.Ptr.TypeQuals)
5012 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
5013 break;
5014 }
5015
5016 // OpenCL v2.0 s6.9b - Pointer to image/sampler cannot be used.
5017 // OpenCL v2.0 s6.13.16.1 - Pointer to pipe cannot be used.
5018 // OpenCL v2.0 s6.12.5 - Pointers to Blocks are not allowed.
5019 if (LangOpts.OpenCL) {
5020 if (T->isImageType() || T->isSamplerT() || T->isPipeType() ||
5021 T->isBlockPointerType()) {
5022 S.Diag(D.getIdentifierLoc(), diag::err_opencl_pointer_to_type) << T;
5023 D.setInvalidType(true);
5024 }
5025 }
5026
5027 T = S.BuildPointerType(T, DeclType.Loc, Name);
5028 if (DeclType.Ptr.TypeQuals)
5029 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
5030 break;
5031 case DeclaratorChunk::Reference: {
5032 // Verify that we're not building a reference to pointer to function with
5033 // exception specification.
5034 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
5035 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
5036 D.setInvalidType(true);
5037 // Build the type anyway.
5038 }
5039 T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name);
5040
5041 if (DeclType.Ref.HasRestrict)
5042 T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict);
5043 break;
5044 }
5045 case DeclaratorChunk::Array: {
5046 // Verify that we're not building an array of pointers to function with
5047 // exception specification.
5048 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
5049 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
5050 D.setInvalidType(true);
5051 // Build the type anyway.
5052 }
5053 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
5054 Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
5055 ArrayType::ArraySizeModifier ASM;
5056 if (ATI.isStar)
5057 ASM = ArrayType::Star;
5058 else if (ATI.hasStatic)
5059 ASM = ArrayType::Static;
5060 else
5061 ASM = ArrayType::Normal;
5062 if (ASM == ArrayType::Star && !D.isPrototypeContext()) {
5063 // FIXME: This check isn't quite right: it allows star in prototypes
5064 // for function definitions, and disallows some edge cases detailed
5065 // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
5066 S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
5067 ASM = ArrayType::Normal;
5068 D.setInvalidType(true);
5069 }
5070
5071 // C99 6.7.5.2p1: The optional type qualifiers and the keyword static
5072 // shall appear only in a declaration of a function parameter with an
5073 // array type, ...
5074 if (ASM == ArrayType::Static || ATI.TypeQuals) {
5075 if (!(D.isPrototypeContext() ||
5076 D.getContext() == DeclaratorContext::KNRTypeList)) {
5077 S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype) <<
5078 (ASM == ArrayType::Static ? "'static'" : "type qualifier");
5079 // Remove the 'static' and the type qualifiers.
5080 if (ASM == ArrayType::Static)
5081 ASM = ArrayType::Normal;
5082 ATI.TypeQuals = 0;
5083 D.setInvalidType(true);
5084 }
5085
5086 // C99 6.7.5.2p1: ... and then only in the outermost array type
5087 // derivation.
5088 if (hasOuterPointerLikeChunk(D, chunkIndex)) {
5089 S.Diag(DeclType.Loc, diag::err_array_static_not_outermost) <<
5090 (ASM == ArrayType::Static ? "'static'" : "type qualifier");
5091 if (ASM == ArrayType::Static)
5092 ASM = ArrayType::Normal;
5093 ATI.TypeQuals = 0;
5094 D.setInvalidType(true);
5095 }
5096 }
5097 const AutoType *AT = T->getContainedAutoType();
5098 // Allow arrays of auto if we are a generic lambda parameter.
5099 // i.e. [](auto (&array)[5]) { return array[0]; }; OK
5100 if (AT && D.getContext() != DeclaratorContext::LambdaExprParameter) {
5101 // We've already diagnosed this for decltype(auto).
5102 if (!AT->isDecltypeAuto())
5103 S.Diag(DeclType.Loc, diag::err_illegal_decl_array_of_auto)
5104 << getPrintableNameForEntity(Name) << T;
5105 T = QualType();
5106 break;
5107 }
5108
5109 // Array parameters can be marked nullable as well, although it's not
5110 // necessary if they're marked 'static'.
5111 if (complainAboutMissingNullability == CAMN_Yes &&
5112 !hasNullabilityAttr(DeclType.getAttrs()) &&
5113 ASM != ArrayType::Static &&
5114 D.isPrototypeContext() &&
5115 !hasOuterPointerLikeChunk(D, chunkIndex)) {
5116 checkNullabilityConsistency(S, SimplePointerKind::Array, DeclType.Loc);
5117 }
5118
5119 T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals,
5120 SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
5121 break;
5122 }
5123 case DeclaratorChunk::Function: {
5124 // If the function declarator has a prototype (i.e. it is not () and
5125 // does not have a K&R-style identifier list), then the arguments are part
5126 // of the type, otherwise the argument list is ().
5127 DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
5128 IsQualifiedFunction =
5129 FTI.hasMethodTypeQualifiers() || FTI.hasRefQualifier();
5130
5131 // Check for auto functions and trailing return type and adjust the
5132 // return type accordingly.
5133 if (!D.isInvalidType()) {
5134 // trailing-return-type is only required if we're declaring a function,
5135 // and not, for instance, a pointer to a function.
5136 if (D.getDeclSpec().hasAutoTypeSpec() &&
5137 !FTI.hasTrailingReturnType() && chunkIndex == 0) {
5138 if (!S.getLangOpts().CPlusPlus14) {
5139 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
5140 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto
5141 ? diag::err_auto_missing_trailing_return
5142 : diag::err_deduced_return_type);
5143 T = Context.IntTy;
5144 D.setInvalidType(true);
5145 } else {
5146 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
5147 diag::warn_cxx11_compat_deduced_return_type);
5148 }
5149 } else if (FTI.hasTrailingReturnType()) {
5150 // T must be exactly 'auto' at this point. See CWG issue 681.
5151 if (isa<ParenType>(T)) {
5152 S.Diag(D.getBeginLoc(), diag::err_trailing_return_in_parens)
5153 << T << D.getSourceRange();
5154 D.setInvalidType(true);
5155 } else if (D.getName().getKind() ==
5156 UnqualifiedIdKind::IK_DeductionGuideName) {
5157 if (T != Context.DependentTy) {
5158 S.Diag(D.getDeclSpec().getBeginLoc(),
5159 diag::err_deduction_guide_with_complex_decl)
5160 << D.getSourceRange();
5161 D.setInvalidType(true);
5162 }
5163 } else if (D.getContext() != DeclaratorContext::LambdaExpr &&
5164 (T.hasQualifiers() || !isa<AutoType>(T) ||
5165 cast<AutoType>(T)->getKeyword() !=
5166 AutoTypeKeyword::Auto ||
5167 cast<AutoType>(T)->isConstrained())) {
5168 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
5169 diag::err_trailing_return_without_auto)
5170 << T << D.getDeclSpec().getSourceRange();
5171 D.setInvalidType(true);
5172 }
5173 T = S.GetTypeFromParser(FTI.getTrailingReturnType(), &TInfo);
5174 if (T.isNull()) {
5175 // An error occurred parsing the trailing return type.
5176 T = Context.IntTy;
5177 D.setInvalidType(true);
5178 } else if (AutoType *Auto = T->getContainedAutoType()) {
5179 // If the trailing return type contains an `auto`, we may need to
5180 // invent a template parameter for it, for cases like
5181 // `auto f() -> C auto` or `[](auto (*p) -> auto) {}`.
5182 InventedTemplateParameterInfo *InventedParamInfo = nullptr;
5183 if (D.getContext() == DeclaratorContext::Prototype)
5184 InventedParamInfo = &S.InventedParameterInfos.back();
5185 else if (D.getContext() == DeclaratorContext::LambdaExprParameter)
5186 InventedParamInfo = S.getCurLambda();
5187 if (InventedParamInfo) {
5188 std::tie(T, TInfo) = InventTemplateParameter(
5189 state, T, TInfo, Auto, *InventedParamInfo);
5190 }
5191 }
5192 } else {
5193 // This function type is not the type of the entity being declared,
5194 // so checking the 'auto' is not the responsibility of this chunk.
5195 }
5196 }
5197
5198 // C99 6.7.5.3p1: The return type may not be a function or array type.
5199 // For conversion functions, we'll diagnose this particular error later.
5200 if (!D.isInvalidType() && (T->isArrayType() || T->isFunctionType()) &&
5201 (D.getName().getKind() !=
5202 UnqualifiedIdKind::IK_ConversionFunctionId)) {
5203 unsigned diagID = diag::err_func_returning_array_function;
5204 // Last processing chunk in block context means this function chunk
5205 // represents the block.
5206 if (chunkIndex == 0 &&
5207 D.getContext() == DeclaratorContext::BlockLiteral)
5208 diagID = diag::err_block_returning_array_function;
5209 S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T;
5210 T = Context.IntTy;
5211 D.setInvalidType(true);
5212 }
5213
5214 // Do not allow returning half FP value.
5215 // FIXME: This really should be in BuildFunctionType.
5216 if (T->isHalfType()) {
5217 if (S.getLangOpts().OpenCL) {
5218 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
5219 S.getLangOpts())) {
5220 S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return)
5221 << T << 0 /*pointer hint*/;
5222 D.setInvalidType(true);
5223 }
5224 } else if (!S.getLangOpts().NativeHalfArgsAndReturns &&
5225 !S.Context.getTargetInfo().allowHalfArgsAndReturns()) {
5226 S.Diag(D.getIdentifierLoc(),
5227 diag::err_parameters_retval_cannot_have_fp16_type) << 1;
5228 D.setInvalidType(true);
5229 }
5230 }
5231
5232 if (LangOpts.OpenCL) {
5233 // OpenCL v2.0 s6.12.5 - A block cannot be the return value of a
5234 // function.
5235 if (T->isBlockPointerType() || T->isImageType() || T->isSamplerT() ||
5236 T->isPipeType()) {
5237 S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return)
5238 << T << 1 /*hint off*/;
5239 D.setInvalidType(true);
5240 }
5241 // OpenCL doesn't support variadic functions and blocks
5242 // (s6.9.e and s6.12.5 OpenCL v2.0) except for printf.
5243 // We also allow here any toolchain reserved identifiers.
5244 if (FTI.isVariadic &&
5245 !S.getOpenCLOptions().isAvailableOption(
5246 "__cl_clang_variadic_functions", S.getLangOpts()) &&
5247 !(D.getIdentifier() &&
5248 ((D.getIdentifier()->getName() == "printf" &&
5249 LangOpts.getOpenCLCompatibleVersion() >= 120) ||
5250 D.getIdentifier()->getName().startswith("__")))) {
5251 S.Diag(D.getIdentifierLoc(), diag::err_opencl_variadic_function);
5252 D.setInvalidType(true);
5253 }
5254 }
5255
5256 // Methods cannot return interface types. All ObjC objects are
5257 // passed by reference.
5258 if (T->isObjCObjectType()) {
5259 SourceLocation DiagLoc, FixitLoc;
5260 if (TInfo) {
5261 DiagLoc = TInfo->getTypeLoc().getBeginLoc();
5262 FixitLoc = S.getLocForEndOfToken(TInfo->getTypeLoc().getEndLoc());
5263 } else {
5264 DiagLoc = D.getDeclSpec().getTypeSpecTypeLoc();
5265 FixitLoc = S.getLocForEndOfToken(D.getDeclSpec().getEndLoc());
5266 }
5267 S.Diag(DiagLoc, diag::err_object_cannot_be_passed_returned_by_value)
5268 << 0 << T
5269 << FixItHint::CreateInsertion(FixitLoc, "*");
5270
5271 T = Context.getObjCObjectPointerType(T);
5272 if (TInfo) {
5273 TypeLocBuilder TLB;
5274 TLB.pushFullCopy(TInfo->getTypeLoc());
5275 ObjCObjectPointerTypeLoc TLoc = TLB.push<ObjCObjectPointerTypeLoc>(T);
5276 TLoc.setStarLoc(FixitLoc);
5277 TInfo = TLB.getTypeSourceInfo(Context, T);
5278 }
5279
5280 D.setInvalidType(true);
5281 }
5282
5283 // cv-qualifiers on return types are pointless except when the type is a
5284 // class type in C++.
5285 if ((T.getCVRQualifiers() || T->isAtomicType()) &&
5286 !(S.getLangOpts().CPlusPlus &&
5287 (T->isDependentType() || T->isRecordType()))) {
5288 if (T->isVoidType() && !S.getLangOpts().CPlusPlus &&
5289 D.getFunctionDefinitionKind() ==
5290 FunctionDefinitionKind::Definition) {
5291 // [6.9.1/3] qualified void return is invalid on a C
5292 // function definition. Apparently ok on declarations and
5293 // in C++ though (!)
5294 S.Diag(DeclType.Loc, diag::err_func_returning_qualified_void) << T;
5295 } else
5296 diagnoseRedundantReturnTypeQualifiers(S, T, D, chunkIndex);
5297
5298 // C++2a [dcl.fct]p12:
5299 // A volatile-qualified return type is deprecated
5300 if (T.isVolatileQualified() && S.getLangOpts().CPlusPlus20)
5301 S.Diag(DeclType.Loc, diag::warn_deprecated_volatile_return) << T;
5302 }
5303
5304 // Objective-C ARC ownership qualifiers are ignored on the function
5305 // return type (by type canonicalization). Complain if this attribute
5306 // was written here.
5307 if (T.getQualifiers().hasObjCLifetime()) {
5308 SourceLocation AttrLoc;
5309 if (chunkIndex + 1 < D.getNumTypeObjects()) {
5310 DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1);
5311 for (const ParsedAttr &AL : ReturnTypeChunk.getAttrs()) {
5312 if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) {
5313 AttrLoc = AL.getLoc();
5314 break;
5315 }
5316 }
5317 }
5318 if (AttrLoc.isInvalid()) {
5319 for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) {
5320 if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) {
5321 AttrLoc = AL.getLoc();
5322 break;
5323 }
5324 }
5325 }
5326
5327 if (AttrLoc.isValid()) {
5328 // The ownership attributes are almost always written via
5329 // the predefined
5330 // __strong/__weak/__autoreleasing/__unsafe_unretained.
5331 if (AttrLoc.isMacroID())
5332 AttrLoc =
5333 S.SourceMgr.getImmediateExpansionRange(AttrLoc).getBegin();
5334
5335 S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type)
5336 << T.getQualifiers().getObjCLifetime();
5337 }
5338 }
5339
5340 if (LangOpts.CPlusPlus && D.getDeclSpec().hasTagDefinition()) {
5341 // C++ [dcl.fct]p6:
5342 // Types shall not be defined in return or parameter types.
5343 TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
5344 S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
5345 << Context.getTypeDeclType(Tag);
5346 }
5347
5348 // Exception specs are not allowed in typedefs. Complain, but add it
5349 // anyway.
5350 if (IsTypedefName && FTI.getExceptionSpecType() && !LangOpts.CPlusPlus17)
5351 S.Diag(FTI.getExceptionSpecLocBeg(),
5352 diag::err_exception_spec_in_typedef)
5353 << (D.getContext() == DeclaratorContext::AliasDecl ||
5354 D.getContext() == DeclaratorContext::AliasTemplate);
5355
5356 // If we see "T var();" or "T var(T());" at block scope, it is probably
5357 // an attempt to initialize a variable, not a function declaration.
5358 if (FTI.isAmbiguous)
5359 warnAboutAmbiguousFunction(S, D, DeclType, T);
5360
5361 FunctionType::ExtInfo EI(
5362 getCCForDeclaratorChunk(S, D, DeclType.getAttrs(), FTI, chunkIndex));
5363
5364 // OpenCL disallows functions without a prototype, but it doesn't enforce
5365 // strict prototypes as in C2x because it allows a function definition to
5366 // have an identifier list. See OpenCL 3.0 6.11/g for more details.
5367 if (!FTI.NumParams && !FTI.isVariadic &&
5368 !LangOpts.requiresStrictPrototypes() && !LangOpts.OpenCL) {
5369 // Simple void foo(), where the incoming T is the result type.
5370 T = Context.getFunctionNoProtoType(T, EI);
5371 } else {
5372 // We allow a zero-parameter variadic function in C if the
5373 // function is marked with the "overloadable" attribute. Scan
5374 // for this attribute now.
5375 if (!FTI.NumParams && FTI.isVariadic && !LangOpts.CPlusPlus)
5376 if (!D.getDeclarationAttributes().hasAttribute(
5377 ParsedAttr::AT_Overloadable) &&
5378 !D.getAttributes().hasAttribute(ParsedAttr::AT_Overloadable) &&
5379 !D.getDeclSpec().getAttributes().hasAttribute(
5380 ParsedAttr::AT_Overloadable))
5381 S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_param);
5382
5383 if (FTI.NumParams && FTI.Params[0].Param == nullptr) {
5384 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function
5385 // definition.
5386 S.Diag(FTI.Params[0].IdentLoc,
5387 diag::err_ident_list_in_fn_declaration);
5388 D.setInvalidType(true);
5389 // Recover by creating a K&R-style function type, if possible.
5390 T = (!LangOpts.requiresStrictPrototypes() && !LangOpts.OpenCL)
5391 ? Context.getFunctionNoProtoType(T, EI)
5392 : Context.IntTy;
5393 break;
5394 }
5395
5396 FunctionProtoType::ExtProtoInfo EPI;
5397 EPI.ExtInfo = EI;
5398 EPI.Variadic = FTI.isVariadic;
5399 EPI.EllipsisLoc = FTI.getEllipsisLoc();
5400 EPI.HasTrailingReturn = FTI.hasTrailingReturnType();
5401 EPI.TypeQuals.addCVRUQualifiers(
5402 FTI.MethodQualifiers ? FTI.MethodQualifiers->getTypeQualifiers()
5403 : 0);
5404 EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None
5405 : FTI.RefQualifierIsLValueRef? RQ_LValue
5406 : RQ_RValue;
5407
5408 // Otherwise, we have a function with a parameter list that is
5409 // potentially variadic.
5410 SmallVector<QualType, 16> ParamTys;
5411 ParamTys.reserve(FTI.NumParams);
5412
5413 SmallVector<FunctionProtoType::ExtParameterInfo, 16>
5414 ExtParameterInfos(FTI.NumParams);
5415 bool HasAnyInterestingExtParameterInfos = false;
5416
5417 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
5418 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
5419 QualType ParamTy = Param->getType();
5420 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", 5420, __extension__ __PRETTY_FUNCTION__
))
;
5421
5422 // Look for 'void'. void is allowed only as a single parameter to a
5423 // function with no other parameters (C99 6.7.5.3p10). We record
5424 // int(void) as a FunctionProtoType with an empty parameter list.
5425 if (ParamTy->isVoidType()) {
5426 // If this is something like 'float(int, void)', reject it. 'void'
5427 // is an incomplete type (C99 6.2.5p19) and function decls cannot
5428 // have parameters of incomplete type.
5429 if (FTI.NumParams != 1 || FTI.isVariadic) {
5430 S.Diag(FTI.Params[i].IdentLoc, diag::err_void_only_param);
5431 ParamTy = Context.IntTy;
5432 Param->setType(ParamTy);
5433 } else if (FTI.Params[i].Ident) {
5434 // Reject, but continue to parse 'int(void abc)'.
5435 S.Diag(FTI.Params[i].IdentLoc, diag::err_param_with_void_type);
5436 ParamTy = Context.IntTy;
5437 Param->setType(ParamTy);
5438 } else {
5439 // Reject, but continue to parse 'float(const void)'.
5440 if (ParamTy.hasQualifiers())
5441 S.Diag(DeclType.Loc, diag::err_void_param_qualified);
5442
5443 // Do not add 'void' to the list.
5444 break;
5445 }
5446 } else if (ParamTy->isHalfType()) {
5447 // Disallow half FP parameters.
5448 // FIXME: This really should be in BuildFunctionType.
5449 if (S.getLangOpts().OpenCL) {
5450 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
5451 S.getLangOpts())) {
5452 S.Diag(Param->getLocation(), diag::err_opencl_invalid_param)
5453 << ParamTy << 0;
5454 D.setInvalidType();
5455 Param->setInvalidDecl();
5456 }
5457 } else if (!S.getLangOpts().NativeHalfArgsAndReturns &&
5458 !S.Context.getTargetInfo().allowHalfArgsAndReturns()) {
5459 S.Diag(Param->getLocation(),
5460 diag::err_parameters_retval_cannot_have_fp16_type) << 0;
5461 D.setInvalidType();
5462 }
5463 } else if (!FTI.hasPrototype) {
5464 if (Context.isPromotableIntegerType(ParamTy)) {
5465 ParamTy = Context.getPromotedIntegerType(ParamTy);
5466 Param->setKNRPromoted(true);
5467 } else if (const BuiltinType *BTy = ParamTy->getAs<BuiltinType>()) {
5468 if (BTy->getKind() == BuiltinType::Float) {
5469 ParamTy = Context.DoubleTy;
5470 Param->setKNRPromoted(true);
5471 }
5472 }
5473 } else if (S.getLangOpts().OpenCL && ParamTy->isBlockPointerType()) {
5474 // OpenCL 2.0 s6.12.5: A block cannot be a parameter of a function.
5475 S.Diag(Param->getLocation(), diag::err_opencl_invalid_param)
5476 << ParamTy << 1 /*hint off*/;
5477 D.setInvalidType();
5478 }
5479
5480 if (LangOpts.ObjCAutoRefCount && Param->hasAttr<NSConsumedAttr>()) {
5481 ExtParameterInfos[i] = ExtParameterInfos[i].withIsConsumed(true);
5482 HasAnyInterestingExtParameterInfos = true;
5483 }
5484
5485 if (auto attr = Param->getAttr<ParameterABIAttr>()) {
5486 ExtParameterInfos[i] =
5487 ExtParameterInfos[i].withABI(attr->getABI());
5488 HasAnyInterestingExtParameterInfos = true;
5489 }
5490
5491 if (Param->hasAttr<PassObjectSizeAttr>()) {
5492 ExtParameterInfos[i] = ExtParameterInfos[i].withHasPassObjectSize();
5493 HasAnyInterestingExtParameterInfos = true;
5494 }
5495
5496 if (Param->hasAttr<NoEscapeAttr>()) {
5497 ExtParameterInfos[i] = ExtParameterInfos[i].withIsNoEscape(true);
5498 HasAnyInterestingExtParameterInfos = true;
5499 }
5500
5501 ParamTys.push_back(ParamTy);
5502 }
5503
5504 if (HasAnyInterestingExtParameterInfos) {
5505 EPI.ExtParameterInfos = ExtParameterInfos.data();
5506 checkExtParameterInfos(S, ParamTys, EPI,
5507 [&](unsigned i) { return FTI.Params[i].Param->getLocation(); });
5508 }
5509
5510 SmallVector<QualType, 4> Exceptions;
5511 SmallVector<ParsedType, 2> DynamicExceptions;
5512 SmallVector<SourceRange, 2> DynamicExceptionRanges;
5513 Expr *NoexceptExpr = nullptr;
5514
5515 if (FTI.getExceptionSpecType() == EST_Dynamic) {
5516 // FIXME: It's rather inefficient to have to split into two vectors
5517 // here.
5518 unsigned N = FTI.getNumExceptions();
5519 DynamicExceptions.reserve(N);
5520 DynamicExceptionRanges.reserve(N);
5521 for (unsigned I = 0; I != N; ++I) {
5522 DynamicExceptions.push_back(FTI.Exceptions[I].Ty);
5523 DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range);
5524 }
5525 } else if (isComputedNoexcept(FTI.getExceptionSpecType())) {
5526 NoexceptExpr = FTI.NoexceptExpr;
5527 }
5528
5529 S.checkExceptionSpecification(D.isFunctionDeclarationContext(),
5530 FTI.getExceptionSpecType(),
5531 DynamicExceptions,
5532 DynamicExceptionRanges,
5533 NoexceptExpr,
5534 Exceptions,
5535 EPI.ExceptionSpec);
5536
5537 // FIXME: Set address space from attrs for C++ mode here.
5538 // OpenCLCPlusPlus: A class member function has an address space.
5539 auto IsClassMember = [&]() {
5540 return (!state.getDeclarator().getCXXScopeSpec().isEmpty() &&
5541 state.getDeclarator()
5542 .getCXXScopeSpec()
5543 .getScopeRep()
5544 ->getKind() == NestedNameSpecifier::TypeSpec) ||
5545 state.getDeclarator().getContext() ==
5546 DeclaratorContext::Member ||
5547 state.getDeclarator().getContext() ==
5548 DeclaratorContext::LambdaExpr;
5549 };
5550
5551 if (state.getSema().getLangOpts().OpenCLCPlusPlus && IsClassMember()) {
5552 LangAS ASIdx = LangAS::Default;
5553 // Take address space attr if any and mark as invalid to avoid adding
5554 // them later while creating QualType.
5555 if (FTI.MethodQualifiers)
5556 for (ParsedAttr &attr : FTI.MethodQualifiers->getAttributes()) {
5557 LangAS ASIdxNew = attr.asOpenCLLangAS();
5558 if (DiagnoseMultipleAddrSpaceAttributes(S, ASIdx, ASIdxNew,
5559 attr.getLoc()))
5560 D.setInvalidType(true);
5561 else
5562 ASIdx = ASIdxNew;
5563 }
5564 // If a class member function's address space is not set, set it to
5565 // __generic.
5566 LangAS AS =
5567 (ASIdx == LangAS::Default ? S.getDefaultCXXMethodAddrSpace()
5568 : ASIdx);
5569 EPI.TypeQuals.addAddressSpace(AS);
5570 }
5571 T = Context.getFunctionType(T, ParamTys, EPI);
5572 }
5573 break;
5574 }
5575 case DeclaratorChunk::MemberPointer: {
5576 // The scope spec must refer to a class, or be dependent.
5577 CXXScopeSpec &SS = DeclType.Mem.Scope();
5578 QualType ClsType;
5579
5580 // Handle pointer nullability.
5581 inferPointerNullability(SimplePointerKind::MemberPointer, DeclType.Loc,
5582 DeclType.EndLoc, DeclType.getAttrs(),
5583 state.getDeclarator().getAttributePool());
5584
5585 if (SS.isInvalid()) {
5586 // Avoid emitting extra errors if we already errored on the scope.
5587 D.setInvalidType(true);
5588 } else if (S.isDependentScopeSpecifier(SS) ||
5589 isa_and_nonnull<CXXRecordDecl>(S.computeDeclContext(SS))) {
5590 NestedNameSpecifier *NNS = SS.getScopeRep();
5591 NestedNameSpecifier *NNSPrefix = NNS->getPrefix();
5592 switch (NNS->getKind()) {
5593 case NestedNameSpecifier::Identifier:
5594 ClsType = Context.getDependentNameType(ETK_None, NNSPrefix,
5595 NNS->getAsIdentifier());
5596 break;
5597
5598 case NestedNameSpecifier::Namespace:
5599 case NestedNameSpecifier::NamespaceAlias:
5600 case NestedNameSpecifier::Global:
5601 case NestedNameSpecifier::Super:
5602 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", 5602)
;
5603
5604 case NestedNameSpecifier::TypeSpec:
5605 case NestedNameSpecifier::TypeSpecWithTemplate:
5606 ClsType = QualType(NNS->getAsType(), 0);
5607 // Note: if the NNS has a prefix and ClsType is a nondependent
5608 // TemplateSpecializationType, then the NNS prefix is NOT included
5609 // in ClsType; hence we wrap ClsType into an ElaboratedType.
5610 // NOTE: in particular, no wrap occurs if ClsType already is an
5611 // Elaborated, DependentName, or DependentTemplateSpecialization.
5612 if (isa<TemplateSpecializationType>(NNS->getAsType()))
5613 ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType);
5614 break;
5615 }
5616 } else {
5617 S.Diag(DeclType.Mem.Scope().getBeginLoc(),
5618 diag::err_illegal_decl_mempointer_in_nonclass)
5619 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
5620 << DeclType.Mem.Scope().getRange();
5621 D.setInvalidType(true);
5622 }
5623
5624 if (!ClsType.isNull())
5625 T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc,
5626 D.getIdentifier());
5627 if (T.isNull()) {
5628 T = Context.IntTy;
5629 D.setInvalidType(true);
5630 } else if (DeclType.Mem.TypeQuals) {
5631 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals);
5632 }
5633 break;
5634 }
5635
5636 case DeclaratorChunk::Pipe: {
5637 T = S.BuildReadPipeType(T, DeclType.Loc);
5638 processTypeAttrs(state, T, TAL_DeclSpec,
5639 D.getMutableDeclSpec().getAttributes());
5640 break;
5641 }
5642 }
5643
5644 if (T.isNull()) {
5645 D.setInvalidType(true);
5646 T = Context.IntTy;
5647 }
5648
5649 // See if there are any attributes on this declarator chunk.
5650 processTypeAttrs(state, T, TAL_DeclChunk, DeclType.getAttrs());
5651
5652 if (DeclType.Kind != DeclaratorChunk::Paren) {
5653 if (ExpectNoDerefChunk && !IsNoDerefableChunk(DeclType))
5654 S.Diag(DeclType.Loc, diag::warn_noderef_on_non_pointer_or_array);
5655
5656 ExpectNoDerefChunk = state.didParseNoDeref();
5657 }
5658 }
5659
5660 if (ExpectNoDerefChunk)
5661 S.Diag(state.getDeclarator().getBeginLoc(),
5662 diag::warn_noderef_on_non_pointer_or_array);
5663
5664 // GNU warning -Wstrict-prototypes
5665 // Warn if a function declaration or definition is without a prototype.
5666 // This warning is issued for all kinds of unprototyped function
5667 // declarations (i.e. function type typedef, function pointer etc.)
5668 // C99 6.7.5.3p14:
5669 // The empty list in a function declarator that is not part of a definition
5670 // of that function specifies that no information about the number or types
5671 // of the parameters is supplied.
5672 // See ActOnFinishFunctionBody() and MergeFunctionDecl() for handling of
5673 // function declarations whose behavior changes in C2x.
5674 if (!LangOpts.requiresStrictPrototypes()) {
5675 bool IsBlock = false;
5676 for (const DeclaratorChunk &DeclType : D.type_objects()) {
5677 switch (DeclType.Kind) {
5678 case DeclaratorChunk::BlockPointer:
5679 IsBlock = true;
5680 break;
5681 case DeclaratorChunk::Function: {
5682 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
5683 // We suppress the warning when there's no LParen location, as this
5684 // indicates the declaration was an implicit declaration, which gets
5685 // warned about separately via -Wimplicit-function-declaration. We also
5686 // suppress the warning when we know the function has a prototype.
5687 if (!FTI.hasPrototype && FTI.NumParams == 0 && !FTI.isVariadic &&
5688 FTI.getLParenLoc().isValid())
5689 S.Diag(DeclType.Loc, diag::warn_strict_prototypes)
5690 << IsBlock
5691 << FixItHint::CreateInsertion(FTI.getRParenLoc(), "void");
5692 IsBlock = false;
5693 break;
5694 }
5695 default:
5696 break;
5697 }
5698 }
5699 }
5700
5701 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", 5701, __extension__ __PRETTY_FUNCTION__
))
;
5702
5703 if (LangOpts.CPlusPlus && T->isFunctionType()) {
5704 const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
5705 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", 5705, __extension__ __PRETTY_FUNCTION__
))
;
5706
5707 // C++ 8.3.5p4:
5708 // A cv-qualifier-seq shall only be part of the function type
5709 // for a nonstatic member function, the function type to which a pointer
5710 // to member refers, or the top-level function type of a function typedef
5711 // declaration.
5712 //
5713 // Core issue 547 also allows cv-qualifiers on function types that are
5714 // top-level template type arguments.
5715 enum { NonMember, Member, DeductionGuide } Kind = NonMember;
5716 if (D.getName().getKind() == UnqualifiedIdKind::IK_DeductionGuideName)
5717 Kind = DeductionGuide;
5718 else if (!D.getCXXScopeSpec().isSet()) {
5719 if ((D.getContext() == DeclaratorContext::Member ||
5720 D.getContext() == DeclaratorContext::LambdaExpr) &&
5721 !D.getDeclSpec().isFriendSpecified())
5722 Kind = Member;
5723 } else {
5724 DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec());
5725 if (!DC || DC->isRecord())
5726 Kind = Member;
5727 }
5728
5729 // C++11 [dcl.fct]p6 (w/DR1417):
5730 // An attempt to specify a function type with a cv-qualifier-seq or a
5731 // ref-qualifier (including by typedef-name) is ill-formed unless it is:
5732 // - the function type for a non-static member function,
5733 // - the function type to which a pointer to member refers,
5734 // - the top-level function type of a function typedef declaration or
5735 // alias-declaration,
5736 // - the type-id in the default argument of a type-parameter, or
5737 // - the type-id of a template-argument for a type-parameter
5738 //
5739 // FIXME: Checking this here is insufficient. We accept-invalid on:
5740 //
5741 // template<typename T> struct S { void f(T); };
5742 // S<int() const> s;
5743 //
5744 // ... for instance.
5745 if (IsQualifiedFunction &&
5746 !(Kind == Member &&
5747 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) &&
5748 !IsTypedefName && D.getContext() != DeclaratorContext::TemplateArg &&
5749 D.getContext() != DeclaratorContext::TemplateTypeArg) {
5750 SourceLocation Loc = D.getBeginLoc();
5751 SourceRange RemovalRange;
5752 unsigned I;
5753 if (D.isFunctionDeclarator(I)) {
5754 SmallVector<SourceLocation, 4> RemovalLocs;
5755 const DeclaratorChunk &Chunk = D.getTypeObject(I);
5756 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", 5756, __extension__ __PRETTY_FUNCTION__
))
;
5757
5758 if (Chunk.Fun.hasRefQualifier())
5759 RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc());
5760
5761 if (Chunk.Fun.hasMethodTypeQualifiers())
5762 Chunk.Fun.MethodQualifiers->forEachQualifier(
5763 [&](DeclSpec::TQ TypeQual, StringRef QualName,
5764 SourceLocation SL) { RemovalLocs.push_back(SL); });
5765
5766 if (!RemovalLocs.empty()) {
5767 llvm::sort(RemovalLocs,
5768 BeforeThanCompare<SourceLocation>(S.getSourceManager()));
5769 RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back());
5770 Loc = RemovalLocs.front();
5771 }
5772 }
5773
5774 S.Diag(Loc, diag::err_invalid_qualified_function_type)
5775 << Kind << D.isFunctionDeclarator() << T
5776 << getFunctionQualifiersAsString(FnTy)
5777 << FixItHint::CreateRemoval(RemovalRange);
5778
5779 // Strip the cv-qualifiers and ref-qualifiers from the type.
5780 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
5781 EPI.TypeQuals.removeCVRQualifiers();
5782 EPI.RefQualifier = RQ_None;
5783
5784 T = Context.getFunctionType(FnTy->getReturnType(), FnTy->getParamTypes(),
5785 EPI);
5786 // Rebuild any parens around the identifier in the function type.
5787 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
5788 if (D.getTypeObject(i).Kind != DeclaratorChunk::Paren)
5789 break;
5790 T = S.BuildParenType(T);
5791 }
5792 }
5793 }
5794
5795 // Apply any undistributed attributes from the declaration or declarator.
5796 ParsedAttributesView NonSlidingAttrs;
5797 for (ParsedAttr &AL : D.getDeclarationAttributes()) {
5798 if (!AL.slidesFromDeclToDeclSpecLegacyBehavior()) {
5799 NonSlidingAttrs.addAtEnd(&AL);
5800 }
5801 }
5802 processTypeAttrs(state, T, TAL_DeclName, NonSlidingAttrs);
5803 processTypeAttrs(state, T, TAL_DeclName, D.getAttributes());
5804
5805 // Diagnose any ignored type attributes.
5806 state.diagnoseIgnoredTypeAttrs(T);
5807
5808 // C++0x [dcl.constexpr]p9:
5809 // A constexpr specifier used in an object declaration declares the object
5810 // as const.
5811 if (D.getDeclSpec().getConstexprSpecifier() == ConstexprSpecKind::Constexpr &&
5812 T->isObjectType())
5813 T.addConst();
5814
5815 // C++2a [dcl.fct]p4:
5816 // A parameter with volatile-qualified type is deprecated
5817 if (T.isVolatileQualified() && S.getLangOpts().CPlusPlus20 &&
5818 (D.getContext() == DeclaratorContext::Prototype ||
5819 D.getContext() == DeclaratorContext::LambdaExprParameter))
5820 S.Diag(D.getIdentifierLoc(), diag::warn_deprecated_volatile_param) << T;
5821
5822 // If there was an ellipsis in the declarator, the declaration declares a
5823 // parameter pack whose type may be a pack expansion type.
5824 if (D.hasEllipsis()) {
5825 // C++0x [dcl.fct]p13:
5826 // A declarator-id or abstract-declarator containing an ellipsis shall
5827 // only be used in a parameter-declaration. Such a parameter-declaration
5828 // is a parameter pack (14.5.3). [...]
5829 switch (D.getContext()) {
5830 case DeclaratorContext::Prototype:
5831 case DeclaratorContext::LambdaExprParameter:
5832 case DeclaratorContext::RequiresExpr:
5833 // C++0x [dcl.fct]p13:
5834 // [...] When it is part of a parameter-declaration-clause, the
5835 // parameter pack is a function parameter pack (14.5.3). The type T
5836 // of the declarator-id of the function parameter pack shall contain
5837 // a template parameter pack; each template parameter pack in T is
5838 // expanded by the function parameter pack.
5839 //
5840 // We represent function parameter packs as function parameters whose
5841 // type is a pack expansion.
5842 if (!T->containsUnexpandedParameterPack() &&
5843 (!LangOpts.CPlusPlus20 || !T->getContainedAutoType())) {
5844 S.Diag(D.getEllipsisLoc(),
5845 diag::err_function_parameter_pack_without_parameter_packs)
5846 << T << D.getSourceRange();
5847 D.setEllipsisLoc(SourceLocation());
5848 } else {
5849 T = Context.getPackExpansionType(T, None, /*ExpectPackInType=*/false);
5850 }
5851 break;
5852 case DeclaratorContext::TemplateParam:
5853 // C++0x [temp.param]p15:
5854 // If a template-parameter is a [...] is a parameter-declaration that
5855 // declares a parameter pack (8.3.5), then the template-parameter is a
5856 // template parameter pack (14.5.3).
5857 //
5858 // Note: core issue 778 clarifies that, if there are any unexpanded
5859 // parameter packs in the type of the non-type template parameter, then
5860 // it expands those parameter packs.
5861 if (T->containsUnexpandedParameterPack())
5862 T = Context.getPackExpansionType(T, None);
5863 else
5864 S.Diag(D.getEllipsisLoc(),
5865 LangOpts.CPlusPlus11
5866 ? diag::warn_cxx98_compat_variadic_templates
5867 : diag::ext_variadic_templates);
5868 break;
5869
5870 case DeclaratorContext::File:
5871 case DeclaratorContext::KNRTypeList: