Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -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 -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~++20200806111125+5446ec85070/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema -I /build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/include -I /build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/build-llvm/include -I /build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/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~++20200806111125+5446ec85070/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070=. -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-08-06-171148-17323-1 -x c++ /build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaType.cpp

/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/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~++20200806111125+5446ec85070/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~++20200806111125+5446ec85070/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~++20200806111125+5446ec85070/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~++20200806111125+5446ec85070/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~++20200806111125+5446ec85070/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~++20200806111125+5446ec85070/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~++20200806111125+5446ec85070/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~++20200806111125+5446ec85070/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~++20200806111125+5446ec85070/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~++20200806111125+5446ec85070/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~++20200806111125+5446ec85070/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~++20200806111125+5446ec85070/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>();
9
Assuming the object is a 'ObjCObjectType'
842 if (!objcObjectType || !objcObjectType->getInterface()) {
10
Assuming 'objcObjectType' is non-null
11
Assuming the condition is false
12
Taking false branch
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) {
13
Assuming 'typeParams' is non-null
14
Taking false branch
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()) {
15
Assuming the condition is false
16
Taking false branch
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) {
17
Assuming 'i' is not equal to 'n'
18
Loop condition is true. Entering loop body
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()) {
19
Assuming the condition is false
20
Taking false branch
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>())
21
Assuming the object is not a 'PackExpansionType'
22
Taking false branch
916 anyPackExpansions = true;
917
918 // Find the corresponding type parameter, if there is one.
919 ObjCTypeParamDecl *typeParam = nullptr;
920 if (!anyPackExpansions
22.1
'anyPackExpansions' is false
22.1
'anyPackExpansions' is false
) {
23
Taking true branch
921 if (i < numTypeParams) {
24
Assuming 'i' is < 'numTypeParams'
25
Taking true branch
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>()) {
26
Assuming the object is a 'ObjCObjectPointerType'
27
Assuming 'typeArgObjC' is non-null
28
Taking true branch
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) {
29
Assuming 'typeParam' is non-null
30
Taking false branch
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~++20200806111125+5446ec85070/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>();
31
Assuming the object is not a 'ObjCObjectPointerType'
32
'boundObjC' initialized to a null pointer value
953
954 // Determine whether the type argument is substitutable for the bound.
955 if (typeArgObjC->isObjCIdType()) {
33
Calling 'ObjCObjectPointerType::isObjCIdType'
38
Returning from 'ObjCObjectPointerType::isObjCIdType'
39
Taking true branch
956 // When the type argument is 'id', the only acceptable type
957 // parameter bound is 'id'.
958 if (boundObjC->isObjCIdType())
40
Called C++ object pointer is null
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~++20200806111125+5446ec85070/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()) {
6
Assuming the condition is true
7
Taking true branch
1077 Result = applyObjCTypeArgs(*this, Loc, Result, TypeArgs,
8
Calling 'applyObjCTypeArgs'
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())
1
Taking false branch
1154 return true;
1155
1156 // Handle missing type-source info.
1157 if (!BaseTypeInfo
1.1
'BaseTypeInfo' is null
1.1
'BaseTypeInfo' is null
)
2
Taking true branch
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) {
3
Assuming 'i' is equal to 'n'
4
Loop condition is false. Execution continues on line 1175
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~++20200806111125+5446ec85070/clang/lib/Sema/SemaType.cpp"
, 1170, __PRETTY_FUNCTION__))
;
1171 ActualTypeArgInfos.push_back(TypeArgInfo);
1172 }
1173
1174 // Build the object type.
1175 QualType Result = BuildObjCObjectType(
5
Calling 'Sema::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~++20200806111125+5446ec85070/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~++20200806111125+5446ec85070/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~++20200806111125+5446ec85070/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~++20200806111125+5446ec85070/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~++20200806111125+5446ec85070/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~++20200806111125+5446ec85070/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~++20200806111125+5446ec85070/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~++20200806111125+5446ec85070/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~++20200806111125+5446ec85070/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~++20200806111125+5446ec85070/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~++20200806111125+5446ec85070/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~++20200806111125+5446ec85070/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~++20200806111125+5446ec85070/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~++20200806111125+5446ec85070/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~++20200806111125+5446ec85070/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~++20200806111125+5446ec85070/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: Result = Context.BoolTy; break; // _Bool or bool
1547 break;
1548 case DeclSpec::TST_decimal32: // _Decimal32
1549 case DeclSpec::TST_decimal64: // _Decimal64
1550 case DeclSpec::TST_decimal128: // _Decimal128
1551 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
1552 Result = Context.IntTy;
1553 declarator.setInvalidType(true);
1554 break;
1555 case DeclSpec::TST_class:
1556 case DeclSpec::TST_enum:
1557 case DeclSpec::TST_union:
1558 case DeclSpec::TST_struct:
1559 case DeclSpec::TST_interface: {
1560 TagDecl *D = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl());
1561 if (!D) {
1562 // This can happen in C++ with ambiguous lookups.
1563 Result = Context.IntTy;
1564 declarator.setInvalidType(true);
1565 break;
1566 }
1567
1568 // If the type is deprecated or unavailable, diagnose it.
1569 S.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeNameLoc());
1570
1571 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~++20200806111125+5446ec85070/clang/lib/Sema/SemaType.cpp"
, 1572, __PRETTY_FUNCTION__))
1572 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~++20200806111125+5446ec85070/clang/lib/Sema/SemaType.cpp"
, 1572, __PRETTY_FUNCTION__))
;
1573
1574 // TypeQuals handled by caller.
1575 Result = Context.getTypeDeclType(D);
1576
1577 // In both C and C++, make an ElaboratedType.
1578 ElaboratedTypeKeyword Keyword
1579 = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType());
1580 Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result,
1581 DS.isTypeSpecOwned() ? D : nullptr);
1582 break;
1583 }
1584 case DeclSpec::TST_typename: {
1585 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~++20200806111125+5446ec85070/clang/lib/Sema/SemaType.cpp"
, 1587, __PRETTY_FUNCTION__))
1586 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~++20200806111125+5446ec85070/clang/lib/Sema/SemaType.cpp"
, 1587, __PRETTY_FUNCTION__))
1587 "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~++20200806111125+5446ec85070/clang/lib/Sema/SemaType.cpp"
, 1587, __PRETTY_FUNCTION__))
;
1588 Result = S.GetTypeFromParser(DS.getRepAsType());
1589 if (Result.isNull()) {
1590 declarator.setInvalidType(true);
1591 }
1592
1593 // TypeQuals handled by caller.
1594 break;
1595 }
1596 case DeclSpec::TST_typeofType:
1597 // FIXME: Preserve type source info.
1598 Result = S.GetTypeFromParser(DS.getRepAsType());
1599 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~++20200806111125+5446ec85070/clang/lib/Sema/SemaType.cpp"
, 1599, __PRETTY_FUNCTION__))
;
1600 if (!Result->isDependentType())
1601 if (const TagType *TT = Result->getAs<TagType>())
1602 S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc());
1603 // TypeQuals handled by caller.
1604 Result = Context.getTypeOfType(Result);
1605 break;
1606 case DeclSpec::TST_typeofExpr: {
1607 Expr *E = DS.getRepAsExpr();
1608 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~++20200806111125+5446ec85070/clang/lib/Sema/SemaType.cpp"
, 1608, __PRETTY_FUNCTION__))
;
1609 // TypeQuals handled by caller.
1610 Result = S.BuildTypeofExprType(E, DS.getTypeSpecTypeLoc());
1611 if (Result.isNull()) {
1612 Result = Context.IntTy;
1613 declarator.setInvalidType(true);
1614 }
1615 break;
1616 }
1617 case DeclSpec::TST_decltype: {
1618 Expr *E = DS.getRepAsExpr();
1619 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~++20200806111125+5446ec85070/clang/lib/Sema/SemaType.cpp"
, 1619, __PRETTY_FUNCTION__))
;
1620 // TypeQuals handled by caller.
1621 Result = S.BuildDecltypeType(E, DS.getTypeSpecTypeLoc());
1622 if (Result.isNull()) {
1623 Result = Context.IntTy;
1624 declarator.setInvalidType(true);
1625 }
1626 break;
1627 }
1628 case DeclSpec::TST_underlyingType:
1629 Result = S.GetTypeFromParser(DS.getRepAsType());
1630 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~++20200806111125+5446ec85070/clang/lib/Sema/SemaType.cpp"
, 1630, __PRETTY_FUNCTION__))
;
1631 Result = S.BuildUnaryTransformType(Result,
1632 UnaryTransformType::EnumUnderlyingType,
1633 DS.getTypeSpecTypeLoc());
1634 if (Result.isNull()) {
1635 Result = Context.IntTy;
1636 declarator.setInvalidType(true);
1637 }
1638 break;
1639
1640 case DeclSpec::TST_auto:
1641 if (DS.isConstrainedAuto()) {
1642 Result = ConvertConstrainedAutoDeclSpecToType(S, DS,
1643 AutoTypeKeyword::Auto);
1644 break;
1645 }
1646 Result = Context.getAutoType(QualType(), AutoTypeKeyword::Auto, false);
1647 break;
1648
1649 case DeclSpec::TST_auto_type:
1650 Result = Context.getAutoType(QualType(), AutoTypeKeyword::GNUAutoType, false);
1651 break;
1652
1653 case DeclSpec::TST_decltype_auto:
1654 if (DS.isConstrainedAuto()) {
1655 Result =
1656 ConvertConstrainedAutoDeclSpecToType(S, DS,
1657 AutoTypeKeyword::DecltypeAuto);
1658 break;
1659 }
1660 Result = Context.getAutoType(QualType(), AutoTypeKeyword::DecltypeAuto,
1661 /*IsDependent*/ false);
1662 break;
1663
1664 case DeclSpec::TST_unknown_anytype:
1665 Result = Context.UnknownAnyTy;
1666 break;
1667
1668 case DeclSpec::TST_atomic:
1669 Result = S.GetTypeFromParser(DS.getRepAsType());
1670 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~++20200806111125+5446ec85070/clang/lib/Sema/SemaType.cpp"
, 1670, __PRETTY_FUNCTION__))
;
1671 Result = S.BuildAtomicType(Result, DS.getTypeSpecTypeLoc());
1672 if (Result.isNull()) {
1673 Result = Context.IntTy;
1674 declarator.setInvalidType(true);
1675 }
1676 break;
1677
1678#define GENERIC_IMAGE_TYPE(ImgType, Id) \
1679 case DeclSpec::TST_##ImgType##_t: \
1680 switch (getImageAccess(DS.getAttributes())) { \
1681 case OpenCLAccessAttr::Keyword_write_only: \
1682 Result = Context.Id##WOTy; \
1683 break; \
1684 case OpenCLAccessAttr::Keyword_read_write: \
1685 Result = Context.Id##RWTy; \
1686 break; \
1687 case OpenCLAccessAttr::Keyword_read_only: \
1688 Result = Context.Id##ROTy; \
1689 break; \
1690 case OpenCLAccessAttr::SpellingNotCalculated: \
1691 llvm_unreachable("Spelling not yet calculated")::llvm::llvm_unreachable_internal("Spelling not yet calculated"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaType.cpp"
, 1691)
; \
1692 } \
1693 break;
1694#include "clang/Basic/OpenCLImageTypes.def"
1695
1696 case DeclSpec::TST_error:
1697 Result = Context.IntTy;
1698 declarator.setInvalidType(true);
1699 break;
1700 }
1701
1702 // FIXME: we want resulting declarations to be marked invalid, but claiming
1703 // the type is invalid is too strong - e.g. it causes ActOnTypeName to return
1704 // a null type.
1705 if (Result->containsErrors())
1706 declarator.setInvalidType();
1707
1708 if (S.getLangOpts().OpenCL &&
1709 S.checkOpenCLDisabledTypeDeclSpec(DS, Result))
1710 declarator.setInvalidType(true);
1711
1712 bool IsFixedPointType = DS.getTypeSpecType() == DeclSpec::TST_accum ||
1713 DS.getTypeSpecType() == DeclSpec::TST_fract;
1714
1715 // Only fixed point types can be saturated
1716 if (DS.isTypeSpecSat() && !IsFixedPointType)
1717 S.Diag(DS.getTypeSpecSatLoc(), diag::err_invalid_saturation_spec)
1718 << DS.getSpecifierName(DS.getTypeSpecType(),
1719 Context.getPrintingPolicy());
1720
1721 // Handle complex types.
1722 if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
1723 if (S.getLangOpts().Freestanding)
1724 S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
1725 Result = Context.getComplexType(Result);
1726 } else if (DS.isTypeAltiVecVector()) {
1727 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result));
1728 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~++20200806111125+5446ec85070/clang/lib/Sema/SemaType.cpp"
, 1728, __PRETTY_FUNCTION__))
;
1729 VectorType::VectorKind VecKind = VectorType::AltiVecVector;
1730 if (DS.isTypeAltiVecPixel())
1731 VecKind = VectorType::AltiVecPixel;
1732 else if (DS.isTypeAltiVecBool())
1733 VecKind = VectorType::AltiVecBool;
1734 Result = Context.getVectorType(Result, 128/typeSize, VecKind);
1735 }
1736
1737 // FIXME: Imaginary.
1738 if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary)
1739 S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported);
1740
1741 // Before we process any type attributes, synthesize a block literal
1742 // function declarator if necessary.
1743 if (declarator.getContext() == DeclaratorContext::BlockLiteralContext)
1744 maybeSynthesizeBlockSignature(state, Result);
1745
1746 // Apply any type attributes from the decl spec. This may cause the
1747 // list of type attributes to be temporarily saved while the type
1748 // attributes are pushed around.
1749 // pipe attributes will be handled later ( at GetFullTypeForDeclarator )
1750 if (!DS.isTypeSpecPipe())
1751 processTypeAttrs(state, Result, TAL_DeclSpec, DS.getAttributes());
1752
1753 // Apply const/volatile/restrict qualifiers to T.
1754 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
1755 // Warn about CV qualifiers on function types.
1756 // C99 6.7.3p8:
1757 // If the specification of a function type includes any type qualifiers,
1758 // the behavior is undefined.
1759 // C++11 [dcl.fct]p7:
1760 // The effect of a cv-qualifier-seq in a function declarator is not the
1761 // same as adding cv-qualification on top of the function type. In the
1762 // latter case, the cv-qualifiers are ignored.
1763 if (Result->isFunctionType()) {
1764 diagnoseAndRemoveTypeQualifiers(
1765 S, DS, TypeQuals, Result, DeclSpec::TQ_const | DeclSpec::TQ_volatile,
1766 S.getLangOpts().CPlusPlus
1767 ? diag::warn_typecheck_function_qualifiers_ignored
1768 : diag::warn_typecheck_function_qualifiers_unspecified);
1769 // No diagnostic for 'restrict' or '_Atomic' applied to a
1770 // function type; we'll diagnose those later, in BuildQualifiedType.
1771 }
1772
1773 // C++11 [dcl.ref]p1:
1774 // Cv-qualified references are ill-formed except when the
1775 // cv-qualifiers are introduced through the use of a typedef-name
1776 // or decltype-specifier, in which case the cv-qualifiers are ignored.
1777 //
1778 // There don't appear to be any other contexts in which a cv-qualified
1779 // reference type could be formed, so the 'ill-formed' clause here appears
1780 // to never happen.
1781 if (TypeQuals && Result->isReferenceType()) {
1782 diagnoseAndRemoveTypeQualifiers(
1783 S, DS, TypeQuals, Result,
1784 DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic,
1785 diag::warn_typecheck_reference_qualifiers);
1786 }
1787
1788 // C90 6.5.3 constraints: "The same type qualifier shall not appear more
1789 // than once in the same specifier-list or qualifier-list, either directly
1790 // or via one or more typedefs."
1791 if (!S.getLangOpts().C99 && !S.getLangOpts().CPlusPlus
1792 && TypeQuals & Result.getCVRQualifiers()) {
1793 if (TypeQuals & DeclSpec::TQ_const && Result.isConstQualified()) {
1794 S.Diag(DS.getConstSpecLoc(), diag::ext_duplicate_declspec)
1795 << "const";
1796 }
1797
1798 if (TypeQuals & DeclSpec::TQ_volatile && Result.isVolatileQualified()) {
1799 S.Diag(DS.getVolatileSpecLoc(), diag::ext_duplicate_declspec)
1800 << "volatile";
1801 }
1802
1803 // C90 doesn't have restrict nor _Atomic, so it doesn't force us to
1804 // produce a warning in this case.
1805 }
1806
1807 QualType Qualified = S.BuildQualifiedType(Result, DeclLoc, TypeQuals, &DS);
1808
1809 // If adding qualifiers fails, just use the unqualified type.
1810 if (Qualified.isNull())
1811 declarator.setInvalidType(true);
1812 else
1813 Result = Qualified;
1814 }
1815
1816 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~++20200806111125+5446ec85070/clang/lib/Sema/SemaType.cpp"
, 1816, __PRETTY_FUNCTION__))
;
1817 return Result;
1818}
1819
1820static std::string getPrintableNameForEntity(DeclarationName Entity) {
1821 if (Entity)
1822 return Entity.getAsString();
1823
1824 return "type name";
1825}
1826
1827QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1828 Qualifiers Qs, const DeclSpec *DS) {
1829 if (T.isNull())
1830 return QualType();
1831
1832 // Ignore any attempt to form a cv-qualified reference.
1833 if (T->isReferenceType()) {
1834 Qs.removeConst();
1835 Qs.removeVolatile();
1836 }
1837
1838 // Enforce C99 6.7.3p2: "Types other than pointer types derived from
1839 // object or incomplete types shall not be restrict-qualified."
1840 if (Qs.hasRestrict()) {
1841 unsigned DiagID = 0;
1842 QualType ProblemTy;
1843
1844 if (T->isAnyPointerType() || T->isReferenceType() ||
1845 T->isMemberPointerType()) {
1846 QualType EltTy;
1847 if (T->isObjCObjectPointerType())
1848 EltTy = T;
1849 else if (const MemberPointerType *PTy = T->getAs<MemberPointerType>())
1850 EltTy = PTy->getPointeeType();
1851 else
1852 EltTy = T->getPointeeType();
1853
1854 // If we have a pointer or reference, the pointee must have an object
1855 // incomplete type.
1856 if (!EltTy->isIncompleteOrObjectType()) {
1857 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1858 ProblemTy = EltTy;
1859 }
1860 } else if (!T->isDependentType()) {
1861 DiagID = diag::err_typecheck_invalid_restrict_not_pointer;
1862 ProblemTy = T;
1863 }
1864
1865 if (DiagID) {
1866 Diag(DS ? DS->getRestrictSpecLoc() : Loc, DiagID) << ProblemTy;
1867 Qs.removeRestrict();
1868 }
1869 }
1870
1871 return Context.getQualifiedType(T, Qs);
1872}
1873
1874QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1875 unsigned CVRAU, const DeclSpec *DS) {
1876 if (T.isNull())
1877 return QualType();
1878
1879 // Ignore any attempt to form a cv-qualified reference.
1880 if (T->isReferenceType())
1881 CVRAU &=
1882 ~(DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic);
1883
1884 // Convert from DeclSpec::TQ to Qualifiers::TQ by just dropping TQ_atomic and
1885 // TQ_unaligned;
1886 unsigned CVR = CVRAU & ~(DeclSpec::TQ_atomic | DeclSpec::TQ_unaligned);
1887
1888 // C11 6.7.3/5:
1889 // If the same qualifier appears more than once in the same
1890 // specifier-qualifier-list, either directly or via one or more typedefs,
1891 // the behavior is the same as if it appeared only once.
1892 //
1893 // It's not specified what happens when the _Atomic qualifier is applied to
1894 // a type specified with the _Atomic specifier, but we assume that this
1895 // should be treated as if the _Atomic qualifier appeared multiple times.
1896 if (CVRAU & DeclSpec::TQ_atomic && !T->isAtomicType()) {
1897 // C11 6.7.3/5:
1898 // If other qualifiers appear along with the _Atomic qualifier in a
1899 // specifier-qualifier-list, the resulting type is the so-qualified
1900 // atomic type.
1901 //
1902 // Don't need to worry about array types here, since _Atomic can't be
1903 // applied to such types.
1904 SplitQualType Split = T.getSplitUnqualifiedType();
1905 T = BuildAtomicType(QualType(Split.Ty, 0),
1906 DS ? DS->getAtomicSpecLoc() : Loc);
1907 if (T.isNull())
1908 return T;
1909 Split.Quals.addCVRQualifiers(CVR);
1910 return BuildQualifiedType(T, Loc, Split.Quals);
1911 }
1912
1913 Qualifiers Q = Qualifiers::fromCVRMask(CVR);
1914 Q.setUnaligned(CVRAU & DeclSpec::TQ_unaligned);
1915 return BuildQualifiedType(T, Loc, Q, DS);
1916}
1917
1918/// Build a paren type including \p T.
1919QualType Sema::BuildParenType(QualType T) {
1920 return Context.getParenType(T);
1921}
1922
1923/// Given that we're building a pointer or reference to the given
1924static QualType inferARCLifetimeForPointee(Sema &S, QualType type,
1925 SourceLocation loc,
1926 bool isReference) {
1927 // Bail out if retention is unrequired or already specified.
1928 if (!type->isObjCLifetimeType() ||
1929 type.getObjCLifetime() != Qualifiers::OCL_None)
1930 return type;
1931
1932 Qualifiers::ObjCLifetime implicitLifetime = Qualifiers::OCL_None;
1933
1934 // If the object type is const-qualified, we can safely use
1935 // __unsafe_unretained. This is safe (because there are no read
1936 // barriers), and it'll be safe to coerce anything but __weak* to
1937 // the resulting type.
1938 if (type.isConstQualified()) {
1939 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1940
1941 // Otherwise, check whether the static type does not require
1942 // retaining. This currently only triggers for Class (possibly
1943 // protocol-qualifed, and arrays thereof).
1944 } else if (type->isObjCARCImplicitlyUnretainedType()) {
1945 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1946
1947 // If we are in an unevaluated context, like sizeof, skip adding a
1948 // qualification.
1949 } else if (S.isUnevaluatedContext()) {
1950 return type;
1951
1952 // If that failed, give an error and recover using __strong. __strong
1953 // is the option most likely to prevent spurious second-order diagnostics,
1954 // like when binding a reference to a field.
1955 } else {
1956 // These types can show up in private ivars in system headers, so
1957 // we need this to not be an error in those cases. Instead we
1958 // want to delay.
1959 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
1960 S.DelayedDiagnostics.add(
1961 sema::DelayedDiagnostic::makeForbiddenType(loc,
1962 diag::err_arc_indirect_no_ownership, type, isReference));
1963 } else {
1964 S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference;
1965 }
1966 implicitLifetime = Qualifiers::OCL_Strong;
1967 }
1968 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~++20200806111125+5446ec85070/clang/lib/Sema/SemaType.cpp"
, 1968, __PRETTY_FUNCTION__))
;
1969
1970 Qualifiers qs;
1971 qs.addObjCLifetime(implicitLifetime);
1972 return S.Context.getQualifiedType(type, qs);
1973}
1974
1975static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){
1976 std::string Quals = FnTy->getMethodQuals().getAsString();
1977
1978 switch (FnTy->getRefQualifier()) {
1979 case RQ_None:
1980 break;
1981
1982 case RQ_LValue:
1983 if (!Quals.empty())
1984 Quals += ' ';
1985 Quals += '&';
1986 break;
1987
1988 case RQ_RValue:
1989 if (!Quals.empty())
1990 Quals += ' ';
1991 Quals += "&&";
1992 break;
1993 }
1994
1995 return Quals;
1996}
1997
1998namespace {
1999/// Kinds of declarator that cannot contain a qualified function type.
2000///
2001/// C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6:
2002/// a function type with a cv-qualifier or a ref-qualifier can only appear
2003/// at the topmost level of a type.
2004///
2005/// Parens and member pointers are permitted. We don't diagnose array and
2006/// function declarators, because they don't allow function types at all.
2007///
2008/// The values of this enum are used in diagnostics.
2009enum QualifiedFunctionKind { QFK_BlockPointer, QFK_Pointer, QFK_Reference };
2010} // end anonymous namespace
2011
2012/// Check whether the type T is a qualified function type, and if it is,
2013/// diagnose that it cannot be contained within the given kind of declarator.
2014static bool checkQualifiedFunction(Sema &S, QualType T, SourceLocation Loc,
2015 QualifiedFunctionKind QFK) {
2016 // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
2017 const FunctionProtoType *FPT = T->getAs<FunctionProtoType>();
2018 if (!FPT ||
2019 (FPT->getMethodQuals().empty() && FPT->getRefQualifier() == RQ_None))
2020 return false;
2021
2022 S.Diag(Loc, diag::err_compound_qualified_function_type)
2023 << QFK << isa<FunctionType>(T.IgnoreParens()) << T
2024 << getFunctionQualifiersAsString(FPT);
2025 return true;
2026}
2027
2028bool Sema::CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc) {
2029 const FunctionProtoType *FPT = T->getAs<FunctionProtoType>();
2030 if (!FPT ||
2031 (FPT->getMethodQuals().empty() && FPT->getRefQualifier() == RQ_None))
2032 return false;
2033
2034 Diag(Loc, diag::err_qualified_function_typeid)
2035 << T << getFunctionQualifiersAsString(FPT);
2036 return true;
2037}
2038
2039// Helper to deduce addr space of a pointee type in OpenCL mode.
2040static QualType deduceOpenCLPointeeAddrSpace(Sema &S, QualType PointeeType) {
2041 if (!PointeeType->isUndeducedAutoType() && !PointeeType->isDependentType() &&
2042 !PointeeType->isSamplerT() &&
2043 !PointeeType.hasAddressSpace())
2044 PointeeType = S.getASTContext().getAddrSpaceQualType(
2045 PointeeType,
2046 S.getLangOpts().OpenCLCPlusPlus || S.getLangOpts().OpenCLVersion == 200
2047 ? LangAS::opencl_generic
2048 : LangAS::opencl_private);
2049 return PointeeType;
2050}
2051
2052/// Build a pointer type.
2053///
2054/// \param T The type to which we'll be building a pointer.
2055///
2056/// \param Loc The location of the entity whose type involves this
2057/// pointer type or, if there is no such entity, the location of the
2058/// type that will have pointer type.
2059///
2060/// \param Entity The name of the entity that involves the pointer
2061/// type, if known.
2062///
2063/// \returns A suitable pointer type, if there are no
2064/// errors. Otherwise, returns a NULL type.
2065QualType Sema::BuildPointerType(QualType T,
2066 SourceLocation Loc, DeclarationName Entity) {
2067 if (T->isReferenceType()) {
2068 // C++ 8.3.2p4: There shall be no ... pointers to references ...
2069 Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
2070 << getPrintableNameForEntity(Entity) << T;
2071 return QualType();
2072 }
2073
2074 if (T->isFunctionType() && getLangOpts().OpenCL) {
2075 Diag(Loc, diag::err_opencl_function_pointer);
2076 return QualType();
2077 }
2078
2079 if (checkQualifiedFunction(*this, T, Loc, QFK_Pointer))
2080 return QualType();
2081
2082 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~++20200806111125+5446ec85070/clang/lib/Sema/SemaType.cpp"
, 2082, __PRETTY_FUNCTION__))
;
2083
2084 // In ARC, it is forbidden to build pointers to unqualified pointers.
2085 if (getLangOpts().ObjCAutoRefCount)
2086 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false);
2087
2088 if (getLangOpts().OpenCL)
2089 T = deduceOpenCLPointeeAddrSpace(*this, T);
2090
2091 // Build the pointer type.
2092 return Context.getPointerType(T);
2093}
2094
2095/// Build a reference type.
2096///
2097/// \param T The type to which we'll be building a reference.
2098///
2099/// \param Loc The location of the entity whose type involves this
2100/// reference type or, if there is no such entity, the location of the
2101/// type that will have reference type.
2102///
2103/// \param Entity The name of the entity that involves the reference
2104/// type, if known.
2105///
2106/// \returns A suitable reference type, if there are no
2107/// errors. Otherwise, returns a NULL type.
2108QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue,
2109 SourceLocation Loc,
2110 DeclarationName Entity) {
2111 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~++20200806111125+5446ec85070/clang/lib/Sema/SemaType.cpp"
, 2112, __PRETTY_FUNCTION__))
2112 "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~++20200806111125+5446ec85070/clang/lib/Sema/SemaType.cpp"
, 2112, __PRETTY_FUNCTION__))
;
2113
2114 // C++0x [dcl.ref]p6:
2115 // If a typedef (7.1.3), a type template-parameter (14.3.1), or a
2116 // decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a
2117 // type T, an attempt to create the type "lvalue reference to cv TR" creates
2118 // the type "lvalue reference to T", while an attempt to create the type
2119 // "rvalue reference to cv TR" creates the type TR.
2120 bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
2121
2122 // C++ [dcl.ref]p4: There shall be no references to references.
2123 //
2124 // According to C++ DR 106, references to references are only
2125 // diagnosed when they are written directly (e.g., "int & &"),
2126 // but not when they happen via a typedef:
2127 //
2128 // typedef int& intref;
2129 // typedef intref& intref2;
2130 //
2131 // Parser::ParseDeclaratorInternal diagnoses the case where
2132 // references are written directly; here, we handle the
2133 // collapsing of references-to-references as described in C++0x.
2134 // DR 106 and 540 introduce reference-collapsing into C++98/03.
2135
2136 // C++ [dcl.ref]p1:
2137 // A declarator that specifies the type "reference to cv void"
2138 // is ill-formed.
2139 if (T->isVoidType()) {
2140 Diag(Loc, diag::err_reference_to_void);
2141 return QualType();
2142 }
2143
2144 if (checkQualifiedFunction(*this, T, Loc, QFK_Reference))
2145 return QualType();
2146
2147 // In ARC, it is forbidden to build references to unqualified pointers.
2148 if (getLangOpts().ObjCAutoRefCount)
2149 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true);
2150
2151 if (getLangOpts().OpenCL)
2152 T = deduceOpenCLPointeeAddrSpace(*this, T);
2153
2154 // Handle restrict on references.
2155 if (LValueRef)
2156 return Context.getLValueReferenceType(T, SpelledAsLValue);
2157 return Context.getRValueReferenceType(T);
2158}
2159
2160/// Build a Read-only Pipe type.
2161///
2162/// \param T The type to which we'll be building a Pipe.
2163///
2164/// \param Loc We do not use it for now.
2165///
2166/// \returns A suitable pipe type, if there are no errors. Otherwise, returns a
2167/// NULL type.
2168QualType Sema::BuildReadPipeType(QualType T, SourceLocation Loc) {
2169 return Context.getReadPipeType(T);
2170}
2171
2172/// Build a Write-only Pipe type.
2173///
2174/// \param T The type to which we'll be building a Pipe.
2175///
2176/// \param Loc We do not use it for now.
2177///
2178/// \returns A suitable pipe type, if there are no errors. Otherwise, returns a
2179/// NULL type.
2180QualType Sema::BuildWritePipeType(QualType T, SourceLocation Loc) {
2181 return Context.getWritePipeType(T);
2182}
2183
2184/// Build a extended int type.
2185///
2186/// \param IsUnsigned Boolean representing the signedness of the type.
2187///
2188/// \param BitWidth Size of this int type in bits, or an expression representing
2189/// that.
2190///
2191/// \param Loc Location of the keyword.
2192QualType Sema::BuildExtIntType(bool IsUnsigned, Expr *BitWidth,
2193 SourceLocation Loc) {
2194 if (BitWidth->isInstantiationDependent())
2195 return Context.getDependentExtIntType(IsUnsigned, BitWidth);
2196
2197 llvm::APSInt Bits(32);
2198 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Bits);
2199
2200 if (ICE.isInvalid())
2201 return QualType();
2202
2203 int64_t NumBits = Bits.getSExtValue();
2204 if (!IsUnsigned && NumBits < 2) {
2205 Diag(Loc, diag::err_ext_int_bad_size) << 0;
2206 return QualType();
2207 }
2208
2209 if (IsUnsigned && NumBits < 1) {
2210 Diag(Loc, diag::err_ext_int_bad_size) << 1;
2211 return QualType();
2212 }
2213
2214 if (NumBits > llvm::IntegerType::MAX_INT_BITS) {
2215 Diag(Loc, diag::err_ext_int_max_size) << IsUnsigned
2216 << llvm::IntegerType::MAX_INT_BITS;
2217 return QualType();
2218 }
2219
2220 return Context.getExtIntType(IsUnsigned, NumBits);
2221}
2222
2223/// Check whether the specified array size makes the array type a VLA. If so,
2224/// return true, if not, return the size of the array in SizeVal.
2225static bool isArraySizeVLA(Sema &S, Expr *ArraySize, llvm::APSInt &SizeVal) {
2226 // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode
2227 // (like gnu99, but not c99) accept any evaluatable value as an extension.
2228 class VLADiagnoser : public Sema::VerifyICEDiagnoser {
2229 public:
2230 VLADiagnoser() : Sema::VerifyICEDiagnoser(true) {}
2231
2232 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
2233 }
2234
2235 void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR) override {
2236 S.Diag(Loc, diag::ext_vla_folded_to_constant) << SR;
2237 }
2238 } Diagnoser;
2239
2240 return S.VerifyIntegerConstantExpression(ArraySize, &SizeVal, Diagnoser,
2241 S.LangOpts.GNUMode ||
2242 S.LangOpts.OpenCL).isInvalid();
2243}
2244
2245/// Build an array type.
2246///
2247/// \param T The type of each element in the array.
2248///
2249/// \param ASM C99 array size modifier (e.g., '*', 'static').
2250///
2251/// \param ArraySize Expression describing the size of the array.
2252///
2253/// \param Brackets The range from the opening '[' to the closing ']'.
2254///
2255/// \param Entity The name of the entity that involves the array
2256/// type, if known.
2257///
2258/// \returns A suitable array type, if there are no errors. Otherwise,
2259/// returns a NULL type.
2260QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
2261 Expr *ArraySize, unsigned Quals,
2262 SourceRange Brackets, DeclarationName Entity) {
2263
2264 SourceLocation Loc = Brackets.getBegin();
2265 if (getLangOpts().CPlusPlus) {
2266 // C++ [dcl.array]p1:
2267 // T is called the array element type; this type shall not be a reference
2268 // type, the (possibly cv-qualified) type void, a function type or an
2269 // abstract class type.
2270 //
2271 // C++ [dcl.array]p3:
2272 // When several "array of" specifications are adjacent, [...] only the
2273 // first of the constant expressions that specify the bounds of the arrays
2274 // may be omitted.
2275 //
2276 // Note: function types are handled in the common path with C.
2277 if (T->isReferenceType()) {
2278 Diag(Loc, diag::err_illegal_decl_array_of_references)
2279 << getPrintableNameForEntity(Entity) << T;
2280 return QualType();
2281 }
2282
2283 if (T->isVoidType() || T->isIncompleteArrayType()) {
2284 Diag(Loc, diag::err_array_incomplete_or_sizeless_type) << 0 << T;
2285 return QualType();
2286 }
2287
2288 if (RequireNonAbstractType(Brackets.getBegin(), T,
2289 diag::err_array_of_abstract_type))
2290 return QualType();
2291
2292 // Mentioning a member pointer type for an array type causes us to lock in
2293 // an inheritance model, even if it's inside an unused typedef.
2294 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
2295 if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>())
2296 if (!MPTy->getClass()->isDependentType())
2297 (void)isCompleteType(Loc, T);
2298
2299 } else {
2300 // C99 6.7.5.2p1: If the element type is an incomplete or function type,
2301 // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
2302 if (RequireCompleteSizedType(Loc, T,
2303 diag::err_array_incomplete_or_sizeless_type))
2304 return QualType();
2305 }
2306
2307 if (T->isSizelessType() && !T->isVLST()) {
2308 Diag(Loc, diag::err_array_incomplete_or_sizeless_type) << 1 << T;
2309 return QualType();
2310 }
2311
2312 if (T->isFunctionType()) {
2313 Diag(Loc, diag::err_illegal_decl_array_of_functions)
2314 << getPrintableNameForEntity(Entity) << T;
2315 return QualType();
2316 }
2317
2318 if (const RecordType *EltTy = T->getAs<RecordType>()) {
2319 // If the element type is a struct or union that contains a variadic
2320 // array, accept it as a GNU extension: C99 6.7.2.1p2.
2321 if (EltTy->getDecl()->hasFlexibleArrayMember())
2322 Diag(Loc, diag::ext_flexible_array_in_array) << T;
2323 } else if (T->isObjCObjectType()) {
2324 Diag(Loc, diag::err_objc_array_of_interfaces) << T;
2325 return QualType();
2326 }
2327
2328 // Do placeholder conversions on the array size expression.
2329 if (ArraySize && ArraySize->hasPlaceholderType()) {
2330 ExprResult Result = CheckPlaceholderExpr(ArraySize);
2331 if (Result.isInvalid()) return QualType();
2332 ArraySize = Result.get();
2333 }
2334
2335 // Do lvalue-to-rvalue conversions on the array size expression.
2336 if (ArraySize && !ArraySize->isRValue()) {
2337 ExprResult Result = DefaultLvalueConversion(ArraySize);
2338 if (Result.isInvalid())
2339 return QualType();
2340
2341 ArraySize = Result.get();
2342 }
2343
2344 // C99 6.7.5.2p1: The size expression shall have integer type.
2345 // C++11 allows contextual conversions to such types.
2346 if (!getLangOpts().CPlusPlus11 &&
2347 ArraySize && !ArraySize->isTypeDependent() &&
2348 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
2349 Diag(ArraySize->getBeginLoc(), diag::err_array_size_non_int)
2350 << ArraySize->getType() << ArraySize->getSourceRange();
2351 return QualType();
2352 }
2353
2354 llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType()));
2355 if (!ArraySize) {
2356 if (ASM == ArrayType::Star)
2357 T = Context.getVariableArrayType(T, nullptr, ASM, Quals, Brackets);
2358 else
2359 T = Context.getIncompleteArrayType(T, ASM, Quals);
2360 } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) {
2361 T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets);
2362 } else if ((!T->isDependentType() && !T->isIncompleteType() &&
2363 !T->isConstantSizeType()) ||
2364 isArraySizeVLA(*this, ArraySize, ConstVal)) {
2365 // Even in C++11, don't allow contextual conversions in the array bound
2366 // of a VLA.
2367 if (getLangOpts().CPlusPlus11 &&
2368 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
2369 Diag(ArraySize->getBeginLoc(), diag::err_array_size_non_int)
2370 << ArraySize->getType() << ArraySize->getSourceRange();
2371 return QualType();
2372 }
2373
2374 // C99: an array with an element type that has a non-constant-size is a VLA.
2375 // C99: an array with a non-ICE size is a VLA. We accept any expression
2376 // that we can fold to a non-zero positive value as an extension.
2377 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
2378 } else {
2379 // C99 6.7.5.2p1: If the expression is a constant expression, it shall
2380 // have a value greater than zero.
2381 if (ConstVal.isSigned() && ConstVal.isNegative()) {
2382 if (Entity)
2383 Diag(ArraySize->getBeginLoc(), diag::err_decl_negative_array_size)
2384 << getPrintableNameForEntity(Entity) << ArraySize->getSourceRange();
2385 else
2386 Diag(ArraySize->getBeginLoc(), diag::err_typecheck_negative_array_size)
2387 << ArraySize->getSourceRange();
2388 return QualType();
2389 }
2390 if (ConstVal == 0) {
2391 // GCC accepts zero sized static arrays. We allow them when
2392 // we're not in a SFINAE context.
2393 Diag(ArraySize->getBeginLoc(), isSFINAEContext()
2394 ? diag::err_typecheck_zero_array_size
2395 : diag::ext_typecheck_zero_array_size)
2396 << ArraySize->getSourceRange();
2397 } else if (!T->isDependentType() && !T->isVariablyModifiedType() &&
2398 !T->isIncompleteType() && !T->isUndeducedType()) {
2399 // Is the array too large?
2400 unsigned ActiveSizeBits
2401 = ConstantArrayType::getNumAddressingBits(Context, T, ConstVal);
2402 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
2403 Diag(ArraySize->getBeginLoc(), diag::err_array_too_large)
2404 << ConstVal.toString(10) << ArraySize->getSourceRange();
2405 return QualType();
2406 }
2407 }
2408
2409 T = Context.getConstantArrayType(T, ConstVal, ArraySize, ASM, Quals);
2410 }
2411
2412 // OpenCL v1.2 s6.9.d: variable length arrays are not supported.
2413 if (getLangOpts().OpenCL && T->isVariableArrayType()) {
2414 Diag(Loc, diag::err_opencl_vla);
2415 return QualType();
2416 }
2417
2418 if (T->isVariableArrayType() && !Context.getTargetInfo().isVLASupported()) {
2419 // CUDA device code and some other targets don't support VLAs.
2420 targetDiag(Loc, (getLangOpts().CUDA && getLangOpts().CUDAIsDevice)
2421 ? diag::err_cuda_vla
2422 : diag::err_vla_unsupported)
2423 << ((getLangOpts().CUDA && getLangOpts().CUDAIsDevice)
2424 ? CurrentCUDATarget()
2425 : CFT_InvalidTarget);
2426 }
2427
2428 // If this is not C99, extwarn about VLA's and C99 array size modifiers.
2429 if (!getLangOpts().C99) {
2430 if (T->isVariableArrayType()) {
2431 // Prohibit the use of VLAs during template argument deduction.
2432 if (isSFINAEContext()) {
2433 Diag(Loc, diag::err_vla_in_sfinae);
2434 return QualType();
2435 }
2436 // Just extwarn about VLAs.
2437 else
2438 Diag(Loc, diag::ext_vla);
2439 } else if (ASM != ArrayType::Normal || Quals != 0)
2440 Diag(Loc,
2441 getLangOpts().CPlusPlus? diag::err_c99_array_usage_cxx
2442 : diag::ext_c99_array_usage) << ASM;
2443 }
2444
2445 if (T->isVariableArrayType()) {
2446 // Warn about VLAs for -Wvla.
2447 Diag(Loc, diag::warn_vla_used);
2448 }
2449
2450 // OpenCL v2.0 s6.12.5 - Arrays of blocks are not supported.
2451 // OpenCL v2.0 s6.16.13.1 - Arrays of pipe type are not supported.
2452 // OpenCL v2.0 s6.9.b - Arrays of image/sampler type are not supported.
2453 if (getLangOpts().OpenCL) {
2454 const QualType ArrType = Context.getBaseElementType(T);
2455 if (ArrType->isBlockPointerType() || ArrType->isPipeType() ||
2456 ArrType->isSamplerT() || ArrType->isImageType()) {
2457 Diag(Loc, diag::err_opencl_invalid_type_array) << ArrType;
2458 return QualType();
2459 }
2460 }
2461
2462 return T;
2463}
2464
2465QualType Sema::BuildVectorType(QualType CurType, Expr *SizeExpr,
2466 SourceLocation AttrLoc) {
2467 // The base type must be integer (not Boolean or enumeration) or float, and
2468 // can't already be a vector.
2469 if (!CurType->isDependentType() &&
2470 (!CurType->isBuiltinType() || CurType->isBooleanType() ||
2471 (!CurType->isIntegerType() && !CurType->isRealFloatingType()))) {
2472 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << CurType;
2473 return QualType();
2474 }
2475
2476 if (SizeExpr->isTypeDependent() || SizeExpr->isValueDependent())
2477 return Context.getDependentVectorType(CurType, SizeExpr, AttrLoc,
2478 VectorType::GenericVector);
2479
2480 Optional<llvm::APSInt> VecSize = SizeExpr->getIntegerConstantExpr(Context);
2481 if (!VecSize) {
2482 Diag(AttrLoc, diag::err_attribute_argument_type)
2483 << "vector_size" << AANT_ArgumentIntegerConstant
2484 << SizeExpr->getSourceRange();
2485 return QualType();
2486 }
2487
2488 if (CurType->isDependentType())
2489 return Context.getDependentVectorType(CurType, SizeExpr, AttrLoc,
2490 VectorType::GenericVector);
2491
2492 // vecSize is specified in bytes - convert to bits.
2493 if (!VecSize->isIntN(61)) {
2494 // Bit size will overflow uint64.
2495 Diag(AttrLoc, diag::err_attribute_size_too_large)
2496 << SizeExpr->getSourceRange() << "vector";
2497 return QualType();
2498 }
2499 uint64_t VectorSizeBits = VecSize->getZExtValue() * 8;
2500 unsigned TypeSize = static_cast<unsigned>(Context.getTypeSize(CurType));
2501
2502 if (VectorSizeBits == 0) {
2503 Diag(AttrLoc, diag::err_attribute_zero_size)
2504 << SizeExpr->getSourceRange() << "vector";
2505 return QualType();
2506 }
2507
2508 if (VectorSizeBits % TypeSize) {
2509 Diag(AttrLoc, diag::err_attribute_invalid_size)
2510 << SizeExpr->getSourceRange();
2511 return QualType();
2512 }
2513
2514 if (VectorSizeBits / TypeSize > std::numeric_limits<uint32_t>::max()) {
2515 Diag(AttrLoc, diag::err_attribute_size_too_large)
2516 << SizeExpr->getSourceRange() << "vector";
2517 return QualType();
2518 }
2519
2520 return Context.getVectorType(CurType, VectorSizeBits / TypeSize,
2521 VectorType::GenericVector);
2522}
2523
2524/// Build an ext-vector type.
2525///
2526/// Run the required checks for the extended vector type.
2527QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize,
2528 SourceLocation AttrLoc) {
2529 // Unlike gcc's vector_size attribute, we do not allow vectors to be defined
2530 // in conjunction with complex types (pointers, arrays, functions, etc.).
2531 //
2532 // Additionally, OpenCL prohibits vectors of booleans (they're considered a
2533 // reserved data type under OpenCL v2.0 s6.1.4), we don't support selects
2534 // on bitvectors, and we have no well-defined ABI for bitvectors, so vectors
2535 // of bool aren't allowed.
2536 if ((!T->isDependentType() && !T->isIntegerType() &&
2537 !T->isRealFloatingType()) ||
2538 T->isBooleanType()) {
2539 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
2540 return QualType();
2541 }
2542
2543 if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) {
2544 Optional<llvm::APSInt> vecSize = ArraySize->getIntegerConstantExpr(Context);
2545 if (!vecSize) {
2546 Diag(AttrLoc, diag::err_attribute_argument_type)
2547 << "ext_vector_type" << AANT_ArgumentIntegerConstant
2548 << ArraySize->getSourceRange();
2549 return QualType();
2550 }
2551
2552 if (!vecSize->isIntN(32)) {
2553 Diag(AttrLoc, diag::err_attribute_size_too_large)
2554 << ArraySize->getSourceRange() << "vector";
2555 return QualType();
2556 }
2557 // Unlike gcc's vector_size attribute, the size is specified as the
2558 // number of elements, not the number of bytes.
2559 unsigned vectorSize = static_cast<unsigned>(vecSize->getZExtValue());
2560
2561 if (vectorSize == 0) {
2562 Diag(AttrLoc, diag::err_attribute_zero_size)
2563 << ArraySize->getSourceRange() << "vector";
2564 return QualType();
2565 }
2566
2567 return Context.getExtVectorType(T, vectorSize);
2568 }
2569
2570 return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc);
2571}
2572
2573QualType Sema::BuildMatrixType(QualType ElementTy, Expr *NumRows, Expr *NumCols,
2574 SourceLocation AttrLoc) {
2575 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~++20200806111125+5446ec85070/clang/lib/Sema/SemaType.cpp"
, 2576, __PRETTY_FUNCTION__))
2576 "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~++20200806111125+5446ec85070/clang/lib/Sema/SemaType.cpp"
, 2576, __PRETTY_FUNCTION__))
;
2577
2578 // Check element type, if it is not dependent.
2579 if (!ElementTy->isDependentType() &&
2580 !MatrixType::isValidElementType(ElementTy)) {
2581 Diag(AttrLoc, diag::err_attribute_invalid_matrix_type) << ElementTy;
2582 return QualType();
2583 }
2584
2585 if (NumRows->isTypeDependent() || NumCols->isTypeDependent() ||
2586 NumRows->isValueDependent() || NumCols->isValueDependent())
2587 return Context.getDependentSizedMatrixType(ElementTy, NumRows, NumCols,
2588 AttrLoc);
2589
2590 Optional<llvm::APSInt> ValueRows = NumRows->getIntegerConstantExpr(Context);
2591 Optional<llvm::APSInt> ValueColumns =
2592 NumCols->getIntegerConstantExpr(Context);
2593
2594 auto const RowRange = NumRows->getSourceRange();
2595 auto const ColRange = NumCols->getSourceRange();
2596
2597 // Both are row and column expressions are invalid.
2598 if (!ValueRows && !ValueColumns) {
2599 Diag(AttrLoc, diag::err_attribute_argument_type)
2600 << "matrix_type" << AANT_ArgumentIntegerConstant << RowRange
2601 << ColRange;
2602 return QualType();
2603 }
2604
2605 // Only the row expression is invalid.
2606 if (!ValueRows) {
2607 Diag(AttrLoc, diag::err_attribute_argument_type)
2608 << "matrix_type" << AANT_ArgumentIntegerConstant << RowRange;
2609 return QualType();
2610 }
2611
2612 // Only the column expression is invalid.
2613 if (!ValueColumns) {
2614 Diag(AttrLoc, diag::err_attribute_argument_type)
2615 << "matrix_type" << AANT_ArgumentIntegerConstant << ColRange;
2616 return QualType();
2617 }
2618
2619 // Check the matrix dimensions.
2620 unsigned MatrixRows = static_cast<unsigned>(ValueRows->getZExtValue());
2621 unsigned MatrixColumns = static_cast<unsigned>(ValueColumns->getZExtValue());
2622 if (MatrixRows == 0 && MatrixColumns == 0) {
2623 Diag(AttrLoc, diag::err_attribute_zero_size)
2624 << "matrix" << RowRange << ColRange;
2625 return QualType();
2626 }
2627 if (MatrixRows == 0) {
2628 Diag(AttrLoc, diag::err_attribute_zero_size) << "matrix" << RowRange;
2629 return QualType();
2630 }
2631 if (MatrixColumns == 0) {
2632 Diag(AttrLoc, diag::err_attribute_zero_size) << "matrix" << ColRange;
2633 return QualType();
2634 }
2635 if (!ConstantMatrixType::isDimensionValid(MatrixRows)) {
2636 Diag(AttrLoc, diag::err_attribute_size_too_large)
2637 << RowRange << "matrix row";
2638 return QualType();
2639 }
2640 if (!ConstantMatrixType::isDimensionValid(MatrixColumns)) {
2641 Diag(AttrLoc, diag::err_attribute_size_too_large)
2642 << ColRange << "matrix column";
2643 return QualType();
2644 }
2645 return Context.getConstantMatrixType(ElementTy, MatrixRows, MatrixColumns);
2646}
2647
2648bool Sema::CheckFunctionReturnType(QualType T, SourceLocation Loc) {
2649 if (T->isArrayType() || T->isFunctionType()) {
2650 Diag(Loc, diag::err_func_returning_array_function)
2651 << T->isFunctionType() << T;
2652 return true;
2653 }
2654
2655 // Functions cannot return half FP.
2656 if (T->isHalfType() && !getLangOpts().HalfArgsAndReturns) {
2657 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 <<
2658 FixItHint::CreateInsertion(Loc, "*");
2659 return true;
2660 }
2661
2662 // Methods cannot return interface types. All ObjC objects are
2663 // passed by reference.
2664 if (T->isObjCObjectType()) {
2665 Diag(Loc, diag::err_object_cannot_be_passed_returned_by_value)
2666 << 0 << T << FixItHint::CreateInsertion(Loc, "*");
2667 return true;
2668 }
2669
2670 if (T.hasNonTrivialToPrimitiveDestructCUnion() ||
2671 T.hasNonTrivialToPrimitiveCopyCUnion())
2672 checkNonTrivialCUnion(T, Loc, NTCUC_FunctionReturn,
2673 NTCUK_Destruct|NTCUK_Copy);
2674
2675 // C++2a [dcl.fct]p12:
2676 // A volatile-qualified return type is deprecated
2677 if (T.isVolatileQualified() && getLangOpts().CPlusPlus20)
2678 Diag(Loc, diag::warn_deprecated_volatile_return) << T;
2679
2680 return false;
2681}
2682
2683/// Check the extended parameter information. Most of the necessary
2684/// checking should occur when applying the parameter attribute; the
2685/// only other checks required are positional restrictions.
2686static void checkExtParameterInfos(Sema &S, ArrayRef<QualType> paramTypes,
2687 const FunctionProtoType::ExtProtoInfo &EPI,
2688 llvm::function_ref<SourceLocation(unsigned)> getParamLoc) {
2689 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~++20200806111125+5446ec85070/clang/lib/Sema/SemaType.cpp"
, 2689, __PRETTY_FUNCTION__))
;
2690
2691 bool hasCheckedSwiftCall = false;
2692 auto checkForSwiftCC = [&](unsigned paramIndex) {
2693 // Only do this once.
2694 if (hasCheckedSwiftCall) return;
2695 hasCheckedSwiftCall = true;
2696 if (EPI.ExtInfo.getCC() == CC_Swift) return;
2697 S.Diag(getParamLoc(paramIndex), diag::err_swift_param_attr_not_swiftcall)
2698 << getParameterABISpelling(EPI.ExtParameterInfos[paramIndex].getABI());
2699 };
2700
2701 for (size_t paramIndex = 0, numParams = paramTypes.size();
2702 paramIndex != numParams; ++paramIndex) {
2703 switch (EPI.ExtParameterInfos[paramIndex].getABI()) {
2704 // Nothing interesting to check for orindary-ABI parameters.
2705 case ParameterABI::Ordinary:
2706 continue;
2707
2708 // swift_indirect_result parameters must be a prefix of the function
2709 // arguments.
2710 case ParameterABI::SwiftIndirectResult:
2711 checkForSwiftCC(paramIndex);
2712 if (paramIndex != 0 &&
2713 EPI.ExtParameterInfos[paramIndex - 1].getABI()
2714 != ParameterABI::SwiftIndirectResult) {
2715 S.Diag(getParamLoc(paramIndex),
2716 diag::err_swift_indirect_result_not_first);
2717 }
2718 continue;
2719
2720 case ParameterABI::SwiftContext:
2721 checkForSwiftCC(paramIndex);
2722 continue;
2723
2724 // swift_error parameters must be preceded by a swift_context parameter.
2725 case ParameterABI::SwiftErrorResult:
2726 checkForSwiftCC(paramIndex);
2727 if (paramIndex == 0 ||
2728 EPI.ExtParameterInfos[paramIndex - 1].getABI() !=
2729 ParameterABI::SwiftContext) {
2730 S.Diag(getParamLoc(paramIndex),
2731 diag::err_swift_error_result_not_after_swift_context);
2732 }
2733 continue;
2734 }
2735 llvm_unreachable("bad ABI kind")::llvm::llvm_unreachable_internal("bad ABI kind", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaType.cpp"
, 2735)
;
2736 }
2737}
2738
2739QualType Sema::BuildFunctionType(QualType T,
2740 MutableArrayRef<QualType> ParamTypes,
2741 SourceLocation Loc, DeclarationName Entity,
2742 const FunctionProtoType::ExtProtoInfo &EPI) {
2743 bool Invalid = false;
2744
2745 Invalid |= CheckFunctionReturnType(T, Loc);
2746
2747 for (unsigned Idx = 0, Cnt = ParamTypes.size(); Idx < Cnt; ++Idx) {
2748 // FIXME: Loc is too inprecise here, should use proper locations for args.
2749 QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]);
2750 if (ParamType->isVoidType()) {
2751 Diag(Loc, diag::err_param_with_void_type);
2752 Invalid = true;
2753 } else if (ParamType->isHalfType() && !getLangOpts().HalfArgsAndReturns) {
2754 // Disallow half FP arguments.
2755 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 <<
2756 FixItHint::CreateInsertion(Loc, "*");
2757 Invalid = true;
2758 }
2759
2760 // C++2a [dcl.fct]p4:
2761 // A parameter with volatile-qualified type is deprecated
2762 if (ParamType.isVolatileQualified() && getLangOpts().CPlusPlus20)
2763 Diag(Loc, diag::warn_deprecated_volatile_param) << ParamType;
2764
2765 ParamTypes[Idx] = ParamType;
2766 }
2767
2768 if (EPI.ExtParameterInfos) {
2769 checkExtParameterInfos(*this, ParamTypes, EPI,
2770 [=](unsigned i) { return Loc; });
2771 }
2772
2773 if (EPI.ExtInfo.getProducesResult()) {
2774 // This is just a warning, so we can't fail to build if we see it.
2775 checkNSReturnsRetainedReturnType(Loc, T);
2776 }
2777
2778 if (Invalid)
2779 return QualType();
2780
2781 return Context.getFunctionType(T, ParamTypes, EPI);
2782}
2783
2784/// Build a member pointer type \c T Class::*.
2785///
2786/// \param T the type to which the member pointer refers.
2787/// \param Class the class type into which the member pointer points.
2788/// \param Loc the location where this type begins
2789/// \param Entity the name of the entity that will have this member pointer type
2790///
2791/// \returns a member pointer type, if successful, or a NULL type if there was
2792/// an error.
2793QualType Sema::BuildMemberPointerType(QualType T, QualType Class,
2794 SourceLocation Loc,
2795 DeclarationName Entity) {
2796 // Verify that we're not building a pointer to pointer to function with
2797 // exception specification.
2798 if (CheckDistantExceptionSpec(T)) {
2799 Diag(Loc, diag::err_distant_exception_spec);
2800 return QualType();
2801 }
2802
2803 // C++ 8.3.3p3: A pointer to member shall not point to ... a member
2804 // with reference type, or "cv void."
2805 if (T->isReferenceType()) {
2806 Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
2807 << getPrintableNameForEntity(Entity) << T;
2808 return QualType();
2809 }
2810
2811 if (T->isVoidType()) {
2812 Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
2813 << getPrintableNameForEntity(Entity);
2814 return QualType();
2815 }
2816
2817 if (!Class->isDependentType() && !Class->isRecordType()) {
2818 Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
2819 return QualType();
2820 }
2821
2822 // Adjust the default free function calling convention to the default method
2823 // calling convention.
2824 bool IsCtorOrDtor =
2825 (Entity.getNameKind() == DeclarationName::CXXConstructorName) ||
2826 (Entity.getNameKind() == DeclarationName::CXXDestructorName);
2827 if (T->isFunctionType())
2828 adjustMemberFunctionCC(T, /*IsStatic=*/false, IsCtorOrDtor, Loc);
2829
2830 return Context.getMemberPointerType(T, Class.getTypePtr());
2831}
2832
2833/// Build a block pointer type.
2834///
2835/// \param T The type to which we'll be building a block pointer.
2836///
2837/// \param Loc The source location, used for diagnostics.
2838///
2839/// \param Entity The name of the entity that involves the block pointer
2840/// type, if known.
2841///
2842/// \returns A suitable block pointer type, if there are no
2843/// errors. Otherwise, returns a NULL type.
2844QualType Sema::BuildBlockPointerType(QualType T,
2845 SourceLocation Loc,
2846 DeclarationName Entity) {
2847 if (!T->isFunctionType()) {
2848 Diag(Loc, diag::err_nonfunction_block_type);
2849 return QualType();
2850 }
2851
2852 if (checkQualifiedFunction(*this, T, Loc, QFK_BlockPointer))
2853 return QualType();
2854
2855 if (getLangOpts().OpenCL)
2856 T = deduceOpenCLPointeeAddrSpace(*this, T);
2857
2858 return Context.getBlockPointerType(T);
2859}
2860
2861QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) {
2862 QualType QT = Ty.get();
2863 if (QT.isNull()) {
2864 if (TInfo) *TInfo = nullptr;
2865 return QualType();
2866 }
2867
2868 TypeSourceInfo *DI = nullptr;
2869 if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
2870 QT = LIT->getType();
2871 DI = LIT->getTypeSourceInfo();
2872 }
2873
2874 if (TInfo) *TInfo = DI;
2875 return QT;
2876}
2877
2878static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
2879 Qualifiers::ObjCLifetime ownership,
2880 unsigned chunkIndex);
2881
2882/// Given that this is the declaration of a parameter under ARC,
2883/// attempt to infer attributes and such for pointer-to-whatever
2884/// types.
2885static void inferARCWriteback(TypeProcessingState &state,
2886 QualType &declSpecType) {
2887 Sema &S = state.getSema();
2888 Declarator &declarator = state.getDeclarator();
2889
2890 // TODO: should we care about decl qualifiers?
2891
2892 // Check whether the declarator has the expected form. We walk
2893 // from the inside out in order to make the block logic work.
2894 unsigned outermostPointerIndex = 0;
2895 bool isBlockPointer = false;
2896 unsigned numPointers = 0;
2897 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
2898 unsigned chunkIndex = i;
2899 DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex);
2900 switch (chunk.Kind) {
2901 case DeclaratorChunk::Paren:
2902 // Ignore parens.
2903 break;
2904
2905 case DeclaratorChunk::Reference:
2906 case DeclaratorChunk::Pointer:
2907 // Count the number of pointers. Treat references
2908 // interchangeably as pointers; if they're mis-ordered, normal
2909 // type building will discover that.
2910 outermostPointerIndex = chunkIndex;
2911 numPointers++;
2912 break;
2913
2914 case DeclaratorChunk::BlockPointer:
2915 // If we have a pointer to block pointer, that's an acceptable
2916 // indirect reference; anything else is not an application of
2917 // the rules.
2918 if (numPointers != 1) return;
2919 numPointers++;
2920 outermostPointerIndex = chunkIndex;
2921 isBlockPointer = true;
2922
2923 // We don't care about pointer structure in return values here.
2924 goto done;
2925
2926 case DeclaratorChunk::Array: // suppress if written (id[])?
2927 case DeclaratorChunk::Function:
2928 case DeclaratorChunk::MemberPointer:
2929 case DeclaratorChunk::Pipe:
2930 return;
2931 }
2932 }
2933 done:
2934
2935 // If we have *one* pointer, then we want to throw the qualifier on
2936 // the declaration-specifiers, which means that it needs to be a
2937 // retainable object type.
2938 if (numPointers == 1) {
2939 // If it's not a retainable object type, the rule doesn't apply.
2940 if (!declSpecType->isObjCRetainableType()) return;
2941
2942 // If it already has lifetime, don't do anything.
2943 if (declSpecType.getObjCLifetime()) return;
2944
2945 // Otherwise, modify the type in-place.
2946 Qualifiers qs;
2947
2948 if (declSpecType->isObjCARCImplicitlyUnretainedType())
2949 qs.addObjCLifetime(Qualifiers::OCL_ExplicitNone);
2950 else
2951 qs.addObjCLifetime(Qualifiers::OCL_Autoreleasing);
2952 declSpecType = S.Context.getQualifiedType(declSpecType, qs);
2953
2954 // If we have *two* pointers, then we want to throw the qualifier on
2955 // the outermost pointer.
2956 } else if (numPointers == 2) {
2957 // If we don't have a block pointer, we need to check whether the
2958 // declaration-specifiers gave us something that will turn into a
2959 // retainable object pointer after we slap the first pointer on it.
2960 if (!isBlockPointer && !declSpecType->isObjCObjectType())
2961 return;
2962
2963 // Look for an explicit lifetime attribute there.
2964 DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex);
2965 if (chunk.Kind != DeclaratorChunk::Pointer &&
2966 chunk.Kind != DeclaratorChunk::BlockPointer)
2967 return;
2968 for (const ParsedAttr &AL : chunk.getAttrs())
2969 if (AL.getKind() == ParsedAttr::AT_ObjCOwnership)
2970 return;
2971
2972 transferARCOwnershipToDeclaratorChunk(state, Qualifiers::OCL_Autoreleasing,
2973 outermostPointerIndex);
2974
2975 // Any other number of pointers/references does not trigger the rule.
2976 } else return;
2977
2978 // TODO: mark whether we did this inference?
2979}
2980
2981void Sema::diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
2982 SourceLocation FallbackLoc,
2983 SourceLocation ConstQualLoc,
2984 SourceLocation VolatileQualLoc,
2985 SourceLocation RestrictQualLoc,
2986 SourceLocation AtomicQualLoc,
2987 SourceLocation UnalignedQualLoc) {
2988 if (!Quals)
2989 return;
2990
2991 struct Qual {
2992 const char *Name;
2993 unsigned Mask;
2994 SourceLocation Loc;
2995 } const QualKinds[5] = {
2996 { "const", DeclSpec::TQ_const, ConstQualLoc },
2997 { "volatile", DeclSpec::TQ_volatile, VolatileQualLoc },
2998 { "restrict", DeclSpec::TQ_restrict, RestrictQualLoc },
2999 { "__unaligned", DeclSpec::TQ_unaligned, UnalignedQualLoc },
3000 { "_Atomic", DeclSpec::TQ_atomic, AtomicQualLoc }
3001 };
3002
3003 SmallString<32> QualStr;
3004 unsigned NumQuals = 0;
3005 SourceLocation Loc;
3006 FixItHint FixIts[5];
3007
3008 // Build a string naming the redundant qualifiers.
3009 for (auto &E : QualKinds) {
3010 if (Quals & E.Mask) {
3011 if (!QualStr.empty()) QualStr += ' ';
3012 QualStr += E.Name;
3013
3014 // If we have a location for the qualifier, offer a fixit.
3015 SourceLocation QualLoc = E.Loc;
3016 if (QualLoc.isValid()) {
3017 FixIts[NumQuals] = FixItHint::CreateRemoval(QualLoc);
3018 if (Loc.isInvalid() ||
3019 getSourceManager().isBeforeInTranslationUnit(QualLoc, Loc))
3020 Loc = QualLoc;
3021 }
3022
3023 ++NumQuals;
3024 }
3025 }
3026
3027 Diag(Loc.isInvalid() ? FallbackLoc : Loc, DiagID)
3028 << QualStr << NumQuals << FixIts[0] << FixIts[1] << FixIts[2] << FixIts[3];
3029}
3030
3031// Diagnose pointless type qualifiers on the return type of a function.
3032static void diagnoseRedundantReturnTypeQualifiers(Sema &S, QualType RetTy,
3033 Declarator &D,
3034 unsigned FunctionChunkIndex) {
3035 if (D.getTypeObject(FunctionChunkIndex).Fun.hasTrailingReturnType()) {
3036 // FIXME: TypeSourceInfo doesn't preserve location information for
3037 // qualifiers.
3038 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
3039 RetTy.getLocalCVRQualifiers(),
3040 D.getIdentifierLoc());
3041 return;
3042 }
3043
3044 for (unsigned OuterChunkIndex = FunctionChunkIndex + 1,
3045 End = D.getNumTypeObjects();
3046 OuterChunkIndex != End; ++OuterChunkIndex) {
3047 DeclaratorChunk &OuterChunk = D.getTypeObject(OuterChunkIndex);
3048 switch (OuterChunk.Kind) {
3049 case DeclaratorChunk::Paren:
3050 continue;
3051
3052 case DeclaratorChunk::Pointer: {
3053 DeclaratorChunk::PointerTypeInfo &PTI = OuterChunk.Ptr;
3054 S.diagnoseIgnoredQualifiers(
3055 diag::warn_qual_return_type,
3056 PTI.TypeQuals,
3057 SourceLocation(),
3058 SourceLocation::getFromRawEncoding(PTI.ConstQualLoc),
3059 SourceLocation::getFromRawEncoding(PTI.VolatileQualLoc),
3060 SourceLocation::getFromRawEncoding(PTI.RestrictQualLoc),
3061 SourceLocation::getFromRawEncoding(PTI.AtomicQualLoc),
3062 SourceLocation::getFromRawEncoding(PTI.UnalignedQualLoc));
3063 return;
3064 }
3065
3066 case DeclaratorChunk::Function:
3067 case DeclaratorChunk::BlockPointer:
3068 case DeclaratorChunk::Reference:
3069 case DeclaratorChunk::Array:
3070 case DeclaratorChunk::MemberPointer:
3071 case DeclaratorChunk::Pipe:
3072 // FIXME: We can't currently provide an accurate source location and a
3073 // fix-it hint for these.
3074 unsigned AtomicQual = RetTy->isAtomicType() ? DeclSpec::TQ_atomic : 0;
3075 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
3076 RetTy.getCVRQualifiers() | AtomicQual,
3077 D.getIdentifierLoc());
3078 return;
3079 }
3080
3081 llvm_unreachable("unknown declarator chunk kind")::llvm::llvm_unreachable_internal("unknown declarator chunk kind"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaType.cpp"
, 3081)
;
3082 }
3083
3084 // If the qualifiers come from a conversion function type, don't diagnose
3085 // them -- they're not necessarily redundant, since such a conversion
3086 // operator can be explicitly called as "x.operator const int()".
3087 if (D.getName().getKind() == UnqualifiedIdKind::IK_ConversionFunctionId)
3088 return;
3089
3090 // Just parens all the way out to the decl specifiers. Diagnose any qualifiers
3091 // which are present there.
3092 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
3093 D.getDeclSpec().getTypeQualifiers(),
3094 D.getIdentifierLoc(),
3095 D.getDeclSpec().getConstSpecLoc(),
3096 D.getDeclSpec().getVolatileSpecLoc(),
3097 D.getDeclSpec().getRestrictSpecLoc(),
3098 D.getDeclSpec().getAtomicSpecLoc(),
3099 D.getDeclSpec().getUnalignedSpecLoc());
3100}
3101
3102static std::pair<QualType, TypeSourceInfo *>
3103InventTemplateParameter(TypeProcessingState &state, QualType T,
3104 TypeSourceInfo *TrailingTSI, AutoType *Auto,
3105 InventedTemplateParameterInfo &Info) {
3106 Sema &S = state.getSema();
3107 Declarator &D = state.getDeclarator();
3108
3109 const unsigned TemplateParameterDepth = Info.AutoTemplateParameterDepth;
3110 const unsigned AutoParameterPosition = Info.TemplateParams.size();
3111 const bool IsParameterPack = D.hasEllipsis();
3112
3113 // If auto is mentioned in a lambda parameter or abbreviated function
3114 // template context, convert it to a template parameter type.
3115
3116 // Create the TemplateTypeParmDecl here to retrieve the corresponding
3117 // template parameter type. Template parameters are temporarily added
3118 // to the TU until the associated TemplateDecl is created.
3119 TemplateTypeParmDecl *InventedTemplateParam =
3120 TemplateTypeParmDecl::Create(
3121 S.Context, S.Context.getTranslationUnitDecl(),
3122 /*KeyLoc=*/D.getDeclSpec().getTypeSpecTypeLoc(),
3123 /*NameLoc=*/D.getIdentifierLoc(),
3124 TemplateParameterDepth, AutoParameterPosition,
3125 S.InventAbbreviatedTemplateParameterTypeName(
3126 D.getIdentifier(), AutoParameterPosition), false,
3127 IsParameterPack, /*HasTypeConstraint=*/Auto->isConstrained());
3128 InventedTemplateParam->setImplicit();
3129 Info.TemplateParams.push_back(InventedTemplateParam);
3130
3131 // Attach type constraints to the new parameter.
3132 if (Auto->isConstrained()) {
3133 if (TrailingTSI) {
3134 // The 'auto' appears in a trailing return type we've already built;
3135 // extract its type constraints to attach to the template parameter.
3136 AutoTypeLoc AutoLoc = TrailingTSI->getTypeLoc().getContainedAutoTypeLoc();
3137 TemplateArgumentListInfo TAL(AutoLoc.getLAngleLoc(), AutoLoc.getRAngleLoc());
3138 for (unsigned Idx = 0; Idx < AutoLoc.getNumArgs(); ++Idx)
3139 TAL.addArgument(AutoLoc.getArgLoc(Idx));
3140
3141 S.AttachTypeConstraint(AutoLoc.getNestedNameSpecifierLoc(),
3142 AutoLoc.getConceptNameInfo(),
3143 AutoLoc.getNamedConcept(),
3144 AutoLoc.hasExplicitTemplateArgs() ? &TAL : nullptr,
3145 InventedTemplateParam, D.getEllipsisLoc());
3146 } else {
3147 // The 'auto' appears in the decl-specifiers; we've not finished forming
3148 // TypeSourceInfo for it yet.
3149 TemplateIdAnnotation *TemplateId = D.getDeclSpec().getRepAsTemplateId();
3150 TemplateArgumentListInfo TemplateArgsInfo;
3151 if (TemplateId->LAngleLoc.isValid()) {
3152 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
3153 TemplateId->NumArgs);
3154 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo);
3155 }
3156 S.AttachTypeConstraint(
3157 D.getDeclSpec().getTypeSpecScope().getWithLocInContext(S.Context),
3158 DeclarationNameInfo(DeclarationName(TemplateId->Name),
3159 TemplateId->TemplateNameLoc),
3160 cast<ConceptDecl>(TemplateId->Template.get().getAsTemplateDecl()),
3161 TemplateId->LAngleLoc.isValid() ? &TemplateArgsInfo : nullptr,
3162 InventedTemplateParam, D.getEllipsisLoc());
3163 }
3164 }
3165
3166 // Replace the 'auto' in the function parameter with this invented
3167 // template type parameter.
3168 // FIXME: Retain some type sugar to indicate that this was written
3169 // as 'auto'?
3170 QualType Replacement(InventedTemplateParam->getTypeForDecl(), 0);
3171 QualType NewT = state.ReplaceAutoType(T, Replacement);
3172 TypeSourceInfo *NewTSI =
3173 TrailingTSI ? S.ReplaceAutoTypeSourceInfo(TrailingTSI, Replacement)
3174 : nullptr;
3175 return {NewT, NewTSI};
3176}
3177
3178static TypeSourceInfo *
3179GetTypeSourceInfoForDeclarator(TypeProcessingState &State,
3180 QualType T, TypeSourceInfo *ReturnTypeInfo);
3181
3182static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state,
3183 TypeSourceInfo *&ReturnTypeInfo) {
3184 Sema &SemaRef = state.getSema();
3185 Declarator &D = state.getDeclarator();
3186 QualType T;
3187 ReturnTypeInfo = nullptr;
3188
3189 // The TagDecl owned by the DeclSpec.
3190 TagDecl *OwnedTagDecl = nullptr;
3191
3192 switch (D.getName().getKind()) {
3193 case UnqualifiedIdKind::IK_ImplicitSelfParam:
3194 case UnqualifiedIdKind::IK_OperatorFunctionId:
3195 case UnqualifiedIdKind::IK_Identifier:
3196 case UnqualifiedIdKind::IK_LiteralOperatorId:
3197 case UnqualifiedIdKind::IK_TemplateId:
3198 T = ConvertDeclSpecToType(state);
3199
3200 if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) {
3201 OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
3202 // Owned declaration is embedded in declarator.
3203 OwnedTagDecl->setEmbeddedInDeclarator(true);
3204 }
3205 break;
3206
3207 case UnqualifiedIdKind::IK_ConstructorName:
3208 case UnqualifiedIdKind::IK_ConstructorTemplateId:
3209 case UnqualifiedIdKind::IK_DestructorName:
3210 // Constructors and destructors don't have return types. Use
3211 // "void" instead.
3212 T = SemaRef.Context.VoidTy;
3213 processTypeAttrs(state, T, TAL_DeclSpec,
3214 D.getMutableDeclSpec().getAttributes());
3215 break;
3216
3217 case UnqualifiedIdKind::IK_DeductionGuideName:
3218 // Deduction guides have a trailing return type and no type in their
3219 // decl-specifier sequence. Use a placeholder return type for now.
3220 T = SemaRef.Context.DependentTy;
3221 break;
3222
3223 case UnqualifiedIdKind::IK_ConversionFunctionId:
3224 // The result type of a conversion function is the type that it
3225 // converts to.
3226 T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId,
3227 &ReturnTypeInfo);
3228 break;
3229 }
3230
3231 if (!D.getAttributes().empty())
3232 distributeTypeAttrsFromDeclarator(state, T);
3233
3234 // Find the deduced type in this type. Look in the trailing return type if we
3235 // have one, otherwise in the DeclSpec type.
3236 // FIXME: The standard wording doesn't currently describe this.
3237 DeducedType *Deduced = T->getContainedDeducedType();
3238 bool DeducedIsTrailingReturnType = false;
3239 if (Deduced && isa<AutoType>(Deduced) && D.hasTrailingReturnType()) {
3240 QualType T = SemaRef.GetTypeFromParser(D.getTrailingReturnType());
3241 Deduced = T.isNull() ? nullptr : T->getContainedDeducedType();
3242 DeducedIsTrailingReturnType = true;
3243 }
3244
3245 // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context.
3246 if (Deduced) {
3247 AutoType *Auto = dyn_cast<AutoType>(Deduced);
3248 int Error = -1;
3249
3250 // Is this a 'auto' or 'decltype(auto)' type (as opposed to __auto_type or
3251 // class template argument deduction)?
3252 bool IsCXXAutoType =
3253 (Auto && Auto->getKeyword() != AutoTypeKeyword::GNUAutoType);
3254 bool IsDeducedReturnType = false;
3255
3256 switch (D.getContext()) {
3257 case DeclaratorContext::LambdaExprContext:
3258 // Declared return type of a lambda-declarator is implicit and is always
3259 // 'auto'.
3260 break;
3261 case DeclaratorContext::ObjCParameterContext:
3262 case DeclaratorContext::ObjCResultContext:
3263 Error = 0;
3264 break;
3265 case DeclaratorContext::RequiresExprContext:
3266 Error = 22;
3267 break;
3268 case DeclaratorContext::PrototypeContext:
3269 case DeclaratorContext::LambdaExprParameterContext: {
3270 InventedTemplateParameterInfo *Info = nullptr;
3271 if (D.getContext() == DeclaratorContext::PrototypeContext) {
3272 // With concepts we allow 'auto' in function parameters.
3273 if (!SemaRef.getLangOpts().CPlusPlus20 || !Auto ||
3274 Auto->getKeyword() != AutoTypeKeyword::Auto) {
3275 Error = 0;
3276 break;
3277 } else if (!SemaRef.getCurScope()->isFunctionDeclarationScope()) {
3278 Error = 21;
3279 break;
3280 }
3281
3282 Info = &SemaRef.InventedParameterInfos.back();
3283 } else {
3284 // In C++14, generic lambdas allow 'auto' in their parameters.
3285 if (!SemaRef.getLangOpts().CPlusPlus14 || !Auto ||
3286 Auto->getKeyword() != AutoTypeKeyword::Auto) {
3287 Error = 16;
3288 break;
3289 }
3290 Info = SemaRef.getCurLambda();
3291 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~++20200806111125+5446ec85070/clang/lib/Sema/SemaType.cpp"
, 3291, __PRETTY_FUNCTION__))
;
3292 }
3293
3294 // We'll deal with inventing template parameters for 'auto' in trailing
3295 // return types when we pick up the trailing return type when processing
3296 // the function chunk.
3297 if (!DeducedIsTrailingReturnType)
3298 T = InventTemplateParameter(state, T, nullptr, Auto, *Info).first;
3299 break;
3300 }
3301 case DeclaratorContext::MemberContext: {
3302 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static ||
3303 D.isFunctionDeclarator())
3304 break;
3305 bool Cxx = SemaRef.getLangOpts().CPlusPlus;
3306 if (isa<ObjCContainerDecl>(SemaRef.CurContext)) {
3307 Error = 6; // Interface member.
3308 } else {
3309 switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) {
3310 case TTK_Enum: llvm_unreachable("unhandled tag kind")::llvm::llvm_unreachable_internal("unhandled tag kind", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaType.cpp"
, 3310)
;
3311 case TTK_Struct: Error = Cxx ? 1 : 2; /* Struct member */ break;
3312 case TTK_Union: Error = Cxx ? 3 : 4; /* Union member */ break;
3313 case TTK_Class: Error = 5; /* Class member */ break;
3314 case TTK_Interface: Error = 6; /* Interface member */ break;
3315 }
3316 }
3317 if (D.getDeclSpec().isFriendSpecified())
3318 Error = 20; // Friend type
3319 break;
3320 }
3321 case DeclaratorContext::CXXCatchContext:
3322 case DeclaratorContext::ObjCCatchContext:
3323 Error = 7; // Exception declaration
3324 break;
3325 case DeclaratorContext::TemplateParamContext:
3326 if (isa<DeducedTemplateSpecializationType>(Deduced))
3327 Error = 19; // Template parameter
3328 else if (!SemaRef.getLangOpts().CPlusPlus17)
3329 Error = 8; // Template parameter (until C++17)
3330 break;
3331 case DeclaratorContext::BlockLiteralContext:
3332 Error = 9; // Block literal
3333 break;
3334 case DeclaratorContext::TemplateArgContext:
3335 // Within a template argument list, a deduced template specialization
3336 // type will be reinterpreted as a template template argument.
3337 if (isa<DeducedTemplateSpecializationType>(Deduced) &&
3338 !D.getNumTypeObjects() &&
3339 D.getDeclSpec().getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier)
3340 break;
3341 LLVM_FALLTHROUGH[[gnu::fallthrough]];
3342 case DeclaratorContext::TemplateTypeArgContext:
3343 Error = 10; // Template type argument
3344 break;
3345 case DeclaratorContext::AliasDeclContext:
3346 case DeclaratorContext::AliasTemplateContext:
3347 Error = 12; // Type alias
3348 break;
3349 case DeclaratorContext::TrailingReturnContext:
3350 case DeclaratorContext::TrailingReturnVarContext:
3351 if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType)
3352 Error = 13; // Function return type
3353 IsDeducedReturnType = true;
3354 break;
3355 case DeclaratorContext::ConversionIdContext:
3356 if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType)
3357 Error = 14; // conversion-type-id
3358 IsDeducedReturnType = true;
3359 break;
3360 case DeclaratorContext::FunctionalCastContext:
3361 if (isa<DeducedTemplateSpecializationType>(Deduced))
3362 break;
3363 LLVM_FALLTHROUGH[[gnu::fallthrough]];
3364 case DeclaratorContext::TypeNameContext:
3365 Error = 15; // Generic
3366 break;
3367 case DeclaratorContext::FileContext:
3368 case DeclaratorContext::BlockContext:
3369 case DeclaratorContext::ForContext:
3370 case DeclaratorContext::InitStmtContext:
3371 case DeclaratorContext::ConditionContext:
3372 // FIXME: P0091R3 (erroneously) does not permit class template argument
3373 // deduction in conditions, for-init-statements, and other declarations
3374 // that are not simple-declarations.
3375 break;
3376 case DeclaratorContext::CXXNewContext:
3377 // FIXME: P0091R3 does not permit class template argument deduction here,
3378 // but we follow GCC and allow it anyway.
3379 if (!IsCXXAutoType && !isa<DeducedTemplateSpecializationType>(Deduced))
3380 Error = 17; // 'new' type
3381 break;
3382 case DeclaratorContext::KNRTypeListContext:
3383 Error = 18; // K&R function parameter
3384 break;
3385 }
3386
3387 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
3388 Error = 11;
3389
3390 // In Objective-C it is an error to use 'auto' on a function declarator
3391 // (and everywhere for '__auto_type').
3392 if (D.isFunctionDeclarator() &&
3393 (!SemaRef.getLangOpts().CPlusPlus11 || !IsCXXAutoType))
3394 Error = 13;
3395
3396 SourceRange AutoRange = D.getDeclSpec().getTypeSpecTypeLoc();
3397 if (D.getName().getKind() == UnqualifiedIdKind::IK_ConversionFunctionId)
3398 AutoRange = D.getName().getSourceRange();
3399
3400 if (Error != -1) {
3401 unsigned Kind;
3402 if (Auto) {
3403 switch (Auto->getKeyword()) {
3404 case AutoTypeKeyword::Auto: Kind = 0; break;
3405 case AutoTypeKeyword::DecltypeAuto: Kind = 1; break;
3406 case AutoTypeKeyword::GNUAutoType: Kind = 2; break;
3407 }
3408 } else {
3409 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~++20200806111125+5446ec85070/clang/lib/Sema/SemaType.cpp"
, 3410, __PRETTY_FUNCTION__))
3410 "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~++20200806111125+5446ec85070/clang/lib/Sema/SemaType.cpp"
, 3410, __PRETTY_FUNCTION__))
;
3411 Kind = 3;
3412 }
3413
3414 auto *DTST = dyn_cast<DeducedTemplateSpecializationType>(Deduced);
3415 TemplateName TN = DTST ? DTST->getTemplateName() : TemplateName();
3416
3417 SemaRef.Diag(AutoRange.getBegin(), diag::err_auto_not_allowed)
3418 << Kind << Error << (int)SemaRef.getTemplateNameKindForDiagnostics(TN)
3419 << QualType(Deduced, 0) << AutoRange;
3420 if (auto *TD = TN.getAsTemplateDecl())
3421 SemaRef.Diag(TD->getLocation(), diag::note_template_decl_here);
3422
3423 T = SemaRef.Context.IntTy;
3424 D.setInvalidType(true);
3425 } else if (Auto && D.getContext() != DeclaratorContext::LambdaExprContext) {
3426 // If there was a trailing return type, we already got
3427 // warn_cxx98_compat_trailing_return_type in the parser.
3428 SemaRef.Diag(AutoRange.getBegin(),
3429 D.getContext() ==
3430 DeclaratorContext::LambdaExprParameterContext
3431 ? diag::warn_cxx11_compat_generic_lambda
3432 : IsDeducedReturnType
3433 ? diag::warn_cxx11_compat_deduced_return_type
3434 : diag::warn_cxx98_compat_auto_type_specifier)
3435 << AutoRange;
3436 }
3437 }
3438
3439 if (SemaRef.getLangOpts().CPlusPlus &&
3440 OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) {
3441 // Check the contexts where C++ forbids the declaration of a new class
3442 // or enumeration in a type-specifier-seq.
3443 unsigned DiagID = 0;
3444 switch (D.getContext()) {
3445 case DeclaratorContext::TrailingReturnContext:
3446 case DeclaratorContext::TrailingReturnVarContext:
3447 // Class and enumeration definitions are syntactically not allowed in
3448 // trailing return types.
3449 llvm_unreachable("parser should not have allowed this")::llvm::llvm_unreachable_internal("parser should not have allowed this"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaType.cpp"
, 3449)
;
3450 break;
3451 case DeclaratorContext::FileContext:
3452 case DeclaratorContext::MemberContext:
3453 case DeclaratorContext::BlockContext:
3454 case DeclaratorContext::ForContext:
3455 case DeclaratorContext::InitStmtContext:
3456 case DeclaratorContext::BlockLiteralContext:
3457 case DeclaratorContext::LambdaExprContext:
3458 // C++11 [dcl.type]p3:
3459 // A type-specifier-seq shall not define a class or enumeration unless
3460 // it appears in the type-id of an alias-declaration (7.1.3) that is not
3461 // the declaration of a template-declaration.
3462 case DeclaratorContext::AliasDeclContext:
3463 break;
3464 case DeclaratorContext::AliasTemplateContext:
3465 DiagID = diag::err_type_defined_in_alias_template;
3466 break;
3467 case DeclaratorContext::TypeNameContext:
3468 case DeclaratorContext::FunctionalCastContext:
3469 case DeclaratorContext::ConversionIdContext:
3470 case DeclaratorContext::TemplateParamContext:
3471 case DeclaratorContext::CXXNewContext:
3472 case DeclaratorContext::CXXCatchContext:
3473 case DeclaratorContext::ObjCCatchContext:
3474 case DeclaratorContext::TemplateArgContext:
3475 case DeclaratorContext::TemplateTypeArgContext:
3476 DiagID = diag::err_type_defined_in_type_specifier;
3477 break;
3478 case DeclaratorContext::PrototypeContext:
3479 case DeclaratorContext::LambdaExprParameterContext:
3480 case DeclaratorContext::ObjCParameterContext:
3481 case DeclaratorContext::ObjCResultContext:
3482 case DeclaratorContext::KNRTypeListContext:
3483 case DeclaratorContext::RequiresExprContext:
3484 // C++ [dcl.fct]p6:
3485 // Types shall not be defined in return or parameter types.
3486 DiagID = diag::err_type_defined_in_param_type;
3487 break;
3488 case DeclaratorContext::ConditionContext:
3489 // C++ 6.4p2:
3490 // The type-specifier-seq shall not contain typedef and shall not declare
3491 // a new class or enumeration.
3492 DiagID = diag::err_type_defined_in_condition;
3493 break;
3494 }
3495
3496 if (DiagID != 0) {
3497 SemaRef.Diag(OwnedTagDecl->getLocation(), DiagID)
3498 << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
3499 D.setInvalidType(true);
3500 }
3501 }
3502
3503 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~++20200806111125+5446ec85070/clang/lib/Sema/SemaType.cpp"
, 3503, __PRETTY_FUNCTION__))
;
3504 return T;
3505}
3506
3507/// Produce an appropriate diagnostic for an ambiguity between a function
3508/// declarator and a C++ direct-initializer.
3509static void warnAboutAmbiguousFunction(Sema &S, Declarator &D,
3510 DeclaratorChunk &DeclType, QualType RT) {
3511 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
3512 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~++20200806111125+5446ec85070/clang/lib/Sema/SemaType.cpp"
, 3512, __PRETTY_FUNCTION__))
;
3513
3514 // If the return type is void there is no ambiguity.
3515 if (RT->isVoidType())
3516 return;
3517
3518 // An initializer for a non-class type can have at most one argument.
3519 if (!RT->isRecordType() && FTI.NumParams > 1)
3520 return;
3521
3522 // An initializer for a reference must have exactly one argument.
3523 if (RT->isReferenceType() && FTI.NumParams != 1)
3524 return;
3525
3526 // Only warn if this declarator is declaring a function at block scope, and
3527 // doesn't have a storage class (such as 'extern') specified.
3528 if (!D.isFunctionDeclarator() ||
3529 D.getFunctionDefinitionKind() != FDK_Declaration ||
3530 !S.CurContext->isFunctionOrMethod() ||
3531 D.getDeclSpec().getStorageClassSpec()
3532 != DeclSpec::SCS_unspecified)
3533 return;
3534
3535 // Inside a condition, a direct initializer is not permitted. We allow one to
3536 // be parsed in order to give better diagnostics in condition parsing.
3537 if (D.getContext() == DeclaratorContext::ConditionContext)
3538 return;
3539
3540 SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc);
3541
3542 S.Diag(DeclType.Loc,
3543 FTI.NumParams ? diag::warn_parens_disambiguated_as_function_declaration
3544 : diag::warn_empty_parens_are_function_decl)
3545 << ParenRange;
3546
3547 // If the declaration looks like:
3548 // T var1,
3549 // f();
3550 // and name lookup finds a function named 'f', then the ',' was
3551 // probably intended to be a ';'.
3552 if (!D.isFirstDeclarator() && D.getIdentifier()) {
3553 FullSourceLoc Comma(D.getCommaLoc(), S.SourceMgr);
3554 FullSourceLoc Name(D.getIdentifierLoc(), S.SourceMgr);
3555 if (Comma.getFileID() != Name.getFileID() ||
3556 Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) {
3557 LookupResult Result(S, D.getIdentifier(), SourceLocation(),
3558 Sema::LookupOrdinaryName);
3559 if (S.LookupName(Result, S.getCurScope()))
3560 S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call)
3561 << FixItHint::CreateReplacement(D.getCommaLoc(), ";")
3562 << D.getIdentifier();
3563 Result.suppressDiagnostics();
3564 }
3565 }
3566
3567 if (FTI.NumParams > 0) {
3568 // For a declaration with parameters, eg. "T var(T());", suggest adding
3569 // parens around the first parameter to turn the declaration into a
3570 // variable declaration.
3571 SourceRange Range = FTI.Params[0].Param->getSourceRange();
3572 SourceLocation B = Range.getBegin();
3573 SourceLocation E = S.getLocForEndOfToken(Range.getEnd());
3574 // FIXME: Maybe we should suggest adding braces instead of parens
3575 // in C++11 for classes that don't have an initializer_list constructor.
3576 S.Diag(B, diag::note_additional_parens_for_variable_declaration)
3577 << FixItHint::CreateInsertion(B, "(")
3578 << FixItHint::CreateInsertion(E, ")");
3579 } else {
3580 // For a declaration without parameters, eg. "T var();", suggest replacing
3581 // the parens with an initializer to turn the declaration into a variable
3582 // declaration.
3583 const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
3584
3585 // Empty parens mean value-initialization, and no parens mean
3586 // default initialization. These are equivalent if the default
3587 // constructor is user-provided or if zero-initialization is a
3588 // no-op.
3589 if (RD && RD->hasDefinition() &&
3590 (RD->isEmpty() || RD->hasUserProvidedDefaultConstructor()))
3591 S.Diag(DeclType.Loc, diag::note_empty_parens_default_ctor)
3592 << FixItHint::CreateRemoval(ParenRange);
3593 else {
3594 std::string Init =
3595 S.getFixItZeroInitializerForType(RT, ParenRange.getBegin());
3596 if (Init.empty() && S.LangOpts.CPlusPlus11)
3597 Init = "{}";
3598 if (!Init.empty())
3599 S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize)
3600 << FixItHint::CreateReplacement(ParenRange, Init);
3601 }
3602 }
3603}
3604
3605/// Produce an appropriate diagnostic for a declarator with top-level
3606/// parentheses.
3607static void warnAboutRedundantParens(Sema &S, Declarator &D, QualType T) {
3608 DeclaratorChunk &Paren = D.getTypeObject(D.getNumTypeObjects() - 1);
3609 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~++20200806111125+5446ec85070/clang/lib/Sema/SemaType.cpp"
, 3610, __PRETTY_FUNCTION__))
3610 "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~++20200806111125+5446ec85070/clang/lib/Sema/SemaType.cpp"
, 3610, __PRETTY_FUNCTION__))
;
3611
3612 // This is a syntactic check; we're not interested in cases that arise
3613 // during template instantiation.
3614 if (S.inTemplateInstantiation())
3615 return;
3616
3617 // Check whether this could be intended to be a construction of a temporary
3618 // object in C++ via a function-style cast.
3619 bool CouldBeTemporaryObject =
3620 S.getLangOpts().CPlusPlus && D.isExpressionContext() &&
3621 !D.isInvalidType() && D.getIdentifier() &&
3622 D.getDeclSpec().getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier &&
3623 (T->isRecordType() || T->isDependentType()) &&
3624 D.getDeclSpec().getTypeQualifiers() == 0 && D.isFirstDeclarator();
3625
3626 bool StartsWithDeclaratorId = true;
3627 for (auto &C : D.type_objects()) {
3628 switch (C.Kind) {
3629 case DeclaratorChunk::Paren:
3630 if (&C == &Paren)
3631 continue;
3632 LLVM_FALLTHROUGH[[gnu::fallthrough]];
3633 case DeclaratorChunk::Pointer:
3634 StartsWithDeclaratorId = false;
3635 continue;
3636
3637 case DeclaratorChunk::Array:
3638 if (!C.Arr.NumElts)
3639 CouldBeTemporaryObject = false;
3640 continue;
3641
3642 case DeclaratorChunk::Reference:
3643 // FIXME: Suppress the warning here if there is no initializer; we're
3644 // going to give an error anyway.
3645 // We assume that something like 'T (&x) = y;' is highly likely to not
3646 // be intended to be a temporary object.
3647 CouldBeTemporaryObject = false;
3648 StartsWithDeclaratorId = false;
3649 continue;
3650
3651 case DeclaratorChunk::Function:
3652 // In a new-type-id, function chunks require parentheses.
3653 if (D.getContext() == DeclaratorContext::CXXNewContext)
3654 return;
3655 // FIXME: "A(f())" deserves a vexing-parse warning, not just a
3656 // redundant-parens warning, but we don't know whether the function
3657 // chunk was syntactically valid as an expression here.
3658 CouldBeTemporaryObject = false;
3659 continue;
3660
3661 case DeclaratorChunk::BlockPointer:
3662 case DeclaratorChunk::MemberPointer:
3663 case DeclaratorChunk::Pipe:
3664 // These cannot appear in expressions.
3665 CouldBeTemporaryObject = false;
3666 StartsWithDeclaratorId = false;
3667 continue;
3668 }
3669 }
3670
3671 // FIXME: If there is an initializer, assume that this is not intended to be
3672 // a construction of a temporary object.
3673
3674 // Check whether the name has already been declared; if not, this is not a
3675 // function-style cast.
3676 if (CouldBeTemporaryObject) {
3677 LookupResult Result(S, D.getIdentifier(), SourceLocation(),
3678 Sema::LookupOrdinaryName);
3679 if (!S.LookupName(Result, S.getCurScope()))
3680 CouldBeTemporaryObject = false;
3681 Result.suppressDiagnostics();
3682 }
3683
3684 SourceRange ParenRange(Paren.Loc, Paren.EndLoc);
3685
3686 if (!CouldBeTemporaryObject) {
3687 // If we have A (::B), the parentheses affect the meaning of the program.
3688 // Suppress the warning in that case. Don't bother looking at the DeclSpec
3689 // here: even (e.g.) "int ::x" is visually ambiguous even though it's
3690 // formally unambiguous.
3691 if (StartsWithDeclaratorId && D.getCXXScopeSpec().isValid()) {
3692 for (NestedNameSpecifier *NNS = D.getCXXScopeSpec().getScopeRep(); NNS;
3693 NNS = NNS->getPrefix()) {
3694 if (NNS->getKind() == NestedNameSpecifier::Global)
3695 return;
3696 }
3697 }
3698
3699 S.Diag(Paren.Loc, diag::warn_redundant_parens_around_declarator)
3700 << ParenRange << FixItHint::CreateRemoval(Paren.Loc)
3701 << FixItHint::CreateRemoval(Paren.EndLoc);
3702 return;
3703 }
3704
3705 S.Diag(Paren.Loc, diag::warn_parens_disambiguated_as_variable_declaration)
3706 << ParenRange << D.getIdentifier();
3707 auto *RD = T->getAsCXXRecordDecl();
3708 if (!RD || !RD->hasDefinition() || RD->hasNonTrivialDestructor())
3709 S.Diag(Paren.Loc, diag::note_raii_guard_add_name)
3710 << FixItHint::CreateInsertion(Paren.Loc, " varname") << T
3711 << D.getIdentifier();
3712 // FIXME: A cast to void is probably a better suggestion in cases where it's
3713 // valid (when there is no initializer and we're not in a condition).
3714 S.Diag(D.getBeginLoc(), diag::note_function_style_cast_add_parentheses)
3715 << FixItHint::CreateInsertion(D.getBeginLoc(), "(")
3716 << FixItHint::CreateInsertion(S.getLocForEndOfToken(D.getEndLoc()), ")");
3717 S.Diag(Paren.Loc, diag::note_remove_parens_for_variable_declaration)
3718 << FixItHint::CreateRemoval(Paren.Loc)
3719 << FixItHint::CreateRemoval(Paren.EndLoc);
3720}
3721
3722/// Helper for figuring out the default CC for a function declarator type. If
3723/// this is the outermost chunk, then we can determine the CC from the
3724/// declarator context. If not, then this could be either a member function
3725/// type or normal function type.
3726static CallingConv getCCForDeclaratorChunk(
3727 Sema &S, Declarator &D, const ParsedAttributesView &AttrList,
3728 const DeclaratorChunk::FunctionTypeInfo &FTI, unsigned ChunkIndex) {
3729 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~++20200806111125+5446ec85070/clang/lib/Sema/SemaType.cpp"
, 3729, __PRETTY_FUNCTION__))
;
3730
3731 // Check for an explicit CC attribute.
3732 for (const ParsedAttr &AL : AttrList) {
3733 switch (AL.getKind()) {
3734 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
: {
3735 // Ignore attributes that don't validate or can't apply to the
3736 // function type. We'll diagnose the failure to apply them in
3737 // handleFunctionTypeAttr.
3738 CallingConv CC;
3739 if (!S.CheckCallingConvAttr(AL, CC) &&
3740 (!FTI.isVariadic || supportsVariadicCall(CC))) {
3741 return CC;
3742 }
3743 break;
3744 }
3745
3746 default:
3747 break;
3748 }
3749 }
3750
3751 bool IsCXXInstanceMethod = false;
3752
3753 if (S.getLangOpts().CPlusPlus) {
3754 // Look inwards through parentheses to see if this chunk will form a
3755 // member pointer type or if we're the declarator. Any type attributes
3756 // between here and there will override the CC we choose here.
3757 unsigned I = ChunkIndex;
3758 bool FoundNonParen = false;
3759 while (I && !FoundNonParen) {
3760 --I;
3761 if (D.getTypeObject(I).Kind != DeclaratorChunk::Paren)
3762 FoundNonParen = true;
3763 }
3764
3765 if (FoundNonParen) {
3766 // If we're not the declarator, we're a regular function type unless we're
3767 // in a member pointer.
3768 IsCXXInstanceMethod =
3769 D.getTypeObject(I).Kind == DeclaratorChunk::MemberPointer;
3770 } else if (D.getContext() == DeclaratorContext::LambdaExprContext) {
3771 // This can only be a call operator for a lambda, which is an instance
3772 // method.
3773 IsCXXInstanceMethod = true;
3774 } else {
3775 // We're the innermost decl chunk, so must be a function declarator.
3776 assert(D.isFunctionDeclarator())((D.isFunctionDeclarator()) ? static_cast<void> (0) : __assert_fail
("D.isFunctionDeclarator()", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaType.cpp"
, 3776, __PRETTY_FUNCTION__))
;
3777
3778 // If we're inside a record, we're declaring a method, but it could be
3779 // explicitly or implicitly static.
3780 IsCXXInstanceMethod =
3781 D.isFirstDeclarationOfMember() &&
3782 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
3783 !D.isStaticMember();
3784 }
3785 }
3786
3787 CallingConv CC = S.Context.getDefaultCallingConvention(FTI.isVariadic,
3788 IsCXXInstanceMethod);
3789
3790 // Attribute AT_OpenCLKernel affects the calling convention for SPIR
3791 // and AMDGPU targets, hence it cannot be treated as a calling
3792 // convention attribute. This is the simplest place to infer
3793 // calling convention for OpenCL kernels.
3794 if (S.getLangOpts().OpenCL) {
3795 for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) {
3796 if (AL.getKind() == ParsedAttr::AT_OpenCLKernel) {
3797 CC = CC_OpenCLKernel;
3798 break;
3799 }
3800 }
3801 }
3802
3803 return CC;
3804}
3805
3806namespace {
3807 /// A simple notion of pointer kinds, which matches up with the various
3808 /// pointer declarators.
3809 enum class SimplePointerKind {
3810 Pointer,
3811 BlockPointer,
3812 MemberPointer,
3813 Array,
3814 };
3815} // end anonymous namespace
3816
3817IdentifierInfo *Sema::getNullabilityKeyword(NullabilityKind nullability) {
3818 switch (nullability) {
3819 case NullabilityKind::NonNull:
3820 if (!Ident__Nonnull)
3821 Ident__Nonnull = PP.getIdentifierInfo("_Nonnull");
3822 return Ident__Nonnull;
3823
3824 case NullabilityKind::Nullable:
3825 if (!Ident__Nullable)
3826 Ident__Nullable = PP.getIdentifierInfo("_Nullable");
3827 return Ident__Nullable;
3828
3829 case NullabilityKind::Unspecified:
3830 if (!Ident__Null_unspecified)
3831 Ident__Null_unspecified = PP.getIdentifierInfo("_Null_unspecified");
3832 return Ident__Null_unspecified;
3833 }
3834 llvm_unreachable("Unknown nullability kind.")::llvm::llvm_unreachable_internal("Unknown nullability kind."
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaType.cpp"
, 3834)
;
3835}
3836
3837/// Retrieve the identifier "NSError".
3838IdentifierInfo *Sema::getNSErrorIdent() {
3839 if (!Ident_NSError)
3840 Ident_NSError = PP.getIdentifierInfo("NSError");
3841
3842 return Ident_NSError;
3843}
3844
3845/// Check whether there is a nullability attribute of any kind in the given
3846/// attribute list.
3847static bool hasNullabilityAttr(const ParsedAttributesView &attrs) {
3848 for (const ParsedAttr &AL : attrs) {
3849 if (AL.getKind() == ParsedAttr::AT_TypeNonNull ||
3850 AL.getKind() == ParsedAttr::AT_TypeNullable ||
3851 AL.getKind() == ParsedAttr::AT_TypeNullUnspecified)
3852 return true;
3853 }
3854
3855 return false;
3856}
3857
3858namespace {
3859 /// Describes the kind of a pointer a declarator describes.
3860 enum class PointerDeclaratorKind {
3861 // Not a pointer.
3862 NonPointer,
3863 // Single-level pointer.
3864 SingleLevelPointer,
3865 // Multi-level pointer (of any pointer kind).
3866 MultiLevelPointer,
3867 // CFFooRef*
3868 MaybePointerToCFRef,
3869 // CFErrorRef*
3870 CFErrorRefPointer,
3871 // NSError**
3872 NSErrorPointerPointer,
3873 };
3874
3875 /// Describes a declarator chunk wrapping a pointer that marks inference as
3876 /// unexpected.
3877 // These values must be kept in sync with diagnostics.
3878 enum class PointerWrappingDeclaratorKind {
3879 /// Pointer is top-level.
3880 None = -1,
3881 /// Pointer is an array element.
3882 Array = 0,
3883 /// Pointer is the referent type of a C++ reference.
3884 Reference = 1
3885 };
3886} // end anonymous namespace
3887
3888/// Classify the given declarator, whose type-specified is \c type, based on
3889/// what kind of pointer it refers to.
3890///
3891/// This is used to determine the default nullability.
3892static PointerDeclaratorKind
3893classifyPointerDeclarator(Sema &S, QualType type, Declarator &declarator,
3894 PointerWrappingDeclaratorKind &wrappingKind) {
3895 unsigned numNormalPointers = 0;
3896
3897 // For any dependent type, we consider it a non-pointer.
3898 if (type->isDependentType())
3899 return PointerDeclaratorKind::NonPointer;
3900
3901 // Look through the declarator chunks to identify pointers.
3902 for (unsigned i = 0, n = declarator.getNumTypeObjects(); i != n; ++i) {
3903 DeclaratorChunk &chunk = declarator.getTypeObject(i);
3904 switch (chunk.Kind) {
3905 case DeclaratorChunk::Array:
3906 if (numNormalPointers == 0)
3907 wrappingKind = PointerWrappingDeclaratorKind::Array;
3908 break;
3909
3910 case DeclaratorChunk::Function:
3911 case DeclaratorChunk::Pipe:
3912 break;
3913
3914 case DeclaratorChunk::BlockPointer:
3915 case DeclaratorChunk::MemberPointer:
3916 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3917 : PointerDeclaratorKind::SingleLevelPointer;
3918
3919 case DeclaratorChunk::Paren:
3920 break;
3921
3922 case DeclaratorChunk::Reference:
3923 if (numNormalPointers == 0)
3924 wrappingKind = PointerWrappingDeclaratorKind::Reference;
3925 break;
3926
3927 case DeclaratorChunk::Pointer:
3928 ++numNormalPointers;
3929 if (numNormalPointers > 2)
3930 return PointerDeclaratorKind::MultiLevelPointer;
3931 break;
3932 }
3933 }
3934
3935 // Then, dig into the type specifier itself.
3936 unsigned numTypeSpecifierPointers = 0;
3937 do {
3938 // Decompose normal pointers.
3939 if (auto ptrType = type->getAs<PointerType>()) {
3940 ++numNormalPointers;
3941
3942 if (numNormalPointers > 2)
3943 return PointerDeclaratorKind::MultiLevelPointer;
3944
3945 type = ptrType->getPointeeType();
3946 ++numTypeSpecifierPointers;
3947 continue;
3948 }
3949
3950 // Decompose block pointers.
3951 if (type->getAs<BlockPointerType>()) {
3952 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3953 : PointerDeclaratorKind::SingleLevelPointer;
3954 }
3955
3956 // Decompose member pointers.
3957 if (type->getAs<MemberPointerType>()) {
3958 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3959 : PointerDeclaratorKind::SingleLevelPointer;
3960 }
3961
3962 // Look at Objective-C object pointers.
3963 if (auto objcObjectPtr = type->getAs<ObjCObjectPointerType>()) {
3964 ++numNormalPointers;
3965 ++numTypeSpecifierPointers;
3966
3967 // If this is NSError**, report that.
3968 if (auto objcClassDecl = objcObjectPtr->getInterfaceDecl()) {
3969 if (objcClassDecl->getIdentifier() == S.getNSErrorIdent() &&
3970 numNormalPointers == 2 && numTypeSpecifierPointers < 2) {
3971 return PointerDeclaratorKind::NSErrorPointerPointer;
3972 }
3973 }
3974
3975 break;
3976 }
3977
3978 // Look at Objective-C class types.
3979 if (auto objcClass = type->getAs<ObjCInterfaceType>()) {
3980 if (objcClass->getInterface()->getIdentifier() == S.getNSErrorIdent()) {
3981 if (numNormalPointers == 2 && numTypeSpecifierPointers < 2)
3982 return PointerDeclaratorKind::NSErrorPointerPointer;
3983 }
3984
3985 break;
3986 }
3987
3988 // If at this point we haven't seen a pointer, we won't see one.
3989 if (numNormalPointers == 0)
3990 return PointerDeclaratorKind::NonPointer;
3991
3992 if (auto recordType = type->getAs<RecordType>()) {
3993 RecordDecl *recordDecl = recordType->getDecl();
3994
3995 bool isCFError = false;
3996 if (S.CFError) {
3997 // If we already know about CFError, test it directly.
3998 isCFError = (S.CFError == recordDecl);
3999 } else {
4000 // Check whether this is CFError, which we identify based on its bridge
4001 // to NSError. CFErrorRef used to be declared with "objc_bridge" but is
4002 // now declared with "objc_bridge_mutable", so look for either one of
4003 // the two attributes.
4004 if (recordDecl->getTagKind() == TTK_Struct && numNormalPointers > 0) {
4005 IdentifierInfo *bridgedType = nullptr;
4006 if (auto bridgeAttr = recordDecl->getAttr<ObjCBridgeAttr>())
4007 bridgedType = bridgeAttr->getBridgedType();
4008 else if (auto bridgeAttr =
4009 recordDecl->getAttr<ObjCBridgeMutableAttr>())
4010 bridgedType = bridgeAttr->getBridgedType();
4011
4012 if (bridgedType == S.getNSErrorIdent()) {
4013 S.CFError = recordDecl;
4014 isCFError = true;
4015 }
4016 }
4017 }
4018
4019 // If this is CFErrorRef*, report it as such.
4020 if (isCFError && numNormalPointers == 2 && numTypeSpecifierPointers < 2) {
4021 return PointerDeclaratorKind::CFErrorRefPointer;
4022 }
4023 break;
4024 }
4025
4026 break;
4027 } while (true);
4028
4029 switch (numNormalPointers) {
4030 case 0:
4031 return PointerDeclaratorKind::NonPointer;
4032
4033 case 1:
4034 return PointerDeclaratorKind::SingleLevelPointer;
4035
4036 case 2:
4037 return PointerDeclaratorKind::MaybePointerToCFRef;
4038
4039 default:
4040 return PointerDeclaratorKind::MultiLevelPointer;
4041 }
4042}
4043
4044static FileID getNullabilityCompletenessCheckFileID(Sema &S,
4045 SourceLocation loc) {
4046 // If we're anywhere in a function, method, or closure context, don't perform
4047 // completeness checks.
4048 for (DeclContext *ctx = S.CurContext; ctx; ctx = ctx->getParent()) {
4049 if (ctx->isFunctionOrMethod())
4050 return FileID();
4051
4052 if (ctx->isFileContext())
4053 break;
4054 }
4055
4056 // We only care about the expansion location.
4057 loc = S.SourceMgr.getExpansionLoc(loc);
4058 FileID file = S.SourceMgr.getFileID(loc);
4059 if (file.isInvalid())
4060 return FileID();
4061
4062 // Retrieve file information.
4063 bool invalid = false;
4064 const SrcMgr::SLocEntry &sloc = S.SourceMgr.getSLocEntry(file, &invalid);
4065 if (invalid || !sloc.isFile())
4066 return FileID();
4067
4068 // We don't want to perform completeness checks on the main file or in
4069 // system headers.
4070 const SrcMgr::FileInfo &fileInfo = sloc.getFile();
4071 if (fileInfo.getIncludeLoc().isInvalid())
4072 return FileID();
4073 if (fileInfo.getFileCharacteristic() != SrcMgr::C_User &&
4074 S.Diags.getSuppressSystemWarnings()) {
4075 return FileID();
4076 }
4077
4078 return file;
4079}
4080
4081/// Creates a fix-it to insert a C-style nullability keyword at \p pointerLoc,
4082/// taking into account whitespace before and after.
4083static void fixItNullability(Sema &S, DiagnosticBuilder &Diag,
4084 SourceLocation PointerLoc,
4085 NullabilityKind Nullability) {
4086 assert(PointerLoc.isValid())((PointerLoc.isValid()) ? static_cast<void> (0) : __assert_fail
("PointerLoc.isValid()", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaType.cpp"
, 4086, __PRETTY_FUNCTION__))
;
4087 if (PointerLoc.isMacroID())
4088 return;
4089
4090 SourceLocation FixItLoc = S.getLocForEndOfToken(PointerLoc);
4091 if (!FixItLoc.isValid() || FixItLoc == PointerLoc)
4092 return;
4093
4094 const char *NextChar = S.SourceMgr.getCharacterData(FixItLoc);
4095 if (!NextChar)
4096 return;
4097
4098 SmallString<32> InsertionTextBuf{" "};
4099 InsertionTextBuf += getNullabilitySpelling(Nullability);
4100 InsertionTextBuf += " ";
4101 StringRef InsertionText = InsertionTextBuf.str();
4102
4103 if (isWhitespace(*NextChar)) {
4104 InsertionText = InsertionText.drop_back();
4105 } else if (NextChar[-1] == '[') {
4106 if (NextChar[0] == ']')
4107 InsertionText = InsertionText.drop_back().drop_front();
4108 else
4109 InsertionText = InsertionText.drop_front();
4110 } else if (!isIdentifierBody(NextChar[0], /*allow dollar*/true) &&
4111 !isIdentifierBody(NextChar[-1], /*allow dollar*/true)) {
4112 InsertionText = InsertionText.drop_back().drop_front();
4113 }
4114
4115 Diag << FixItHint::CreateInsertion(FixItLoc, InsertionText);
4116}
4117
4118static void emitNullabilityConsistencyWarning(Sema &S,
4119 SimplePointerKind PointerKind,
4120 SourceLocation PointerLoc,
4121 SourceLocation PointerEndLoc) {
4122 assert(PointerLoc.isValid())((PointerLoc.isValid()) ? static_cast<void> (0) : __assert_fail
("PointerLoc.isValid()", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaType.cpp"
, 4122, __PRETTY_FUNCTION__))
;
4123
4124 if (PointerKind == SimplePointerKind::Array) {
4125 S.Diag(PointerLoc, diag::warn_nullability_missing_array);
4126 } else {
4127 S.Diag(PointerLoc, diag::warn_nullability_missing)
4128 << static_cast<unsigned>(PointerKind);
4129 }
4130
4131 auto FixItLoc = PointerEndLoc.isValid() ? PointerEndLoc : PointerLoc;
4132 if (FixItLoc.isMacroID())
4133 return;
4134
4135 auto addFixIt = [&](NullabilityKind Nullability) {
4136 auto Diag = S.Diag(FixItLoc, diag::note_nullability_fix_it);
4137 Diag << static_cast<unsigned>(Nullability);
4138 Diag << static_cast<unsigned>(PointerKind);
4139 fixItNullability(S, Diag, FixItLoc, Nullability);
4140 };
4141 addFixIt(NullabilityKind::Nullable);
4142 addFixIt(NullabilityKind::NonNull);
4143}
4144
4145/// Complains about missing nullability if the file containing \p pointerLoc
4146/// has other uses of nullability (either the keywords or the \c assume_nonnull
4147/// pragma).
4148///
4149/// If the file has \e not seen other uses of nullability, this particular
4150/// pointer is saved for possible later diagnosis. See recordNullabilitySeen().
4151static void
4152checkNullabilityConsistency(Sema &S, SimplePointerKind pointerKind,
4153 SourceLocation pointerLoc,
4154 SourceLocation pointerEndLoc = SourceLocation()) {
4155 // Determine which file we're performing consistency checking for.
4156 FileID file = getNullabilityCompletenessCheckFileID(S, pointerLoc);
4157 if (file.isInvalid())
4158 return;
4159
4160 // If we haven't seen any type nullability in this file, we won't warn now
4161 // about anything.
4162 FileNullability &fileNullability = S.NullabilityMap[file];
4163 if (!fileNullability.SawTypeNullability) {
4164 // If this is the first pointer declarator in the file, and the appropriate
4165 // warning is on, record it in case we need to diagnose it retroactively.
4166 diag::kind diagKind;
4167 if (pointerKind == SimplePointerKind::Array)
4168 diagKind = diag::warn_nullability_missing_array;
4169 else
4170 diagKind = diag::warn_nullability_missing;
4171
4172 if (fileNullability.PointerLoc.isInvalid() &&
4173 !S.Context.getDiagnostics().isIgnored(diagKind, pointerLoc)) {
4174 fileNullability.PointerLoc = pointerLoc;
4175 fileNullability.PointerEndLoc = pointerEndLoc;
4176 fileNullability.PointerKind = static_cast<unsigned>(pointerKind);
4177 }
4178
4179 return;
4180 }
4181
4182 // Complain about missing nullability.
4183 emitNullabilityConsistencyWarning(S, pointerKind, pointerLoc, pointerEndLoc);
4184}
4185
4186/// Marks that a nullability feature has been used in the file containing
4187/// \p loc.
4188///
4189/// If this file already had pointer types in it that were missing nullability,
4190/// the first such instance is retroactively diagnosed.
4191///
4192/// \sa checkNullabilityConsistency
4193static void recordNullabilitySeen(Sema &S, SourceLocation loc) {
4194 FileID file = getNullabilityCompletenessCheckFileID(S, loc);
4195 if (file.isInvalid())
4196 return;
4197
4198 FileNullability &fileNullability = S.NullabilityMap[file];
4199 if (fileNullability.SawTypeNullability)
4200 return;
4201 fileNullability.SawTypeNullability = true;
4202
4203 // If we haven't seen any type nullability before, now we have. Retroactively
4204 // diagnose the first unannotated pointer, if there was one.
4205 if (fileNullability.PointerLoc.isInvalid())
4206 return;
4207
4208 auto kind = static_cast<SimplePointerKind>(fileNullability.PointerKind);
4209 emitNullabilityConsistencyWarning(S, kind, fileNullability.PointerLoc,
4210 fileNullability.PointerEndLoc);
4211}
4212
4213/// Returns true if any of the declarator chunks before \p endIndex include a
4214/// level of indirection: array, pointer, reference, or pointer-to-member.
4215///
4216/// Because declarator chunks are stored in outer-to-inner order, testing
4217/// every chunk before \p endIndex is testing all chunks that embed the current
4218/// chunk as part of their type.
4219///
4220/// It is legal to pass the result of Declarator::getNumTypeObjects() as the
4221/// end index, in which case all chunks are tested.
4222static bool hasOuterPointerLikeChunk(const Declarator &D, unsigned endIndex) {
4223 unsigned i = endIndex;
4224 while (i != 0) {
4225 // Walk outwards along the declarator chunks.
4226 --i;
4227 const DeclaratorChunk &DC = D.getTypeObject(i);
4228 switch (DC.Kind) {
4229 case DeclaratorChunk::Paren:
4230 break;
4231 case DeclaratorChunk::Array:
4232 case DeclaratorChunk::Pointer:
4233 case DeclaratorChunk::Reference:
4234 case DeclaratorChunk::MemberPointer:
4235 return true;
4236 case DeclaratorChunk::Function:
4237 case DeclaratorChunk::BlockPointer:
4238 case DeclaratorChunk::Pipe:
4239 // These are invalid anyway, so just ignore.
4240 break;
4241 }
4242 }
4243 return false;
4244}
4245
4246static bool IsNoDerefableChunk(DeclaratorChunk Chunk) {
4247 return (Chunk.Kind == DeclaratorChunk::Pointer ||
4248 Chunk.Kind == DeclaratorChunk::Array);
4249}
4250
4251template<typename AttrT>
4252static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4253 AL.setUsedAsTypeAttr();
4254 return ::new (Ctx) AttrT(Ctx, AL);
4255}
4256
4257static Attr *createNullabilityAttr(ASTContext &Ctx, ParsedAttr &Attr,
4258 NullabilityKind NK) {
4259 switch (NK) {
4260 case NullabilityKind::NonNull:
4261 return createSimpleAttr<TypeNonNullAttr>(Ctx, Attr);
4262
4263 case NullabilityKind::Nullable:
4264 return createSimpleAttr<TypeNullableAttr>(Ctx, Attr);
4265
4266 case NullabilityKind::Unspecified:
4267 return createSimpleAttr<TypeNullUnspecifiedAttr>(Ctx, Attr);
4268 }
4269 llvm_unreachable("unknown NullabilityKind")::llvm::llvm_unreachable_internal("unknown NullabilityKind", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaType.cpp"
, 4269)
;
4270}
4271
4272// Diagnose whether this is a case with the multiple addr spaces.
4273// Returns true if this is an invalid case.
4274// ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified
4275// by qualifiers for two or more different address spaces."
4276static bool DiagnoseMultipleAddrSpaceAttributes(Sema &S, LangAS ASOld,
4277 LangAS ASNew,
4278 SourceLocation AttrLoc) {
4279 if (ASOld != LangAS::Default) {
4280 if (ASOld != ASNew) {
4281 S.Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers);
4282 return true;
4283 }
4284 // Emit a warning if they are identical; it's likely unintended.
4285 S.Diag(AttrLoc,
4286 diag::warn_attribute_address_multiple_identical_qualifiers);
4287 }
4288 return false;
4289}
4290
4291static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
4292 QualType declSpecType,
4293 TypeSourceInfo *TInfo) {
4294 // The TypeSourceInfo that this function returns will not be a null type.
4295 // If there is an error, this function will fill in a dummy type as fallback.
4296 QualType T = declSpecType;
4297 Declarator &D = state.getDeclarator();
4298 Sema &S = state.getSema();
4299 ASTContext &Context = S.Context;
4300 const LangOptions &LangOpts = S.getLangOpts();
4301
4302 // The name we're declaring, if any.
4303 DeclarationName Name;
4304 if (D.getIdentifier())
4305 Name = D.getIdentifier();
4306
4307 // Does this declaration declare a typedef-name?
4308 bool IsTypedefName =
4309 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef ||
4310 D.getContext() == DeclaratorContext::AliasDeclContext ||
4311 D.getContext() == DeclaratorContext::AliasTemplateContext;
4312
4313 // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
4314 bool IsQualifiedFunction = T->isFunctionProtoType() &&
4315 (!T->castAs<FunctionProtoType>()->getMethodQuals().empty() ||
4316 T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None);
4317
4318 // If T is 'decltype(auto)', the only declarators we can have are parens
4319 // and at most one function declarator if this is a function declaration.
4320 // If T is a deduced class template specialization type, we can have no
4321 // declarator chunks at all.
4322 if (auto *DT = T->getAs<DeducedType>()) {
4323 const AutoType *AT = T->getAs<AutoType>();
4324 bool IsClassTemplateDeduction = isa<DeducedTemplateSpecializationType>(DT);
4325 if ((AT && AT->isDecltypeAuto()) || IsClassTemplateDeduction) {
4326 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4327 unsigned Index = E - I - 1;
4328 DeclaratorChunk &DeclChunk = D.getTypeObject(Index);
4329 unsigned DiagId = IsClassTemplateDeduction
4330 ? diag::err_deduced_class_template_compound_type
4331 : diag::err_decltype_auto_compound_type;
4332 unsigned DiagKind = 0;
4333 switch (DeclChunk.Kind) {
4334 case DeclaratorChunk::Paren:
4335 // FIXME: Rejecting this is a little silly.
4336 if (IsClassTemplateDeduction) {
4337 DiagKind = 4;
4338 break;
4339 }
4340 continue;
4341 case DeclaratorChunk::Function: {
4342 if (IsClassTemplateDeduction) {
4343 DiagKind = 3;
4344 break;
4345 }
4346 unsigned FnIndex;
4347 if (D.isFunctionDeclarationContext() &&
4348 D.isFunctionDeclarator(FnIndex) && FnIndex == Index)
4349 continue;
4350 DiagId = diag::err_decltype_auto_function_declarator_not_declaration;
4351 break;
4352 }
4353 case DeclaratorChunk::Pointer:
4354 case DeclaratorChunk::BlockPointer:
4355 case DeclaratorChunk::MemberPointer:
4356 DiagKind = 0;
4357 break;
4358 case DeclaratorChunk::Reference:
4359 DiagKind = 1;
4360 break;
4361 case DeclaratorChunk::Array:
4362 DiagKind = 2;
4363 break;
4364 case DeclaratorChunk::Pipe:
4365 break;
4366 }
4367
4368 S.Diag(DeclChunk.Loc, DiagId) << DiagKind;
4369 D.setInvalidType(true);
4370 break;
4371 }
4372 }
4373 }
4374
4375 // Determine whether we should infer _Nonnull on pointer types.
4376 Optional<NullabilityKind> inferNullability;
4377 bool inferNullabilityCS = false;
4378 bool inferNullabilityInnerOnly = false;
4379 bool inferNullabilityInnerOnlyComplete = false;
4380
4381 // Are we in an assume-nonnull region?
4382 bool inAssumeNonNullRegion = false;
4383 SourceLocation assumeNonNullLoc = S.PP.getPragmaAssumeNonNullLoc();
4384 if (assumeNonNullLoc.isValid()) {
4385 inAssumeNonNullRegion = true;
4386 recordNullabilitySeen(S, assumeNonNullLoc);
4387 }
4388
4389 // Whether to complain about missing nullability specifiers or not.
4390 enum {
4391 /// Never complain.
4392 CAMN_No,
4393 /// Complain on the inner pointers (but not the outermost
4394 /// pointer).
4395 CAMN_InnerPointers,
4396 /// Complain about any pointers that don't have nullability
4397 /// specified or inferred.
4398 CAMN_Yes
4399 } complainAboutMissingNullability = CAMN_No;
4400 unsigned NumPointersRemaining = 0;
4401 auto complainAboutInferringWithinChunk = PointerWrappingDeclaratorKind::None;
4402
4403 if (IsTypedefName) {
4404 // For typedefs, we do not infer any nullability (the default),
4405 // and we only complain about missing nullability specifiers on
4406 // inner pointers.
4407 complainAboutMissingNullability = CAMN_InnerPointers;
4408
4409 if (T->canHaveNullability(/*ResultIfUnknown*/false) &&
4410 !T->getNullability(S.Context)) {
4411 // Note that we allow but don't require nullability on dependent types.
4412 ++NumPointersRemaining;
4413 }
4414
4415 for (unsigned i = 0, n = D.getNumTypeObjects(); i != n; ++i) {
4416 DeclaratorChunk &chunk = D.getTypeObject(i);
4417 switch (chunk.Kind) {
4418 case DeclaratorChunk::Array:
4419 case DeclaratorChunk::Function:
4420 case DeclaratorChunk::Pipe:
4421 break;
4422
4423 case DeclaratorChunk::BlockPointer:
4424 case DeclaratorChunk::MemberPointer:
4425 ++NumPointersRemaining;
4426 break;
4427
4428 case DeclaratorChunk::Paren:
4429 case DeclaratorChunk::Reference:
4430 continue;
4431
4432 case DeclaratorChunk::Pointer:
4433 ++NumPointersRemaining;
4434 continue;
4435 }
4436 }
4437 } else {
4438 bool isFunctionOrMethod = false;
4439 switch (auto context = state.getDeclarator().getContext()) {
4440 case DeclaratorContext::ObjCParameterContext:
4441 case DeclaratorContext::ObjCResultContext:
4442 case DeclaratorContext::PrototypeContext:
4443 case DeclaratorContext::TrailingReturnContext:
4444 case DeclaratorContext::TrailingReturnVarContext:
4445 isFunctionOrMethod = true;
4446 LLVM_FALLTHROUGH[[gnu::fallthrough]];
4447
4448 case DeclaratorContext::MemberContext:
4449 if (state.getDeclarator().isObjCIvar() && !isFunctionOrMethod) {
4450 complainAboutMissingNullability = CAMN_No;
4451 break;
4452 }
4453
4454 // Weak properties are inferred to be nullable.
4455 if (state.getDeclarator().isObjCWeakProperty() && inAssumeNonNullRegion) {
4456 inferNullability = NullabilityKind::Nullable;
4457 break;
4458 }
4459
4460 LLVM_FALLTHROUGH[[gnu::fallthrough]];
4461
4462 case DeclaratorContext::FileContext:
4463 case DeclaratorContext::KNRTypeListContext: {
4464 complainAboutMissingNullability = CAMN_Yes;
4465
4466 // Nullability inference depends on the type and declarator.
4467 auto wrappingKind = PointerWrappingDeclaratorKind::None;
4468 switch (classifyPointerDeclarator(S, T, D, wrappingKind)) {
4469 case PointerDeclaratorKind::NonPointer:
4470 case PointerDeclaratorKind::MultiLevelPointer:
4471 // Cannot infer nullability.
4472 break;
4473
4474 case PointerDeclaratorKind::SingleLevelPointer:
4475 // Infer _Nonnull if we are in an assumes-nonnull region.
4476 if (inAssumeNonNullRegion) {
4477 complainAboutInferringWithinChunk = wrappingKind;
4478 inferNullability = NullabilityKind::NonNull;
4479 inferNullabilityCS =
4480 (context == DeclaratorContext::ObjCParameterContext ||
4481 context == DeclaratorContext::ObjCResultContext);
4482 }
4483 break;
4484
4485 case PointerDeclaratorKind::CFErrorRefPointer:
4486 case PointerDeclaratorKind::NSErrorPointerPointer:
4487 // Within a function or method signature, infer _Nullable at both
4488 // levels.
4489 if (isFunctionOrMethod && inAssumeNonNullRegion)
4490 inferNullability = NullabilityKind::Nullable;
4491 break;
4492
4493 case PointerDeclaratorKind::MaybePointerToCFRef:
4494 if (isFunctionOrMethod) {
4495 // On pointer-to-pointer parameters marked cf_returns_retained or
4496 // cf_returns_not_retained, if the outer pointer is explicit then
4497 // infer the inner pointer as _Nullable.
4498 auto hasCFReturnsAttr =
4499 [](const ParsedAttributesView &AttrList) -> bool {
4500 return AttrList.hasAttribute(ParsedAttr::AT_CFReturnsRetained) ||
4501 AttrList.hasAttribute(ParsedAttr::AT_CFReturnsNotRetained);
4502 };
4503 if (const auto *InnermostChunk = D.getInnermostNonParenChunk()) {
4504 if (hasCFReturnsAttr(D.getAttributes()) ||
4505 hasCFReturnsAttr(InnermostChunk->getAttrs()) ||
4506 hasCFReturnsAttr(D.getDeclSpec().getAttributes())) {
4507 inferNullability = NullabilityKind::Nullable;
4508 inferNullabilityInnerOnly = true;
4509 }
4510 }
4511 }
4512 break;
4513 }
4514 break;
4515 }
4516
4517 case DeclaratorContext::ConversionIdContext:
4518 complainAboutMissingNullability = CAMN_Yes;
4519 break;
4520
4521 case DeclaratorContext::AliasDeclContext:
4522 case DeclaratorContext::AliasTemplateContext:
4523 case DeclaratorContext::BlockContext:
4524 case DeclaratorContext::BlockLiteralContext:
4525 case DeclaratorContext::ConditionContext:
4526 case DeclaratorContext::CXXCatchContext:
4527 case DeclaratorContext::CXXNewContext:
4528 case DeclaratorContext::ForContext:
4529 case DeclaratorContext::InitStmtContext:
4530 case DeclaratorContext::LambdaExprContext:
4531 case DeclaratorContext::LambdaExprParameterContext:
4532 case DeclaratorContext::ObjCCatchContext:
4533 case DeclaratorContext::TemplateParamContext:
4534 case DeclaratorContext::TemplateArgContext:
4535 case DeclaratorContext::TemplateTypeArgContext:
4536 case DeclaratorContext::TypeNameContext:
4537 case DeclaratorContext::FunctionalCastContext:
4538 case DeclaratorContext::RequiresExprContext:
4539 // Don't infer in these contexts.
4540 break;
4541 }
4542 }
4543
4544 // Local function that returns true if its argument looks like a va_list.
4545 auto isVaList = [&S](QualType T) -> bool {
4546 auto *typedefTy = T->getAs<TypedefType>();
4547 if (!typedefTy)
4548 return false;
4549 TypedefDecl *vaListTypedef = S.Context.getBuiltinVaListDecl();
4550 do {
4551 if (typedefTy->getDecl() == vaListTypedef)
4552 return true;
4553 if (auto *name = typedefTy->getDecl()->getIdentifier())
4554 if (name->isStr("va_list"))
4555 return true;
4556 typedefTy = typedefTy->desugar()->getAs<TypedefType>();
4557 } while (typedefTy);
4558 return false;
4559 };
4560
4561 // Local function that checks the nullability for a given pointer declarator.
4562 // Returns true if _Nonnull was inferred.
4563 auto inferPointerNullability =
4564 [&](SimplePointerKind pointerKind, SourceLocation pointerLoc,
4565 SourceLocation pointerEndLoc,
4566 ParsedAttributesView &attrs, AttributePool &Pool) -> ParsedAttr * {
4567 // We've seen a pointer.
4568 if (NumPointersRemaining > 0)
4569 --NumPointersRemaining;
4570
4571 // If a nullability attribute is present, there's nothing to do.
4572 if (hasNullabilityAttr(attrs))
4573 return nullptr;
4574
4575 // If we're supposed to infer nullability, do so now.
4576 if (inferNullability && !inferNullabilityInnerOnlyComplete) {
4577 ParsedAttr::Syntax syntax = inferNullabilityCS
4578 ? ParsedAttr::AS_ContextSensitiveKeyword
4579 : ParsedAttr::AS_Keyword;
4580 ParsedAttr *nullabilityAttr = Pool.create(
4581 S.getNullabilityKeyword(*inferNullability), SourceRange(pointerLoc),
4582 nullptr, SourceLocation(), nullptr, 0, syntax);
4583
4584 attrs.addAtEnd(nullabilityAttr);
4585
4586 if (inferNullabilityCS) {
4587 state.getDeclarator().getMutableDeclSpec().getObjCQualifiers()
4588 ->setObjCDeclQualifier(ObjCDeclSpec::DQ_CSNullability);
4589 }
4590
4591 if (pointerLoc.isValid() &&
4592 complainAboutInferringWithinChunk !=
4593 PointerWrappingDeclaratorKind::None) {
4594 auto Diag =
4595 S.Diag(pointerLoc, diag::warn_nullability_inferred_on_nested_type);
4596 Diag << static_cast<int>(complainAboutInferringWithinChunk);
4597 fixItNullability(S, Diag, pointerLoc, NullabilityKind::NonNull);
4598 }
4599
4600 if (inferNullabilityInnerOnly)
4601 inferNullabilityInnerOnlyComplete = true;
4602 return nullabilityAttr;
4603 }
4604
4605 // If we're supposed to complain about missing nullability, do so
4606 // now if it's truly missing.
4607 switch (complainAboutMissingNullability) {
4608 case CAMN_No:
4609 break;
4610
4611 case CAMN_InnerPointers:
4612 if (NumPointersRemaining == 0)
4613 break;
4614 LLVM_FALLTHROUGH[[gnu::fallthrough]];
4615
4616 case CAMN_Yes:
4617 checkNullabilityConsistency(S, pointerKind, pointerLoc, pointerEndLoc);
4618 }
4619 return nullptr;
4620 };
4621
4622 // If the type itself could have nullability but does not, infer pointer
4623 // nullability and perform consistency checking.
4624 if (S.CodeSynthesisContexts.empty()) {
4625 if (T->canHaveNullability(/*ResultIfUnknown*/false) &&
4626 !T->getNullability(S.Context)) {
4627 if (isVaList(T)) {
4628 // Record that we've seen a pointer, but do nothing else.
4629 if (NumPointersRemaining > 0)
4630 --NumPointersRemaining;
4631 } else {
4632 SimplePointerKind pointerKind = SimplePointerKind::Pointer;
4633 if (T->isBlockPointerType())
4634 pointerKind = SimplePointerKind::BlockPointer;
4635 else if (T->isMemberPointerType())
4636 pointerKind = SimplePointerKind::MemberPointer;
4637
4638 if (auto *attr = inferPointerNullability(
4639 pointerKind, D.getDeclSpec().getTypeSpecTypeLoc(),
4640 D.getDeclSpec().getEndLoc(),
4641 D.getMutableDeclSpec().getAttributes(),
4642 D.getMutableDeclSpec().getAttributePool())) {
4643 T = state.getAttributedType(
4644 createNullabilityAttr(Context, *attr, *inferNullability), T, T);
4645 }
4646 }
4647 }
4648
4649 if (complainAboutMissingNullability == CAMN_Yes &&
4650 T->isArrayType() && !T->getNullability(S.Context) && !isVaList(T) &&
4651 D.isPrototypeContext() &&
4652 !hasOuterPointerLikeChunk(D, D.getNumTypeObjects())) {
4653 checkNullabilityConsistency(S, SimplePointerKind::Array,
4654 D.getDeclSpec().getTypeSpecTypeLoc());
4655 }
4656 }
4657
4658 bool ExpectNoDerefChunk =
4659 state.getCurrentAttributes().hasAttribute(ParsedAttr::AT_NoDeref);
4660
4661 // Walk the DeclTypeInfo, building the recursive type as we go.
4662 // DeclTypeInfos are ordered from the identifier out, which is
4663 // opposite of what we want :).
4664 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
4665 unsigned chunkIndex = e - i - 1;
4666 state.setCurrentChunkIndex(chunkIndex);
4667 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
4668 IsQualifiedFunction &= DeclType.Kind == DeclaratorChunk::Paren;
4669 switch (DeclType.Kind) {
4670 case DeclaratorChunk::Paren:
4671 if (i == 0)
4672 warnAboutRedundantParens(S, D, T);
4673 T = S.BuildParenType(T);
4674 break;
4675 case DeclaratorChunk::BlockPointer:
4676 // If blocks are disabled, emit an error.
4677 if (!LangOpts.Blocks)
4678 S.Diag(DeclType.Loc, diag::err_blocks_disable) << LangOpts.OpenCL;
4679
4680 // Handle pointer nullability.
4681 inferPointerNullability(SimplePointerKind::BlockPointer, DeclType.Loc,
4682 DeclType.EndLoc, DeclType.getAttrs(),
4683 state.getDeclarator().getAttributePool());
4684
4685 T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name);
4686 if (DeclType.Cls.TypeQuals || LangOpts.OpenCL) {
4687 // OpenCL v2.0, s6.12.5 - Block variable declarations are implicitly
4688 // qualified with const.
4689 if (LangOpts.OpenCL)
4690 DeclType.Cls.TypeQuals |= DeclSpec::TQ_const;
4691 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals);
4692 }
4693 break;
4694 case DeclaratorChunk::Pointer:
4695 // Verify that we're not building a pointer to pointer to function with
4696 // exception specification.
4697 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4698 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4699 D.setInvalidType(true);
4700 // Build the type anyway.
4701 }
4702
4703 // Handle pointer nullability
4704 inferPointerNullability(SimplePointerKind::Pointer, DeclType.Loc,
4705 DeclType.EndLoc, DeclType.getAttrs(),
4706 state.getDeclarator().getAttributePool());
4707
4708 if (LangOpts.ObjC && T->getAs<ObjCObjectType>()) {
4709 T = Context.getObjCObjectPointerType(T);
4710 if (DeclType.Ptr.TypeQuals)
4711 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
4712 break;
4713 }
4714
4715 // OpenCL v2.0 s6.9b - Pointer to image/sampler cannot be used.
4716 // OpenCL v2.0 s6.13.16.1 - Pointer to pipe cannot be used.
4717 // OpenCL v2.0 s6.12.5 - Pointers to Blocks are not allowed.
4718 if (LangOpts.OpenCL) {
4719 if (T->isImageType() || T->isSamplerT() || T->isPipeType() ||
4720 T->isBlockPointerType()) {
4721 S.Diag(D.getIdentifierLoc(), diag::err_opencl_pointer_to_type) << T;
4722 D.setInvalidType(true);
4723 }
4724 }
4725
4726 T = S.BuildPointerType(T, DeclType.Loc, Name);
4727 if (DeclType.Ptr.TypeQuals)
4728 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
4729 break;
4730 case DeclaratorChunk::Reference: {
4731 // Verify that we're not building a reference to pointer to function with
4732 // exception specification.
4733 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4734 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4735 D.setInvalidType(true);
4736 // Build the type anyway.
4737 }
4738 T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name);
4739
4740 if (DeclType.Ref.HasRestrict)
4741 T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict);
4742 break;
4743 }
4744 case DeclaratorChunk::Array: {
4745 // Verify that we're not building an array of pointers to function with
4746 // exception specification.
4747 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4748 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4749 D.setInvalidType(true);
4750 // Build the type anyway.
4751 }
4752 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
4753 Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
4754 ArrayType::ArraySizeModifier ASM;
4755 if (ATI.isStar)
4756 ASM = ArrayType::Star;
4757 else if (ATI.hasStatic)
4758 ASM = ArrayType::Static;
4759 else
4760 ASM = ArrayType::Normal;
4761 if (ASM == ArrayType::Star && !D.isPrototypeContext()) {
4762 // FIXME: This check isn't quite right: it allows star in prototypes
4763 // for function definitions, and disallows some edge cases detailed
4764 // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
4765 S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
4766 ASM = ArrayType::Normal;
4767 D.setInvalidType(true);
4768 }
4769
4770 // C99 6.7.5.2p1: The optional type qualifiers and the keyword static
4771 // shall appear only in a declaration of a function parameter with an
4772 // array type, ...
4773 if (ASM == ArrayType::Static || ATI.TypeQuals) {
4774 if (!(D.isPrototypeContext() ||
4775 D.getContext() == DeclaratorContext::KNRTypeListContext)) {
4776 S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype) <<
4777 (ASM == ArrayType::Static ? "'static'" : "type qualifier");
4778 // Remove the 'static' and the type qualifiers.
4779 if (ASM == ArrayType::Static)
4780 ASM = ArrayType::Normal;
4781 ATI.TypeQuals = 0;
4782 D.setInvalidType(true);
4783 }
4784
4785 // C99 6.7.5.2p1: ... and then only in the outermost array type
4786 // derivation.
4787 if (hasOuterPointerLikeChunk(D, chunkIndex)) {
4788 S.Diag(DeclType.Loc, diag::err_array_static_not_outermost) <<
4789 (ASM == ArrayType::Static ? "'static'" : "type qualifier");
4790 if (ASM == ArrayType::Static)
4791 ASM = ArrayType::Normal;
4792 ATI.TypeQuals = 0;
4793 D.setInvalidType(true);
4794 }
4795 }
4796 const AutoType *AT = T->getContainedAutoType();
4797 // Allow arrays of auto if we are a generic lambda parameter.
4798 // i.e. [](auto (&array)[5]) { return array[0]; }; OK
4799 if (AT &&
4800 D.getContext() != DeclaratorContext::LambdaExprParameterContext) {
4801 // We've already diagnosed this for decltype(auto).
4802 if (!AT->isDecltypeAuto())
4803 S.Diag(DeclType.Loc, diag::err_illegal_decl_array_of_auto)
4804 << getPrintableNameForEntity(Name) << T;
4805 T = QualType();
4806 break;
4807 }
4808
4809 // Array parameters can be marked nullable as well, although it's not
4810 // necessary if they're marked 'static'.
4811 if (complainAboutMissingNullability == CAMN_Yes &&
4812 !hasNullabilityAttr(DeclType.getAttrs()) &&
4813 ASM != ArrayType::Static &&
4814 D.isPrototypeContext() &&
4815 !hasOuterPointerLikeChunk(D, chunkIndex)) {
4816 checkNullabilityConsistency(S, SimplePointerKind::Array, DeclType.Loc);
4817 }
4818
4819 T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals,
4820 SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
4821 break;
4822 }
4823 case DeclaratorChunk::Function: {
4824 // If the function declarator has a prototype (i.e. it is not () and
4825 // does not have a K&R-style identifier list), then the arguments are part
4826 // of the type, otherwise the argument list is ().
4827 DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
4828 IsQualifiedFunction =
4829 FTI.hasMethodTypeQualifiers() || FTI.hasRefQualifier();
4830
4831 // Check for auto functions and trailing return type and adjust the
4832 // return type accordingly.
4833 if (!D.isInvalidType()) {
4834 // trailing-return-type is only required if we're declaring a function,
4835 // and not, for instance, a pointer to a function.
4836 if (D.getDeclSpec().hasAutoTypeSpec() &&
4837 !FTI.hasTrailingReturnType() && chunkIndex == 0) {
4838 if (!S.getLangOpts().CPlusPlus14) {
4839 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
4840 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto
4841 ? diag::err_auto_missing_trailing_return
4842 : diag::err_deduced_return_type);
4843 T = Context.IntTy;
4844 D.setInvalidType(true);
4845 } else {
4846 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
4847 diag::warn_cxx11_compat_deduced_return_type);
4848 }
4849 } else if (FTI.hasTrailingReturnType()) {
4850 // T must be exactly 'auto' at this point. See CWG issue 681.
4851 if (isa<ParenType>(T)) {
4852 S.Diag(D.getBeginLoc(), diag::err_trailing_return_in_parens)
4853 << T << D.getSourceRange();
4854 D.setInvalidType(true);
4855 } else if (D.getName().getKind() ==
4856 UnqualifiedIdKind::IK_DeductionGuideName) {
4857 if (T != Context.DependentTy) {
4858 S.Diag(D.getDeclSpec().getBeginLoc(),
4859 diag::err_deduction_guide_with_complex_decl)
4860 << D.getSourceRange();
4861 D.setInvalidType(true);
4862 }
4863 } else if (D.getContext() != DeclaratorContext::LambdaExprContext &&
4864 (T.hasQualifiers() || !isa<AutoType>(T) ||
4865 cast<AutoType>(T)->getKeyword() !=
4866 AutoTypeKeyword::Auto ||
4867 cast<AutoType>(T)->isConstrained())) {
4868 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
4869 diag::err_trailing_return_without_auto)
4870 << T << D.getDeclSpec().getSourceRange();
4871 D.setInvalidType(true);
4872 }
4873 T = S.GetTypeFromParser(FTI.getTrailingReturnType(), &TInfo);
4874 if (T.isNull()) {
4875 // An error occurred parsing the trailing return type.
4876 T = Context.IntTy;
4877 D.setInvalidType(true);
4878 } else if (AutoType *Auto = T->getContainedAutoType()) {
4879 // If the trailing return type contains an `auto`, we may need to
4880 // invent a template parameter for it, for cases like
4881 // `auto f() -> C auto` or `[](auto (*p) -> auto) {}`.
4882 InventedTemplateParameterInfo *InventedParamInfo = nullptr;
4883 if (D.getContext() == DeclaratorContext::PrototypeContext)
4884 InventedParamInfo = &S.InventedParameterInfos.back();
4885 else if (D.getContext() ==
4886 DeclaratorContext::LambdaExprParameterContext)
4887 InventedParamInfo = S.getCurLambda();
4888 if (InventedParamInfo) {
4889 std::tie(T, TInfo) = InventTemplateParameter(
4890 state, T, TInfo, Auto, *InventedParamInfo);
4891 }
4892 }
4893 } else {
4894 // This function type is not the type of the entity being declared,
4895 // so checking the 'auto' is not the responsibility of this chunk.
4896 }
4897 }
4898
4899 // C99 6.7.5.3p1: The return type may not be a function or array type.
4900 // For conversion functions, we'll diagnose this particular error later.
4901 if (!D.isInvalidType() && (T->isArrayType() || T->isFunctionType()) &&
4902 (D.getName().getKind() !=
4903 UnqualifiedIdKind::IK_ConversionFunctionId)) {
4904 unsigned diagID = diag::err_func_returning_array_function;
4905 // Last processing chunk in block context means this function chunk
4906 // represents the block.
4907 if (chunkIndex == 0 &&
4908 D.getContext() == DeclaratorContext::BlockLiteralContext)
4909 diagID = diag::err_block_returning_array_function;
4910 S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T;
4911 T = Context.IntTy;
4912 D.setInvalidType(true);
4913 }
4914
4915 // Do not allow returning half FP value.
4916 // FIXME: This really should be in BuildFunctionType.
4917 if (T->isHalfType()) {
4918 if (S.getLangOpts().OpenCL) {
4919 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16")) {
4920 S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return)
4921 << T << 0 /*pointer hint*/;
4922 D.setInvalidType(true);
4923 }
4924 } else if (!S.getLangOpts().HalfArgsAndReturns) {
4925 S.Diag(D.getIdentifierLoc(),
4926 diag::err_parameters_retval_cannot_have_fp16_type) << 1;
4927 D.setInvalidType(true);
4928 }
4929 }
4930
4931 if (LangOpts.OpenCL) {
4932 // OpenCL v2.0 s6.12.5 - A block cannot be the return value of a
4933 // function.
4934 if (T->isBlockPointerType() || T->isImageType() || T->isSamplerT() ||
4935 T->isPipeType()) {
4936 S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return)
4937 << T << 1 /*hint off*/;
4938 D.setInvalidType(true);
4939 }
4940 // OpenCL doesn't support variadic functions and blocks
4941 // (s6.9.e and s6.12.5 OpenCL v2.0) except for printf.
4942 // We also allow here any toolchain reserved identifiers.
4943 if (FTI.isVariadic &&
4944 !(D.getIdentifier() &&
4945 ((D.getIdentifier()->getName() == "printf" &&
4946 (LangOpts.OpenCLCPlusPlus || LangOpts.OpenCLVersion >= 120)) ||
4947 D.getIdentifier()->getName().startswith("__")))) {
4948 S.Diag(D.getIdentifierLoc(), diag::err_opencl_variadic_function);
4949 D.setInvalidType(true);
4950 }
4951 }
4952
4953 // Methods cannot return interface types. All ObjC objects are
4954 // passed by reference.
4955 if (T->isObjCObjectType()) {
4956 SourceLocation DiagLoc, FixitLoc;
4957 if (TInfo) {
4958 DiagLoc = TInfo->getTypeLoc().getBeginLoc();
4959 FixitLoc = S.getLocForEndOfToken(TInfo->getTypeLoc().getEndLoc());
4960 } else {
4961 DiagLoc = D.getDeclSpec().getTypeSpecTypeLoc();
4962 FixitLoc = S.getLocForEndOfToken(D.getDeclSpec().getEndLoc());
4963 }
4964 S.Diag(DiagLoc, diag::err_object_cannot_be_passed_returned_by_value)
4965 << 0 << T
4966 << FixItHint::CreateInsertion(FixitLoc, "*");
4967
4968 T = Context.getObjCObjectPointerType(T);
4969 if (TInfo) {
4970 TypeLocBuilder TLB;
4971 TLB.pushFullCopy(TInfo->getTypeLoc());
4972 ObjCObjectPointerTypeLoc TLoc = TLB.push<ObjCObjectPointerTypeLoc>(T);
4973 TLoc.setStarLoc(FixitLoc);
4974 TInfo = TLB.getTypeSourceInfo(Context, T);
4975 }
4976
4977 D.setInvalidType(true);
4978 }
4979
4980 // cv-qualifiers on return types are pointless except when the type is a
4981 // class type in C++.
4982 if ((T.getCVRQualifiers() || T->isAtomicType()) &&
4983 !(S.getLangOpts().CPlusPlus &&
4984 (T->isDependentType() || T->isRecordType()))) {
4985 if (T->isVoidType() && !S.getLangOpts().CPlusPlus &&
4986 D.getFunctionDefinitionKind() == FDK_Definition) {
4987 // [6.9.1/3] qualified void return is invalid on a C
4988 // function definition. Apparently ok on declarations and
4989 // in C++ though (!)
4990 S.Diag(DeclType.Loc, diag::err_func_returning_qualified_void) << T;
4991 } else
4992 diagnoseRedundantReturnTypeQualifiers(S, T, D, chunkIndex);
4993
4994 // C++2a [dcl.fct]p12:
4995 // A volatile-qualified return type is deprecated
4996 if (T.isVolatileQualified() && S.getLangOpts().CPlusPlus20)
4997 S.Diag(DeclType.Loc, diag::warn_deprecated_volatile_return) << T;
4998 }
4999
5000 // Objective-C ARC ownership qualifiers are ignored on the function
5001 // return type (by type canonicalization). Complain if this attribute
5002 // was written here.
5003 if (T.getQualifiers().hasObjCLifetime()) {
5004 SourceLocation AttrLoc;
5005 if (chunkIndex + 1 < D.getNumTypeObjects()) {
5006 DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1);
5007 for (const ParsedAttr &AL : ReturnTypeChunk.getAttrs()) {
5008 if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) {
5009 AttrLoc = AL.getLoc();
5010 break;
5011 }
5012 }
5013 }
5014 if (AttrLoc.isInvalid()) {
5015 for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) {
5016 if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) {
5017 AttrLoc = AL.getLoc();
5018 break;
5019 }
5020 }
5021 }
5022
5023 if (AttrLoc.isValid()) {
5024 // The ownership attributes are almost always written via
5025 // the predefined
5026 // __strong/__weak/__autoreleasing/__unsafe_unretained.
5027 if (AttrLoc.isMacroID())
5028 AttrLoc =
5029 S.SourceMgr.getImmediateExpansionRange(AttrLoc).getBegin();
5030
5031 S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type)
5032 << T.getQualifiers().getObjCLifetime();
5033 }
5034 }
5035
5036 if (LangOpts.CPlusPlus && D.getDeclSpec().hasTagDefinition()) {
5037 // C++ [dcl.fct]p6:
5038 // Types shall not be defined in return or parameter types.
5039 TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
5040 S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
5041 << Context.getTypeDeclType(Tag);
5042 }
5043
5044 // Exception specs are not allowed in typedefs. Complain, but add it
5045 // anyway.
5046 if (IsTypedefName && FTI.getExceptionSpecType() && !LangOpts.CPlusPlus17)
5047 S.Diag(FTI.getExceptionSpecLocBeg(),
5048 diag::err_exception_spec_in_typedef)
5049 << (D.getContext() == DeclaratorContext::AliasDeclContext ||
5050 D.getContext() == DeclaratorContext::AliasTemplateContext);
5051
5052 // If we see "T var();" or "T var(T());" at block scope, it is probably
5053 // an attempt to initialize a variable, not a function declaration.
5054 if (FTI.isAmbiguous)
5055 warnAboutAmbiguousFunction(S, D, DeclType, T);
5056
5057 FunctionType::ExtInfo EI(
5058 getCCForDeclaratorChunk(S, D, DeclType.getAttrs(), FTI, chunkIndex));
5059
5060 if (!FTI.NumParams && !FTI.isVariadic && !LangOpts.CPlusPlus
5061 && !LangOpts.OpenCL) {
5062 // Simple void foo(), where the incoming T is the result type.
5063 T = Context.getFunctionNoProtoType(T, EI);
5064 } else {
5065 // We allow a zero-parameter variadic function in C if the
5066 // function is marked with the "overloadable" attribute. Scan
5067 // for this attribute now.
5068 if (!FTI.NumParams && FTI.isVariadic && !LangOpts.CPlusPlus)
5069 if (!D.getAttributes().hasAttribute(ParsedAttr::AT_Overloadable))
5070 S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_param);
5071
5072 if (FTI.NumParams && FTI.Params[0].Param == nullptr) {
5073 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function
5074 // definition.
5075 S.Diag(FTI.Params[0].IdentLoc,
5076 diag::err_ident_list_in_fn_declaration);
5077 D.setInvalidType(true);
5078 // Recover by creating a K&R-style function type.
5079 T = Context.getFunctionNoProtoType(T, EI);
5080 break;
5081 }
5082
5083 FunctionProtoType::ExtProtoInfo EPI;
5084 EPI.ExtInfo = EI;
5085 EPI.Variadic = FTI.isVariadic;
5086 EPI.EllipsisLoc = FTI.getEllipsisLoc();
5087 EPI.HasTrailingReturn = FTI.hasTrailingReturnType();
5088 EPI.TypeQuals.addCVRUQualifiers(
5089 FTI.MethodQualifiers ? FTI.MethodQualifiers->getTypeQualifiers()
5090 : 0);
5091 EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None
5092 : FTI.RefQualifierIsLValueRef? RQ_LValue
5093 : RQ_RValue;
5094
5095 // Otherwise, we have a function with a parameter list that is
5096 // potentially variadic.
5097 SmallVector<QualType, 16> ParamTys;
5098 ParamTys.reserve(FTI.NumParams);
5099
5100 SmallVector<FunctionProtoType::ExtParameterInfo, 16>
5101 ExtParameterInfos(FTI.NumParams);
5102 bool HasAnyInterestingExtParameterInfos = false;
5103
5104 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
5105 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
5106 QualType ParamTy = Param->getType();
5107 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~++20200806111125+5446ec85070/clang/lib/Sema/SemaType.cpp"
, 5107, __PRETTY_FUNCTION__))
;
5108
5109 // Look for 'void'. void is allowed only as a single parameter to a
5110 // function with no other parameters (C99 6.7.5.3p10). We record
5111 // int(void) as a FunctionProtoType with an empty parameter list.
5112 if (ParamTy->isVoidType()) {
5113 // If this is something like 'float(int, void)', reject it. 'void'
5114 // is an incomplete type (C99 6.2.5p19) and function decls cannot
5115 // have parameters of incomplete type.
5116 if (FTI.NumParams != 1 || FTI.isVariadic) {
5117 S.Diag(FTI.Params[i].IdentLoc, diag::err_void_only_param);
5118 ParamTy = Context.IntTy;
5119 Param->setType(ParamTy);
5120 } else if (FTI.Params[i].Ident) {
5121 // Reject, but continue to parse 'int(void abc)'.
5122 S.Diag(FTI.Params[i].IdentLoc, diag::err_param_with_void_type);
5123 ParamTy = Context.IntTy;
5124 Param->setType(ParamTy);
5125 } else {
5126 // Reject, but continue to parse 'float(const void)'.
5127 if (ParamTy.hasQualifiers())
5128 S.Diag(DeclType.Loc, diag::err_void_param_qualified);
5129
5130 // Do not add 'void' to the list.
5131 break;
5132 }
5133 } else if (ParamTy->isHalfType()) {
5134 // Disallow half FP parameters.
5135 // FIXME: This really should be in BuildFunctionType.
5136 if (S.getLangOpts().OpenCL) {
5137 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16")) {
5138 S.Diag(Param->getLocation(), diag::err_opencl_invalid_param)
5139 << ParamTy << 0;
5140 D.setInvalidType();
5141 Param->setInvalidDecl();
5142 }
5143 } else if (!S.getLangOpts().HalfArgsAndReturns) {
5144 S.Diag(Param->getLocation(),
5145 diag::err_parameters_retval_cannot_have_fp16_type) << 0;
5146 D.setInvalidType();
5147 }
5148 } else if (!FTI.hasPrototype) {
5149 if (ParamTy->isPromotableIntegerType()) {
5150 ParamTy = Context.getPromotedIntegerType(ParamTy);
5151 Param->setKNRPromoted(true);
5152 } else if (const BuiltinType* BTy = ParamTy->getAs<BuiltinType>()) {
5153 if (BTy->getKind() == BuiltinType::Float) {
5154 ParamTy = Context.DoubleTy;
5155 Param->setKNRPromoted(true);
5156 }
5157 }
5158 } else if (S.getLangOpts().OpenCL && ParamTy->isBlockPointerType()) {
5159 // OpenCL 2.0 s6.12.5: A block cannot be a parameter of a function.
5160 S.Diag(Param->getLocation(), diag::err_opencl_invalid_param)
5161 << ParamTy << 1 /*hint off*/;
5162 D.setInvalidType();
5163 }
5164
5165 if (LangOpts.ObjCAutoRefCount && Param->hasAttr<NSConsumedAttr>()) {
5166 ExtParameterInfos[i] = ExtParameterInfos[i].withIsConsumed(true);
5167 HasAnyInterestingExtParameterInfos = true;
5168 }
5169
5170 if (auto attr = Param->getAttr<ParameterABIAttr>()) {
5171 ExtParameterInfos[i] =
5172 ExtParameterInfos[i].withABI(attr->getABI());
5173 HasAnyInterestingExtParameterInfos = true;
5174 }
5175
5176 if (Param->hasAttr<PassObjectSizeAttr>()) {
5177 ExtParameterInfos[i] = ExtParameterInfos[i].withHasPassObjectSize();
5178 HasAnyInterestingExtParameterInfos = true;
5179 }
5180
5181 if (Param->hasAttr<NoEscapeAttr>()) {
5182 ExtParameterInfos[i] = ExtParameterInfos[i].withIsNoEscape(true);
5183 HasAnyInterestingExtParameterInfos = true;
5184 }
5185
5186 ParamTys.push_back(ParamTy);
5187 }
5188
5189 if (HasAnyInterestingExtParameterInfos) {
5190 EPI.ExtParameterInfos = ExtParameterInfos.data();
5191 checkExtParameterInfos(S, ParamTys, EPI,
5192 [&](unsigned i) { return FTI.Params[i].Param->getLocation(); });
5193 }
5194
5195 SmallVector<QualType, 4> Exceptions;
5196 SmallVector<ParsedType, 2> DynamicExceptions;
5197 SmallVector<SourceRange, 2> DynamicExceptionRanges;
5198 Expr *NoexceptExpr = nullptr;
5199
5200 if (FTI.getExceptionSpecType() == EST_Dynamic) {
5201 // FIXME: It's rather inefficient to have to split into two vectors
5202 // here.
5203 unsigned N = FTI.getNumExceptions();
5204 DynamicExceptions.reserve(N);
5205 DynamicExceptionRanges.reserve(N);
5206 for (unsigned I = 0; I != N; ++I) {
5207 DynamicExceptions.push_back(FTI.Exceptions[I].Ty);
5208 DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range);
5209 }
5210 } else if (isComputedNoexcept(FTI.getExceptionSpecType())) {
5211 NoexceptExpr = FTI.NoexceptExpr;
5212 }
5213
5214 S.checkExceptionSpecification(D.isFunctionDeclarationContext(),
5215 FTI.getExceptionSpecType(),
5216 DynamicExceptions,
5217 DynamicExceptionRanges,
5218 NoexceptExpr,
5219 Exceptions,
5220 EPI.ExceptionSpec);
5221
5222 // FIXME: Set address space from attrs for C++ mode here.
5223 // OpenCLCPlusPlus: A class member function has an address space.
5224 auto IsClassMember = [&]() {
5225 return (!state.getDeclarator().getCXXScopeSpec().isEmpty() &&
5226 state.getDeclarator()
5227 .getCXXScopeSpec()
5228 .getScopeRep()
5229 ->getKind() == NestedNameSpecifier::TypeSpec) ||
5230 state.getDeclarator().getContext() ==
5231 DeclaratorContext::MemberContext ||
5232 state.getDeclarator().getContext() ==
5233 DeclaratorContext::LambdaExprContext;
5234 };
5235
5236 if (state.getSema().getLangOpts().OpenCLCPlusPlus && IsClassMember()) {
5237 LangAS ASIdx = LangAS::Default;
5238 // Take address space attr if any and mark as invalid to avoid adding
5239 // them later while creating QualType.
5240 if (FTI.MethodQualifiers)
5241 for (ParsedAttr &attr : FTI.MethodQualifiers->getAttributes()) {
5242 LangAS ASIdxNew = attr.asOpenCLLangAS();
5243 if (DiagnoseMultipleAddrSpaceAttributes(S, ASIdx, ASIdxNew,
5244 attr.getLoc()))
5245 D.setInvalidType(true);
5246 else
5247 ASIdx = ASIdxNew;
5248 }
5249 // If a class member function's address space is not set, set it to
5250 // __generic.
5251 LangAS AS =
5252 (ASIdx == LangAS::Default ? S.getDefaultCXXMethodAddrSpace()
5253 : ASIdx);
5254 EPI.TypeQuals.addAddressSpace(AS);
5255 }
5256 T = Context.getFunctionType(T, ParamTys, EPI);
5257 }
5258 break;
5259 }
5260 case DeclaratorChunk::MemberPointer: {
5261 // The scope spec must refer to a class, or be dependent.
5262 CXXScopeSpec &SS = DeclType.Mem.Scope();
5263 QualType ClsType;
5264
5265 // Handle pointer nullability.
5266 inferPointerNullability(SimplePointerKind::MemberPointer, DeclType.Loc,
5267 DeclType.EndLoc, DeclType.getAttrs(),
5268 state.getDeclarator().getAttributePool());
5269
5270 if (SS.isInvalid()) {
5271 // Avoid emitting extra errors if we already errored on the scope.
5272 D.setInvalidType(true);
5273 } else if (S.isDependentScopeSpecifier(SS) ||
5274 dyn_cast_or_null<CXXRecordDecl>(S.computeDeclContext(SS))) {
5275 NestedNameSpecifier *NNS = SS.getScopeRep();
5276 NestedNameSpecifier *NNSPrefix = NNS->getPrefix();
5277 switch (NNS->getKind()) {
5278 case NestedNameSpecifier::Identifier:
5279 ClsType = Context.getDependentNameType(ETK_None, NNSPrefix,
5280 NNS->getAsIdentifier());
5281 break;
5282
5283 case NestedNameSpecifier::Namespace:
5284 case NestedNameSpecifier::NamespaceAlias:
5285 case NestedNameSpecifier::Global:
5286 case NestedNameSpecifier::Super:
5287 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~++20200806111125+5446ec85070/clang/lib/Sema/SemaType.cpp"
, 5287)
;
5288
5289 case NestedNameSpecifier::TypeSpec:
5290 case NestedNameSpecifier::TypeSpecWithTemplate:
5291 ClsType = QualType(NNS->getAsType(), 0);
5292 // Note: if the NNS has a prefix and ClsType is a nondependent
5293 // TemplateSpecializationType, then the NNS prefix is NOT included
5294 // in ClsType; hence we wrap ClsType into an ElaboratedType.
5295 // NOTE: in particular, no wrap occurs if ClsType already is an
5296 // Elaborated, DependentName, or DependentTemplateSpecialization.
5297 if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType()))
5298 ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType);
5299 break;
5300 }
5301 } else {
5302 S.Diag(DeclType.Mem.Scope().getBeginLoc(),
5303 diag::err_illegal_decl_mempointer_in_nonclass)
5304 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
5305 << DeclType.Mem.Scope().getRange();
5306 D.setInvalidType(true);
5307 }
5308
5309 if (!ClsType.isNull())
5310 T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc,
5311 D.getIdentifier());
5312 if (T.isNull()) {
5313 T = Context.IntTy;
5314 D.setInvalidType(true);
5315 } else if (DeclType.Mem.TypeQuals) {
5316 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals);
5317 }
5318 break;
5319 }
5320
5321 case DeclaratorChunk::Pipe: {
5322 T = S.BuildReadPipeType(T, DeclType.Loc);
5323 processTypeAttrs(state, T, TAL_DeclSpec,
5324 D.getMutableDeclSpec().getAttributes());
5325 break;
5326 }
5327 }
5328
5329 if (T.isNull()) {
5330 D.setInvalidType(true);
5331 T = Context.IntTy;
5332 }
5333
5334 // See if there are any attributes on this declarator chunk.
5335 processTypeAttrs(state, T, TAL_DeclChunk, DeclType.getAttrs());
5336
5337 if (DeclType.Kind != DeclaratorChunk::Paren) {
5338 if (ExpectNoDerefChunk && !IsNoDerefableChunk(DeclType))
5339 S.Diag(DeclType.Loc, diag::warn_noderef_on_non_pointer_or_array);
5340
5341 ExpectNoDerefChunk = state.didParseNoDeref();
5342 }
5343 }
5344
5345 if (ExpectNoDerefChunk)
5346 S.Diag(state.getDeclarator().getBeginLoc(),
5347 diag::warn_noderef_on_non_pointer_or_array);
5348
5349 // GNU warning -Wstrict-prototypes
5350 // Warn if a function declaration is without a prototype.
5351 // This warning is issued for all kinds of unprototyped function
5352 // declarations (i.e. function type typedef, function pointer etc.)
5353 // C99 6.7.5.3p14:
5354 // The empty list in a function declarator that is not part of a definition
5355 // of that function specifies that no information about the number or types
5356 // of the parameters is supplied.
5357 if (!LangOpts.CPlusPlus && D.getFunctionDefinitionKind() == FDK_Declaration) {
5358 bool IsBlock = false;
5359 for (const DeclaratorChunk &DeclType : D.type_objects()) {
5360 switch (DeclType.Kind) {
5361 case DeclaratorChunk::BlockPointer:
5362 IsBlock = true;
5363 break;
5364 case DeclaratorChunk::Function: {
5365 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
5366 // We supress the warning when there's no LParen location, as this
5367 // indicates the declaration was an implicit declaration, which gets
5368 // warned about separately via -Wimplicit-function-declaration.
5369 if (FTI.NumParams == 0 && !FTI.isVariadic && FTI.getLParenLoc().isValid())
5370 S.Diag(DeclType.Loc, diag::warn_strict_prototypes)
5371 << IsBlock
5372 << FixItHint::CreateInsertion(FTI.getRParenLoc(), "void");
5373 IsBlock = false;
5374 break;
5375 }
5376 default:
5377 break;
5378 }
5379 }
5380 }
5381
5382 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~++20200806111125+5446ec85070/clang/lib/Sema/SemaType.cpp"
, 5382, __PRETTY_FUNCTION__))
;
5383
5384 if (LangOpts.CPlusPlus && T->isFunctionType()) {
5385 const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
5386 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~++20200806111125+5446ec85070/clang/lib/Sema/SemaType.cpp"
, 5386, __PRETTY_FUNCTION__))
;
5387
5388 // C++ 8.3.5p4:
5389 // A cv-qualifier-seq shall only be part of the function type
5390 // for a nonstatic member function, the function type to which a pointer
5391 // to member refers, or the top-level function type of a function typedef
5392 // declaration.
5393 //
5394 // Core issue 547 also allows cv-qualifiers on function types that are
5395 // top-level template type arguments.
5396 enum { NonMember, Member, DeductionGuide } Kind = NonMember;
5397 if (D.getName().getKind() == UnqualifiedIdKind::IK_DeductionGuideName)
5398 Kind = DeductionGuide;
5399 else if (!D.getCXXScopeSpec().isSet()) {
5400 if ((D.getContext() == DeclaratorContext::MemberContext ||
5401 D.getContext() == DeclaratorContext::LambdaExprContext) &&
5402 !D.getDeclSpec().isFriendSpecified())
5403 Kind = Member;
5404 } else {
5405 DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec());
5406 if (!DC || DC->isRecord())
5407 Kind = Member;
5408 }
5409
5410 // C++11 [dcl.fct]p6 (w/DR1417):
5411 // An attempt to specify a function type with a cv-qualifier-seq or a
5412 // ref-qualifier (including by typedef-name) is ill-formed unless it is:
5413 // - the function type for a non-static member function,
5414 // - the function type to which a pointer to member refers,
5415 // - the top-level function type of a function typedef declaration or
5416 // alias-declaration,
5417 // - the type-id in the default argument of a type-parameter, or
5418 // - the type-id of a template-argument for a type-parameter
5419 //
5420 // FIXME: Checking this here is insufficient. We accept-invalid on:
5421 //
5422 // template<typename T> struct S { void f(T); };
5423 // S<int() const> s;
5424 //
5425 // ... for instance.
5426 if (IsQualifiedFunction &&
5427 !(Kind == Member &&
5428 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) &&
5429 !IsTypedefName &&
5430 D.getContext() != DeclaratorContext::TemplateArgContext &&
5431 D.getContext() != DeclaratorContext::TemplateTypeArgContext) {
5432 SourceLocation Loc = D.getBeginLoc();
5433 SourceRange RemovalRange;
5434 unsigned I;
5435 if (D.isFunctionDeclarator(I)) {
5436 SmallVector<SourceLocation, 4> RemovalLocs;
5437 const DeclaratorChunk &Chunk = D.getTypeObject(I);
5438 assert(Chunk.Kind == DeclaratorChunk::Function)((Chunk.Kind == DeclaratorChunk::Function) ? static_cast<void
> (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::Function"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaType.cpp"
, 5438, __PRETTY_FUNCTION__))
;
5439
5440 if (Chunk.Fun.hasRefQualifier())
5441 RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc());
5442
5443 if (Chunk.Fun.hasMethodTypeQualifiers())
5444 Chunk.Fun.MethodQualifiers->forEachQualifier(
5445 [&](DeclSpec::TQ TypeQual, StringRef QualName,
5446 SourceLocation SL) { RemovalLocs.push_back(SL); });
5447
5448 if (!RemovalLocs.empty()) {
5449 llvm::sort(RemovalLocs,
5450 BeforeThanCompare<SourceLocation>(S.getSourceManager()));
5451 RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back());
5452 Loc = RemovalLocs.front();
5453 }
5454 }
5455
5456 S.Diag(Loc, diag::err_invalid_qualified_function_type)
5457 << Kind << D.isFunctionDeclarator() << T
5458 << getFunctionQualifiersAsString(FnTy)
5459 << FixItHint::CreateRemoval(RemovalRange);
5460
5461 // Strip the cv-qualifiers and ref-qualifiers from the type.
5462 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
5463 EPI.TypeQuals.removeCVRQualifiers();
5464 EPI.RefQualifier = RQ_None;
5465
5466 T = Context.getFunctionType(FnTy->getReturnType(), FnTy->getParamTypes(),
5467 EPI);
5468 // Rebuild any parens around the identifier in the function type.
5469 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
5470 if (D.getTypeObject(i).Kind != DeclaratorChunk::Paren)
5471 break;
5472 T = S.BuildParenType(T);
5473 }
5474 }
5475 }
5476
5477 // Apply any undistributed attributes from the declarator.
5478 processTypeAttrs(state, T, TAL_DeclName, D.getAttributes());
5479
5480 // Diagnose any ignored type attributes.
5481 state.diagnoseIgnoredTypeAttrs(T);
5482
5483 // C++0x [dcl.constexpr]p9:
5484 // A constexpr specifier used in an object declaration declares the object
5485 // as const.
5486 if (D.getDeclSpec().getConstexprSpecifier() == CSK_constexpr &&
5487 T->isObjectType())
5488 T.addConst();
5489
5490 // C++2a [dcl.fct]p4:
5491 // A parameter with volatile-qualified type is deprecated
5492 if (T.isVolatileQualified() && S.getLangOpts().CPlusPlus20 &&
5493 (D.getContext() == DeclaratorContext::PrototypeContext ||
5494 D.getContext() == DeclaratorContext::LambdaExprParameterContext))
5495 S.Diag(D.getIdentifierLoc(), diag::warn_deprecated_volatile_param) << T;
5496
5497 // If there was an ellipsis in the declarator, the declaration declares a
5498 // parameter pack whose type may be a pack expansion type.
5499 if (D.hasEllipsis()) {
5500 // C++0x [dcl.fct]p13:
5501 // A declarator-id or abstract-declarator containing an ellipsis shall
5502 // only be used in a parameter-declaration. Such a parameter-declaration
5503 // is a parameter pack (14.5.3). [...]
5504 switch (D.getContext()) {
5505 case DeclaratorContext::PrototypeContext:
5506 case DeclaratorContext::LambdaExprParameterContext:
5507 case DeclaratorContext::RequiresExprContext:
5508 // C++0x [dcl.fct]p13:
5509 // [...] When it is part of a parameter-declaration-clause, the
5510 // parameter pack is a function parameter pack (14.5.3). The type T
5511 // of the declarator-id of the function parameter pack shall contain
5512 // a template parameter pack; each template parameter pack in T is
5513 // expanded by the function parameter pack.
5514 //
5515 // We represent function parameter packs as function parameters whose
5516 // type is a pack expansion.
5517 if (!T->containsUnexpandedParameterPack() &&
5518 (!LangOpts.CPlusPlus20 || !T->getContainedAutoType())) {
5519 S.Diag(D.getEllipsisLoc(),
5520 diag::err_function_parameter_pack_without_parameter_packs)
5521 << T << D.getSourceRange();
5522 D.setEllipsisLoc(SourceLocation());
5523 } else {
5524 T = Context.getPackExpansionType(T, None, /*ExpectPackInType=*/false);
5525 }
5526 break;
5527 case DeclaratorContext::TemplateParamContext:
5528 // C++0x [temp.param]p15:
5529 // If a template-parameter is a [...] is a parameter-declaration that
5530 // declares a parameter pack (8.3.5), then the template-parameter is a
5531 // template parameter pack (14.5.3).
5532 //
5533 // Note: core issue 778 clarifies that, if there are any unexpanded
5534 // parameter packs in the type of the non-type template parameter, then
5535 // it expands those parameter packs.
5536 if (T->containsUnexpandedParameterPack())
5537 T = Context.getPackExpansionType(T, None);
5538 else
5539 S.Diag(D.getEllipsisLoc(),
5540 LangOpts.CPlusPlus11
5541 ? diag::warn_cxx98_compat_variadic_templates
5542 : diag::ext_variadic_templates);
5543 break;
5544
5545 case DeclaratorContext::FileContext:
5546 case DeclaratorContext::KNRTypeListContext:
5547 case DeclaratorContext::ObjCParameterContext: // FIXME: special diagnostic
5548 // here?
5549 case DeclaratorContext::ObjCResultContext: // FIXME: special diagnostic
5550 // here?
5551 case DeclaratorContext::TypeNameContext:
5552 case DeclaratorContext::FunctionalCastContext:
5553 case DeclaratorContext::CXXNewContext:
5554 case DeclaratorContext::AliasDeclContext:
5555 case DeclaratorContext::AliasTemplateContext:
5556 case DeclaratorContext::MemberContext:
5557 case DeclaratorContext::BlockContext:
5558 case DeclaratorContext::ForContext:
5559 case DeclaratorContext::InitStmtContext:
5560 case DeclaratorContext::ConditionContext:
5561 case DeclaratorContext::CXXCatchContext:
5562 case DeclaratorContext::ObjCCatchContext:
5563 case DeclaratorContext::BlockLiteralContext:
5564 case DeclaratorContext::LambdaExprContext:
5565 case DeclaratorContext::ConversionIdContext:
5566 case DeclaratorContext::TrailingReturnContext:
5567 case DeclaratorContext::TrailingReturnVarContext:
5568 case DeclaratorContext::TemplateArgContext:
5569 case DeclaratorContext::TemplateTypeArgContext:
5570 // FIXME: We may want to allow parameter packs in block-literal contexts
5571 // in the future.
5572 S.Diag(D.getEllipsisLoc(),
5573 diag::err_ellipsis_in_declarator_not_parameter);
5574 D.setEllipsisLoc(SourceLocation());
5575 break;
5576 }
5577 }
5578
5579 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~++20200806111125+5446ec85070/clang/lib/Sema/SemaType.cpp"
, 5579, __PRETTY_FUNCTION__))
;
5580 if (D.isInvalidType())
5581 return Context.getTrivialTypeSourceInfo(T);
5582
5583 return GetTypeSourceInfoForDeclarator(state, T, TInfo);
5584}
5585
5586/// GetTypeForDeclarator - Convert the type for the specified
5587/// declarator to Type instances.
5588///
5589/// The result of this call will never be null, but the associated
5590/// type may be a null type if there's an unrecoverable error.
5591TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) {
5592 // Determine the type of the declarator. Not all forms of declarator
5593 // have a type.
5594
5595 TypeProcessingState state(*this, D);
5596
5597 TypeSourceInfo *ReturnTypeInfo = nullptr;
5598 QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
5599 if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount)
5600 inferARCWriteback(state, T);
5601
5602 return GetFullTypeForDeclarator(state, T, ReturnTypeInfo);
5603}
5604
5605static void transferARCOwnershipToDeclSpec(Sema &S,
5606 QualType &declSpecTy,
5607 Qualifiers::ObjCLifetime ownership) {
5608 if (declSpecTy->isObjCRetainableType() &&
5609 declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) {
5610 Qualifiers qs;
5611 qs.addObjCLifetime(ownership);
5612 declSpecTy = S.Context.getQualifiedType(declSpecTy, qs);
5613 }
5614}
5615
5616static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
5617 Qualifiers::ObjCLifetime ownership,
5618 unsigned chunkIndex) {
5619 Sema &S = state.getSema();
5620 Declarator &D = state.getDeclarator();
5621
5622 // Look for an explicit lifetime attribute.
5623 DeclaratorChunk &chunk = D.getTypeObject(chunkIndex);
5624 if (chunk.getAttrs().hasAttribute(ParsedAttr::AT_ObjCOwnership))
5625 return;
5626
5627 const char *attrStr = nullptr;
5628 switch (ownership) {
5629 case Qualifiers::OCL_None: llvm_unreachable("no ownership!")::llvm::llvm_unreachable_internal("no ownership!", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaType.cpp"
, 5629)
;
5630 case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break;
5631 case Qualifiers::OCL_Strong: attrStr = "strong"; break;
5632 case Qualifiers::OCL_Weak: attrStr = "weak"; break;
5633 case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break;
5634 }
5635
5636 IdentifierLoc *Arg = new (S.Context) IdentifierLoc;
5637 Arg->Ident = &S.Context.Idents.get(attrStr);
5638 Arg->Loc = SourceLocation();
5639
5640 ArgsUnion Args(Arg);
5641
5642 // If there wasn't one, add one (with an invalid source location
5643 // so that we don't make an AttributedType for it).
5644 ParsedAttr *attr = D.getAttributePool().create(
5645 &S.Context.Idents.get("objc_ownership"), SourceLocation(),
5646 /*scope*/ nullptr, SourceLocation(),
5647 /*args*/ &Args, 1, ParsedAttr::AS_GNU);
5648 chunk.getAttrs().addAtEnd(attr);
5649 // TODO: mark whether we did this inference?
5650}
5651
5652/// Used for transferring ownership in casts resulting in l-values.
5653static void transferARCOwnership(TypeProcessingState &state,
5654 QualType &declSpecTy,
5655 Qualifiers::ObjCLifetime ownership) {
5656 Sema &S = state.getSema();
5657 Declarator &D = state.getDeclarator();
5658
5659 int inner = -1;
5660 bool hasIndirection = false;
5661 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
5662 DeclaratorChunk &chunk = D.getTypeObject(i);
5663 switch (chunk.Kind) {
5664 case DeclaratorChunk::Paren:
5665 // Ignore parens.
5666 break;
5667
5668 case DeclaratorChunk::Array:
5669 case DeclaratorChunk::Reference:
5670 case DeclaratorChunk::Pointer:
5671 if (inner != -1)
5672 hasIndirection = true;
5673 inner = i;
5674 break;
5675
5676 case DeclaratorChunk::BlockPointer:
5677 if (inner != -1)
5678 transferARCOwnershipToDeclaratorChunk(state, ownership, i);
5679 return;
5680
5681 case DeclaratorChunk::Function:
5682 case DeclaratorChunk::MemberPointer:
5683 case DeclaratorChunk::Pipe:
5684 return;
5685 }
5686 }
5687
5688 if (inner == -1)
5689 return;
5690
5691 DeclaratorChunk &chunk = D.getTypeObject(inner);
5692 if (chunk.Kind == DeclaratorChunk::Pointer) {
5693 if (declSpecTy->isObjCRetainableType())
5694 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
5695 if (declSpecTy->isObjCObjectType() && hasIndirection)
5696 return transferARCOwnershipToDeclaratorChunk(state, ownership, inner);
5697 } else {
5698 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~++20200806111125+5446ec85070/clang/lib/Sema/SemaType.cpp"
, 5699, __PRETTY_FUNCTION__))
5699 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~++20200806111125+5446ec85070/clang/lib/Sema/SemaType.cpp"
, 5699, __PRETTY_FUNCTION__))
;
5700 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
5701 }
5702}
5703
5704TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) {
5705 TypeProcessingState state(*this, D);
5706
5707 TypeSourceInfo *ReturnTypeInfo = nullptr;
5708 QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
5709
5710 if (getLangOpts().ObjC) {
5711 Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy);
5712 if (ownership != Qualifiers::OCL_None)
5713 transferARCOwnership(state, declSpecTy, ownership);
5714 }
5715
5716 return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo);
5717}
5718
5719static void fillAttributedTypeLoc(AttributedTypeLoc TL,
5720 TypeProcessingState &State) {
5721 TL.setAttr(State.takeAttrForAttributedType(TL.getTypePtr()));
5722}
5723
5724namespace {
5725 class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
5726 Sema &SemaRef;
5727 ASTContext &Context;
5728 TypeProcessingState &State;
5729 const DeclSpec &DS;
5730
5731 public:
5732 TypeSpecLocFiller(Sema &S, ASTContext &Context, TypeProcessingState &State,
5733 const DeclSpec &DS)
5734 : SemaRef(S), Context(Context), State(State), DS(DS) {}
5735
5736 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5737 Visit(TL.getModifiedLoc());
5738 fillAttributedTypeLoc(TL, State);
5739 }
5740 void VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
5741 Visit(TL.getInnerLoc());
5742 TL.setExpansionLoc(
5743 State.getExpansionLocForMacroQualifiedType(TL.getTypePtr()));
5744 }
5745 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5746 Visit(TL.getUnqualifiedLoc());
5747 }
5748 void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5749 TL.setNameLoc(DS.getTypeSpecTypeLoc());
5750 }
5751 void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5752 TL.setNameLoc(DS.getTypeSpecTypeLoc());
5753 // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires
5754 // addition field. What we have is good enough for dispay of location
5755 // of 'fixit' on interface name.
5756 TL.setNameEndLoc(DS.getEndLoc());
5757 }
5758 void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5759 TypeSourceInfo *RepTInfo = nullptr;
5760 Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
5761 TL.copy(RepTInfo->getTypeLoc());
5762 }
5763 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5764 TypeSourceInfo *RepTInfo = nullptr;
5765 Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
5766 TL.copy(RepTInfo->getTypeLoc());
5767 }
5768 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
5769 TypeSourceInfo *TInfo = nullptr;
5770 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5771
5772 // If we got no declarator info from previous Sema routines,
5773 // just fill with the typespec loc.
5774 if (!TInfo) {
5775 TL.initialize(Context, DS.getTypeSpecTypeNameLoc());
5776 return;
5777 }
5778
5779 TypeLoc OldTL = TInfo->getTypeLoc();
5780 if (TInfo->getType()->getAs<ElaboratedType>()) {
5781 ElaboratedTypeLoc ElabTL = OldTL.castAs<ElaboratedTypeLoc>();
5782 TemplateSpecializationTypeLoc NamedTL = ElabTL.getNamedTypeLoc()
5783 .castAs<TemplateSpecializationTypeLoc>();
5784 TL.copy(NamedTL);
5785 } else {
5786 TL.copy(OldTL.castAs<TemplateSpecializationTypeLoc>());
5787 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~++20200806111125+5446ec85070/clang/lib/Sema/SemaType.cpp"
, 5787, __PRETTY_FUNCTION__))
;
5788 }
5789
5790 }
5791 void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5792 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~++20200806111125+5446ec85070/clang/lib/Sema/SemaType.cpp"
, 5792, __PRETTY_FUNCTION__))
;
5793 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
5794 TL.setParensRange(DS.getTypeofParensRange());
5795 }
5796 void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5797 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~++20200806111125+5446ec85070/clang/lib/Sema/SemaType.cpp"
, 5797, __PRETTY_FUNCTION__))
;
5798 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
5799 TL.setParensRange(DS.getTypeofParensRange());
5800 assert(DS.getRepAsType())((DS.getRepAsType()) ? static_cast<void> (0) : __assert_fail
("DS.getRepAsType()", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaType.cpp"
, 5800, __PRETTY_FUNCTION__))
;
5801 TypeSourceInfo *TInfo = nullptr;
5802 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5803 TL.setUnderlyingTInfo(TInfo);
5804 }
5805 void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5806 // FIXME: This holds only because we only have one unary transform.
5807 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~++20200806111125+5446ec85070/clang/lib/Sema/SemaType.cpp"
, 5807, __PRETTY_FUNCTION__))
;
5808 TL.setKWLoc(DS.getTypeSpecTypeLoc());
5809 TL.setParensRange(DS.getTypeofParensRange());
5810 assert(DS.getRepAsType())((DS.getRepAsType()) ? static_cast<void> (0) : __assert_fail
("DS.getRepAsType()", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaType.cpp"
, 5810, __PRETTY_FUNCTION__))
;
5811 TypeSourceInfo *TInfo = nullptr;
5812 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5813 TL.setUnderlyingTInfo(TInfo);
5814 }
5815 void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5816 // By default, use the source location of the type specifier.
5817 TL.setBuiltinLoc(DS.getTypeSpecTypeLoc());
5818 if (TL.needsExtraLocalData()) {
5819 // Set info for the written builtin specifiers.
5820 TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs();
5821 // Try to have a meaningful source location.
5822 if (TL.getWrittenSignSpec() != TSS_unspecified)
5823 TL.expandBuiltinRange(DS.getTypeSpecSignLoc());
5824 if (TL.getWrittenWidthSpec() != TSW_unspecified)
5825 TL.expandBuiltinRange(DS.getTypeSpecWidthRange());
5826 }
5827 }
5828 void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5829 ElaboratedTypeKeyword Keyword
5830 = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
5831 if (DS.getTypeSpecType() == TST_typename) {
5832 TypeSourceInfo *TInfo = nullptr;
5833 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5834 if (TInfo) {
5835 TL.copy(TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>());
5836 return;
5837 }
5838 }
5839 TL.setElaboratedKeywordLoc(Keyword != ETK_None
5840 ? DS.getTypeSpecTypeLoc()
5841 : SourceLocation());
5842 const CXXScopeSpec& SS = DS.getTypeSpecScope();
5843 TL.setQualifierLoc(SS.getWithLocInContext(Context));
5844 Visit(TL.getNextTypeLoc().getUnqualifiedLoc());
5845 }
5846 void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5847 assert(DS.getTypeSpecType() == TST_typename)((DS.getTypeSpecType() == TST_typename) ? static_cast<void
> (0) : __assert_fail ("DS.getTypeSpecType() == TST_typename"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaType.cpp"
, 5847, __PRETTY_FUNCTION__))
;
5848 TypeSourceInfo *TInfo = nullptr;
5849 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5850 assert(TInfo)((TInfo) ? static_cast<void> (0) : __assert_fail ("TInfo"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaType.cpp"
, 5850, __PRETTY_FUNCTION__))
;
5851 TL.copy(TInfo->getTypeLoc().castAs<DependentNameTypeLoc>());
5852 }
5853 void VisitDependentTemplateSpecializationTypeLoc(
5854 DependentTemplateSpecializationTypeLoc TL) {
5855 assert(DS.getTypeSpecType() == TST_typename)((DS.getTypeSpecType() == TST_typename) ? static_cast<void
> (0) : __assert_fail ("DS.getTypeSpecType() == TST_typename"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaType.cpp"
, 5855, __PRETTY_FUNCTION__))
;
5856 TypeSourceInfo *TInfo = nullptr;
5857 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5858 assert(TInfo)((TInfo) ? static_cast<void> (0) : __assert_fail ("TInfo"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaType.cpp"
, 5858, __PRETTY_FUNCTION__))
;
5859 TL.copy(
5860 TInfo->getTypeLoc().castAs<DependentTemplateSpecializationTypeLoc>());
5861 }
5862 void VisitAutoTypeLoc(AutoTypeLoc TL) {
5863 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~++20200806111125+5446ec85070/clang/lib/Sema/SemaType.cpp"
, 5866, __PRETTY_FUNCTION__))
5864 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~++20200806111125+5446ec85070/clang/lib/Sema/SemaType.cpp"
, 5866, __PRETTY_FUNCTION__))
5865 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~++20200806111125+5446ec85070/clang/lib/Sema/SemaType.cpp"
, 5866, __PRETTY_FUNCTION__))
5866 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~++20200806111125+5446ec85070/clang/lib/Sema/SemaType.cpp"
, 5866, __PRETTY_FUNCTION__))
;
5867 TL.setNameLoc(DS.getTypeSpecTypeLoc());
5868 if (!DS.isConstrainedAuto())
5869 return;
5870 TemplateIdAnnotation *TemplateId = DS.getRepAsTemplateId();
5871 if (DS.getTypeSpecScope().isNotEmpty())
5872 TL.setNestedNameSpecifierLoc(
5873 DS.getTypeSpecScope().getWithLocInContext(Context));
5874 else
5875 TL.setNestedNameSpecifierLoc(NestedNameSpecifierLoc());
5876 TL.setTemplateKWLoc(TemplateId->TemplateKWLoc);
5877 TL.setConceptNameLoc(TemplateId->TemplateNameLoc);
5878 TL.setFoundDecl(nullptr);
5879 TL.setLAngleLoc(TemplateId->LAngleLoc);
5880 TL.setRAngleLoc(TemplateId->RAngleLoc);
5881 if (TemplateId->NumArgs == 0)
5882 return;
5883 TemplateArgumentListInfo TemplateArgsInfo;
5884 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
5885 TemplateId->NumArgs);
5886 SemaRef.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo);
5887 for (unsigned I = 0; I < TemplateId->NumArgs; ++I)
5888 TL.setArgLocInfo(I, TemplateArgsInfo.arguments()[I].getLocInfo());
5889 }
5890 void VisitTagTypeLoc(TagTypeLoc TL) {
5891 TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
5892 }
5893 void VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5894 // An AtomicTypeLoc can come from either an _Atomic(...) type specifier
5895 // or an _Atomic qualifier.
5896 if (DS.getTypeSpecType() == DeclSpec::TST_atomic) {
5897 TL.setKWLoc(DS.getTypeSpecTypeLoc());
5898 TL.setParensRange(DS.getTypeofParensRange());
5899
5900 TypeSourceInfo *TInfo = nullptr;
5901 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5902 assert(TInfo)((TInfo) ? static_cast<void> (0) : __assert_fail ("TInfo"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaType.cpp"
, 5902, __PRETTY_FUNCTION__))
;
5903 TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
5904 } else {
5905 TL.setKWLoc(DS.getAtomicSpecLoc());
5906 // No parens, to indicate this was spelled as an _Atomic qualifier.
5907 TL.setParensRange(SourceRange());
5908 Visit(TL.getValueLoc());
5909 }
5910 }
5911
5912 void VisitPipeTypeLoc(PipeTypeLoc TL) {
5913 TL.setKWLoc(DS.getTypeSpecTypeLoc());
5914
5915 TypeSourceInfo *TInfo = nullptr;
5916 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5917 TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
5918 }
5919
5920 void VisitExtIntTypeLoc(ExtIntTypeLoc TL) {
5921 TL.setNameLoc(DS.getTypeSpecTypeLoc());
5922