Bug Summary

File:clang/lib/Sema/SemaType.cpp
Warning:line 2654, column 37
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 -disable-llvm-verifier -discard-value-names -main-file-name SemaType.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -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 -fhalf-no-semantic-interposition -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-12/lib/clang/12.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-12~++20210105111114+53a341a61d1f/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-12~++20210105111114+53a341a61d1f/clang/lib/Sema -I /build/llvm-toolchain-snapshot-12~++20210105111114+53a341a61d1f/clang/include -I /build/llvm-toolchain-snapshot-12~++20210105111114+53a341a61d1f/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-12~++20210105111114+53a341a61d1f/build-llvm/include -I /build/llvm-toolchain-snapshot-12~++20210105111114+53a341a61d1f/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-12/lib/clang/12.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-12~++20210105111114+53a341a61d1f/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-12~++20210105111114+53a341a61d1f=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2021-01-05-120504-36406-1 -x c++ /build/llvm-toolchain-snapshot-12~++20210105111114+53a341a61d1f/clang/lib/Sema/SemaType.cpp

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