Bug Summary

File:tools/clang/lib/Sema/SemaType.cpp
Warning:line 2199, column 8
Potential leak of memory pointed to by field 'DiagStorage'

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~svn326551/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn326551/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn326551/build-llvm/include -I /build/llvm-toolchain-snapshot-7~svn326551/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0/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/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-7~svn326551/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-checker optin.performance.Padding -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-03-02-155150-1477-1 -x c++ /build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaType.cpp

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