Bug Summary

File:clang/lib/Sema/SemaType.cpp
Warning:line 2636, 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 -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 CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/clang/lib/Sema -I /build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/clang/include -I /build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/build-llvm/include -I /build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/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~++20200926111128+c6c5629f2fb/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb=. -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-2020-09-26-161721-17566-1 -x c++ /build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/clang/lib/Sema/SemaType.cpp

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