Bug Summary

File:tools/clang/lib/Sema/SemaType.cpp
Warning:line 7755, column 9
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 -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-8/lib/clang/8.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-8~svn345461/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-8~svn345461/tools/clang/include -I /build/llvm-toolchain-snapshot-8~svn345461/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-8~svn345461/build-llvm/include -I /build/llvm-toolchain-snapshot-8~svn345461/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/8.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-8/lib/clang/8.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-8~svn345461/build-llvm/tools/clang/lib/Sema -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -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-2018-10-27-211344-32123-1 -x c++ /build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/Sema/SemaType.cpp -faddrsig

/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/Sema/SemaType.cpp

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