Bug Summary

File:tools/clang/lib/Sema/SemaType.cpp
Warning:line 5435, column 43
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-eagerly-assume -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-7/lib/clang/7.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-7~svn338205/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn338205/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn338205/build-llvm/include -I /build/llvm-toolchain-snapshot-7~svn338205/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/c++/8 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/x86_64-linux-gnu/c++/8 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/x86_64-linux-gnu/c++/8 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/c++/8/backward -internal-isystem /usr/include/clang/7.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-7/lib/clang/7.0.0/include -internal-externc-isystem /usr/lib/gcc/x86_64-linux-gnu/8/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-class-memaccess -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-7~svn338205/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-07-29-043837-17923-1 -x c++ /build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaType.cpp -faddrsig

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