Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -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 -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -relaxed-aliasing -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-9/lib/clang/9.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-9~svn361465/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-9~svn361465/tools/clang/include -I /build/llvm-toolchain-snapshot-9~svn361465/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-9~svn361465/build-llvm/include -I /build/llvm-toolchain-snapshot-9~svn361465/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/include/clang/9.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-9/lib/clang/9.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++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-9~svn361465/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-9~svn361465=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2019-05-24-031927-21217-1 -x c++ /build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/Sema/SemaType.cpp -faddrsig

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