blob: 017517797fbdfab37f3666dd7b9045e683738283 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaType.cpp - Semantic Analysis for Types -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements type-related semantic analysis.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000015#include "clang/AST/ASTContext.h"
Douglas Gregor36f255c2011-06-03 14:28:43 +000016#include "clang/AST/ASTMutationListener.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000017#include "clang/AST/CXXInheritance.h"
Steve Naroff980e5082007-10-01 19:00:59 +000018#include "clang/AST/DeclObjC.h"
Douglas Gregor2943aed2009-03-03 04:44:36 +000019#include "clang/AST/DeclTemplate.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000020#include "clang/AST/Expr.h"
Argyrios Kyrtzidis4adab7f2009-08-19 01:28:06 +000021#include "clang/AST/TypeLoc.h"
John McCall51bd8032009-10-18 01:05:36 +000022#include "clang/AST/TypeLocVisitor.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000023#include "clang/Basic/OpenCL.h"
Anders Carlsson91a0cc92009-08-26 22:33:56 +000024#include "clang/Basic/PartialDiagnostic.h"
Charles Davisd18f9f92010-08-16 04:01:50 +000025#include "clang/Basic/TargetInfo.h"
John McCall2792fa52011-03-08 04:17:03 +000026#include "clang/Lex/Preprocessor.h"
Eli Friedmanbc1029b2012-04-05 22:47:34 +000027#include "clang/Parse/ParseDiagnostic.h"
John McCall19510852010-08-20 18:27:03 +000028#include "clang/Sema/DeclSpec.h"
John McCallf85e1932011-06-15 23:02:42 +000029#include "clang/Sema/DelayedDiagnostic.h"
Douglas Gregord07cc362012-01-02 17:18:37 +000030#include "clang/Sema/Lookup.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000031#include "clang/Sema/ScopeInfo.h"
32#include "clang/Sema/Template.h"
Sebastian Redl4994d2d2009-07-04 11:39:00 +000033#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor87c12c42009-11-04 16:49:01 +000034#include "llvm/Support/ErrorHandling.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000035using namespace clang;
36
Chris Lattner5db2bb12009-10-25 18:21:37 +000037/// isOmittedBlockReturnType - Return true if this declarator is missing a
Chad Rosier91cbbbf2012-06-26 21:41:40 +000038/// return type because this is a omitted return type on a block literal.
Sebastian Redl8ce35b02009-10-25 21:45:37 +000039static bool isOmittedBlockReturnType(const Declarator &D) {
Chris Lattner5db2bb12009-10-25 18:21:37 +000040 if (D.getContext() != Declarator::BlockLiteralContext ||
Sebastian Redl8ce35b02009-10-25 21:45:37 +000041 D.getDeclSpec().hasTypeSpecifier())
Chris Lattner5db2bb12009-10-25 18:21:37 +000042 return false;
Chad Rosier91cbbbf2012-06-26 21:41:40 +000043
Chris Lattner5db2bb12009-10-25 18:21:37 +000044 if (D.getNumTypeObjects() == 0)
Chris Lattnera64ef0a2009-10-25 22:09:09 +000045 return true; // ^{ ... }
Chad Rosier91cbbbf2012-06-26 21:41:40 +000046
Chris Lattner5db2bb12009-10-25 18:21:37 +000047 if (D.getNumTypeObjects() == 1 &&
48 D.getTypeObject(0).Kind == DeclaratorChunk::Function)
Chris Lattnera64ef0a2009-10-25 22:09:09 +000049 return true; // ^(int X, float Y) { ... }
Chad Rosier91cbbbf2012-06-26 21:41:40 +000050
Chris Lattner5db2bb12009-10-25 18:21:37 +000051 return false;
52}
53
John McCall2792fa52011-03-08 04:17:03 +000054/// diagnoseBadTypeAttribute - Diagnoses a type attribute which
55/// doesn't apply to the given type.
56static void diagnoseBadTypeAttribute(Sema &S, const AttributeList &attr,
57 QualType type) {
Chandler Carruth108f7562011-07-26 05:40:03 +000058 bool useExpansionLoc = false;
John McCall2792fa52011-03-08 04:17:03 +000059
60 unsigned diagID = 0;
61 switch (attr.getKind()) {
Sean Hunt8e083e72012-06-19 23:57:03 +000062 case AttributeList::AT_ObjCGC:
John McCall2792fa52011-03-08 04:17:03 +000063 diagID = diag::warn_pointer_attribute_wrong_type;
Chandler Carruth108f7562011-07-26 05:40:03 +000064 useExpansionLoc = true;
John McCall2792fa52011-03-08 04:17:03 +000065 break;
66
Sean Hunt8e083e72012-06-19 23:57:03 +000067 case AttributeList::AT_ObjCOwnership:
Argyrios Kyrtzidis05d48762011-07-01 22:23:09 +000068 diagID = diag::warn_objc_object_attribute_wrong_type;
Chandler Carruth108f7562011-07-26 05:40:03 +000069 useExpansionLoc = true;
Argyrios Kyrtzidis05d48762011-07-01 22:23:09 +000070 break;
71
John McCall2792fa52011-03-08 04:17:03 +000072 default:
73 // Assume everything else was a function attribute.
74 diagID = diag::warn_function_attribute_wrong_type;
75 break;
76 }
77
78 SourceLocation loc = attr.getLoc();
Chris Lattner5f9e2722011-07-23 10:55:15 +000079 StringRef name = attr.getName()->getName();
John McCall2792fa52011-03-08 04:17:03 +000080
81 // The GC attributes are usually written with macros; special-case them.
Chandler Carruth108f7562011-07-26 05:40:03 +000082 if (useExpansionLoc && loc.isMacroID() && attr.getParameterName()) {
John McCall834e3f62011-03-08 07:59:04 +000083 if (attr.getParameterName()->isStr("strong")) {
84 if (S.findMacroSpelling(loc, "__strong")) name = "__strong";
85 } else if (attr.getParameterName()->isStr("weak")) {
86 if (S.findMacroSpelling(loc, "__weak")) name = "__weak";
John McCall2792fa52011-03-08 04:17:03 +000087 }
88 }
89
90 S.Diag(loc, diagID) << name << type;
91}
92
John McCall711c52b2011-01-05 12:14:39 +000093// objc_gc applies to Objective-C pointers or, otherwise, to the
94// smallest available pointer type (i.e. 'void*' in 'void**').
95#define OBJC_POINTER_TYPE_ATTRS_CASELIST \
Sean Hunt8e083e72012-06-19 23:57:03 +000096 case AttributeList::AT_ObjCGC: \
97 case AttributeList::AT_ObjCOwnership
John McCall04a67a62010-02-05 21:31:56 +000098
John McCall711c52b2011-01-05 12:14:39 +000099// Function type attributes.
100#define FUNCTION_TYPE_ATTRS_CASELIST \
Sean Hunt8e083e72012-06-19 23:57:03 +0000101 case AttributeList::AT_NoReturn: \
102 case AttributeList::AT_CDecl: \
103 case AttributeList::AT_FastCall: \
104 case AttributeList::AT_StdCall: \
105 case AttributeList::AT_ThisCall: \
106 case AttributeList::AT_Pascal: \
107 case AttributeList::AT_Regparm: \
Derek Schuff263366f2012-10-16 22:30:41 +0000108 case AttributeList::AT_Pcs: \
Guy Benyei38980082012-12-25 08:53:55 +0000109 case AttributeList::AT_PnaclCall: \
110 case AttributeList::AT_IntelOclBicc \
John McCall04a67a62010-02-05 21:31:56 +0000111
John McCall711c52b2011-01-05 12:14:39 +0000112namespace {
113 /// An object which stores processing state for the entire
114 /// GetTypeForDeclarator process.
115 class TypeProcessingState {
116 Sema &sema;
117
118 /// The declarator being processed.
119 Declarator &declarator;
120
121 /// The index of the declarator chunk we're currently processing.
122 /// May be the total number of valid chunks, indicating the
123 /// DeclSpec.
124 unsigned chunkIndex;
125
126 /// Whether there are non-trivial modifications to the decl spec.
127 bool trivial;
128
John McCall7ea21932011-03-26 01:39:56 +0000129 /// Whether we saved the attributes in the decl spec.
130 bool hasSavedAttrs;
131
John McCall711c52b2011-01-05 12:14:39 +0000132 /// The original set of attributes on the DeclSpec.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000133 SmallVector<AttributeList*, 2> savedAttrs;
John McCall711c52b2011-01-05 12:14:39 +0000134
135 /// A list of attributes to diagnose the uselessness of when the
136 /// processing is complete.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000137 SmallVector<AttributeList*, 2> ignoredTypeAttrs;
John McCall711c52b2011-01-05 12:14:39 +0000138
139 public:
140 TypeProcessingState(Sema &sema, Declarator &declarator)
141 : sema(sema), declarator(declarator),
142 chunkIndex(declarator.getNumTypeObjects()),
John McCall7ea21932011-03-26 01:39:56 +0000143 trivial(true), hasSavedAttrs(false) {}
John McCall711c52b2011-01-05 12:14:39 +0000144
145 Sema &getSema() const {
146 return sema;
Abramo Bagnarae215f722010-04-30 13:10:51 +0000147 }
John McCall711c52b2011-01-05 12:14:39 +0000148
149 Declarator &getDeclarator() const {
150 return declarator;
151 }
152
John McCallb2381b12013-03-01 07:58:16 +0000153 bool isProcessingDeclSpec() const {
154 return chunkIndex == declarator.getNumTypeObjects();
155 }
156
John McCall711c52b2011-01-05 12:14:39 +0000157 unsigned getCurrentChunkIndex() const {
158 return chunkIndex;
159 }
160
161 void setCurrentChunkIndex(unsigned idx) {
162 assert(idx <= declarator.getNumTypeObjects());
163 chunkIndex = idx;
164 }
165
166 AttributeList *&getCurrentAttrListRef() const {
John McCallb2381b12013-03-01 07:58:16 +0000167 if (isProcessingDeclSpec())
John McCall711c52b2011-01-05 12:14:39 +0000168 return getMutableDeclSpec().getAttributes().getListRef();
169 return declarator.getTypeObject(chunkIndex).getAttrListRef();
170 }
171
172 /// Save the current set of attributes on the DeclSpec.
173 void saveDeclSpecAttrs() {
174 // Don't try to save them multiple times.
John McCall7ea21932011-03-26 01:39:56 +0000175 if (hasSavedAttrs) return;
John McCall711c52b2011-01-05 12:14:39 +0000176
177 DeclSpec &spec = getMutableDeclSpec();
178 for (AttributeList *attr = spec.getAttributes().getList(); attr;
179 attr = attr->getNext())
180 savedAttrs.push_back(attr);
181 trivial &= savedAttrs.empty();
John McCall7ea21932011-03-26 01:39:56 +0000182 hasSavedAttrs = true;
John McCall711c52b2011-01-05 12:14:39 +0000183 }
184
185 /// Record that we had nowhere to put the given type attribute.
186 /// We will diagnose such attributes later.
187 void addIgnoredTypeAttr(AttributeList &attr) {
188 ignoredTypeAttrs.push_back(&attr);
189 }
190
191 /// Diagnose all the ignored type attributes, given that the
192 /// declarator worked out to the given type.
193 void diagnoseIgnoredTypeAttrs(QualType type) const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000194 for (SmallVectorImpl<AttributeList*>::const_iterator
John McCall711c52b2011-01-05 12:14:39 +0000195 i = ignoredTypeAttrs.begin(), e = ignoredTypeAttrs.end();
John McCall2792fa52011-03-08 04:17:03 +0000196 i != e; ++i)
197 diagnoseBadTypeAttribute(getSema(), **i, type);
John McCall711c52b2011-01-05 12:14:39 +0000198 }
199
200 ~TypeProcessingState() {
201 if (trivial) return;
202
203 restoreDeclSpecAttrs();
204 }
205
206 private:
207 DeclSpec &getMutableDeclSpec() const {
208 return const_cast<DeclSpec&>(declarator.getDeclSpec());
209 }
210
211 void restoreDeclSpecAttrs() {
John McCall7ea21932011-03-26 01:39:56 +0000212 assert(hasSavedAttrs);
213
214 if (savedAttrs.empty()) {
215 getMutableDeclSpec().getAttributes().set(0);
216 return;
217 }
218
John McCall711c52b2011-01-05 12:14:39 +0000219 getMutableDeclSpec().getAttributes().set(savedAttrs[0]);
220 for (unsigned i = 0, e = savedAttrs.size() - 1; i != e; ++i)
221 savedAttrs[i]->setNext(savedAttrs[i+1]);
222 savedAttrs.back()->setNext(0);
223 }
224 };
225
226 /// Basically std::pair except that we really want to avoid an
227 /// implicit operator= for safety concerns. It's also a minor
228 /// link-time optimization for this to be a private type.
229 struct AttrAndList {
230 /// The attribute.
231 AttributeList &first;
232
233 /// The head of the list the attribute is currently in.
234 AttributeList *&second;
235
236 AttrAndList(AttributeList &attr, AttributeList *&head)
237 : first(attr), second(head) {}
238 };
John McCall04a67a62010-02-05 21:31:56 +0000239}
240
John McCall711c52b2011-01-05 12:14:39 +0000241namespace llvm {
242 template <> struct isPodLike<AttrAndList> {
243 static const bool value = true;
244 };
245}
246
247static void spliceAttrIntoList(AttributeList &attr, AttributeList *&head) {
248 attr.setNext(head);
249 head = &attr;
250}
251
252static void spliceAttrOutOfList(AttributeList &attr, AttributeList *&head) {
253 if (head == &attr) {
254 head = attr.getNext();
255 return;
John McCall04a67a62010-02-05 21:31:56 +0000256 }
John McCall711c52b2011-01-05 12:14:39 +0000257
258 AttributeList *cur = head;
259 while (true) {
260 assert(cur && cur->getNext() && "ran out of attrs?");
261 if (cur->getNext() == &attr) {
262 cur->setNext(attr.getNext());
263 return;
264 }
265 cur = cur->getNext();
266 }
267}
268
269static void moveAttrFromListToList(AttributeList &attr,
270 AttributeList *&fromList,
271 AttributeList *&toList) {
272 spliceAttrOutOfList(attr, fromList);
273 spliceAttrIntoList(attr, toList);
274}
275
Richard Smithf7a05272013-01-14 07:53:01 +0000276/// The location of a type attribute.
277enum TypeAttrLocation {
278 /// The attribute is in the decl-specifier-seq.
279 TAL_DeclSpec,
280 /// The attribute is part of a DeclaratorChunk.
281 TAL_DeclChunk,
282 /// The attribute is immediately after the declaration's name.
283 TAL_DeclName
284};
285
John McCall711c52b2011-01-05 12:14:39 +0000286static void processTypeAttrs(TypeProcessingState &state,
Richard Smithf7a05272013-01-14 07:53:01 +0000287 QualType &type, TypeAttrLocation TAL,
John McCall711c52b2011-01-05 12:14:39 +0000288 AttributeList *attrs);
289
290static bool handleFunctionTypeAttr(TypeProcessingState &state,
291 AttributeList &attr,
292 QualType &type);
293
294static bool handleObjCGCTypeAttr(TypeProcessingState &state,
295 AttributeList &attr, QualType &type);
296
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +0000297static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
John McCallf85e1932011-06-15 23:02:42 +0000298 AttributeList &attr, QualType &type);
299
John McCall711c52b2011-01-05 12:14:39 +0000300static bool handleObjCPointerTypeAttr(TypeProcessingState &state,
301 AttributeList &attr, QualType &type) {
Sean Hunt8e083e72012-06-19 23:57:03 +0000302 if (attr.getKind() == AttributeList::AT_ObjCGC)
John McCallf85e1932011-06-15 23:02:42 +0000303 return handleObjCGCTypeAttr(state, attr, type);
Sean Hunt8e083e72012-06-19 23:57:03 +0000304 assert(attr.getKind() == AttributeList::AT_ObjCOwnership);
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +0000305 return handleObjCOwnershipTypeAttr(state, attr, type);
John McCall711c52b2011-01-05 12:14:39 +0000306}
307
John McCallb2381b12013-03-01 07:58:16 +0000308/// Given the index of a declarator chunk, check whether that chunk
309/// directly specifies the return type of a function and, if so, find
310/// an appropriate place for it.
311///
312/// \param i - a notional index which the search will start
313/// immediately inside
314static DeclaratorChunk *maybeMovePastReturnType(Declarator &declarator,
315 unsigned i) {
316 assert(i <= declarator.getNumTypeObjects());
317
318 DeclaratorChunk *result = 0;
319
320 // First, look inwards past parens for a function declarator.
321 for (; i != 0; --i) {
322 DeclaratorChunk &fnChunk = declarator.getTypeObject(i-1);
323 switch (fnChunk.Kind) {
324 case DeclaratorChunk::Paren:
325 continue;
326
327 // If we find anything except a function, bail out.
328 case DeclaratorChunk::Pointer:
329 case DeclaratorChunk::BlockPointer:
330 case DeclaratorChunk::Array:
331 case DeclaratorChunk::Reference:
332 case DeclaratorChunk::MemberPointer:
333 return result;
334
335 // If we do find a function declarator, scan inwards from that,
336 // looking for a block-pointer declarator.
337 case DeclaratorChunk::Function:
338 for (--i; i != 0; --i) {
339 DeclaratorChunk &blockChunk = declarator.getTypeObject(i-1);
340 switch (blockChunk.Kind) {
341 case DeclaratorChunk::Paren:
342 case DeclaratorChunk::Pointer:
343 case DeclaratorChunk::Array:
344 case DeclaratorChunk::Function:
345 case DeclaratorChunk::Reference:
346 case DeclaratorChunk::MemberPointer:
347 continue;
348 case DeclaratorChunk::BlockPointer:
349 result = &blockChunk;
350 goto continue_outer;
351 }
352 llvm_unreachable("bad declarator chunk kind");
353 }
354
355 // If we run out of declarators doing that, we're done.
356 return result;
357 }
358 llvm_unreachable("bad declarator chunk kind");
359
360 // Okay, reconsider from our new point.
361 continue_outer: ;
362 }
363
364 // Ran out of chunks, bail out.
365 return result;
366}
367
John McCall711c52b2011-01-05 12:14:39 +0000368/// Given that an objc_gc attribute was written somewhere on a
369/// declaration *other* than on the declarator itself (for which, use
370/// distributeObjCPointerTypeAttrFromDeclarator), and given that it
371/// didn't apply in whatever position it was written in, try to move
372/// it to a more appropriate position.
373static void distributeObjCPointerTypeAttr(TypeProcessingState &state,
374 AttributeList &attr,
375 QualType type) {
376 Declarator &declarator = state.getDeclarator();
John McCallb2381b12013-03-01 07:58:16 +0000377
378 // Move it to the outermost normal or block pointer declarator.
John McCall711c52b2011-01-05 12:14:39 +0000379 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
380 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
381 switch (chunk.Kind) {
382 case DeclaratorChunk::Pointer:
John McCallb2381b12013-03-01 07:58:16 +0000383 case DeclaratorChunk::BlockPointer: {
384 // But don't move an ARC ownership attribute to the return type
385 // of a block.
386 DeclaratorChunk *destChunk = 0;
387 if (state.isProcessingDeclSpec() &&
388 attr.getKind() == AttributeList::AT_ObjCOwnership)
389 destChunk = maybeMovePastReturnType(declarator, i - 1);
390 if (!destChunk) destChunk = &chunk;
391
John McCall711c52b2011-01-05 12:14:39 +0000392 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
John McCallb2381b12013-03-01 07:58:16 +0000393 destChunk->getAttrListRef());
John McCall711c52b2011-01-05 12:14:39 +0000394 return;
John McCallb2381b12013-03-01 07:58:16 +0000395 }
John McCall711c52b2011-01-05 12:14:39 +0000396
397 case DeclaratorChunk::Paren:
398 case DeclaratorChunk::Array:
399 continue;
400
John McCallb2381b12013-03-01 07:58:16 +0000401 // We may be starting at the return type of a block.
402 case DeclaratorChunk::Function:
403 if (state.isProcessingDeclSpec() &&
404 attr.getKind() == AttributeList::AT_ObjCOwnership) {
405 if (DeclaratorChunk *dest = maybeMovePastReturnType(declarator, i)) {
406 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
407 dest->getAttrListRef());
408 return;
409 }
410 }
411 goto error;
412
John McCall711c52b2011-01-05 12:14:39 +0000413 // Don't walk through these.
414 case DeclaratorChunk::Reference:
John McCall711c52b2011-01-05 12:14:39 +0000415 case DeclaratorChunk::MemberPointer:
416 goto error;
417 }
418 }
419 error:
John McCall2792fa52011-03-08 04:17:03 +0000420
421 diagnoseBadTypeAttribute(state.getSema(), attr, type);
John McCall711c52b2011-01-05 12:14:39 +0000422}
423
424/// Distribute an objc_gc type attribute that was written on the
425/// declarator.
426static void
427distributeObjCPointerTypeAttrFromDeclarator(TypeProcessingState &state,
428 AttributeList &attr,
429 QualType &declSpecType) {
430 Declarator &declarator = state.getDeclarator();
431
432 // objc_gc goes on the innermost pointer to something that's not a
433 // pointer.
434 unsigned innermost = -1U;
435 bool considerDeclSpec = true;
436 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
437 DeclaratorChunk &chunk = declarator.getTypeObject(i);
438 switch (chunk.Kind) {
439 case DeclaratorChunk::Pointer:
440 case DeclaratorChunk::BlockPointer:
441 innermost = i;
John McCallae278a32011-01-12 00:34:59 +0000442 continue;
John McCall711c52b2011-01-05 12:14:39 +0000443
444 case DeclaratorChunk::Reference:
445 case DeclaratorChunk::MemberPointer:
446 case DeclaratorChunk::Paren:
447 case DeclaratorChunk::Array:
448 continue;
449
450 case DeclaratorChunk::Function:
451 considerDeclSpec = false;
452 goto done;
453 }
454 }
455 done:
456
457 // That might actually be the decl spec if we weren't blocked by
458 // anything in the declarator.
459 if (considerDeclSpec) {
John McCall7ea21932011-03-26 01:39:56 +0000460 if (handleObjCPointerTypeAttr(state, attr, declSpecType)) {
461 // Splice the attribute into the decl spec. Prevents the
462 // attribute from being applied multiple times and gives
463 // the source-location-filler something to work with.
464 state.saveDeclSpecAttrs();
465 moveAttrFromListToList(attr, declarator.getAttrListRef(),
466 declarator.getMutableDeclSpec().getAttributes().getListRef());
John McCall711c52b2011-01-05 12:14:39 +0000467 return;
John McCall7ea21932011-03-26 01:39:56 +0000468 }
John McCall711c52b2011-01-05 12:14:39 +0000469 }
470
471 // Otherwise, if we found an appropriate chunk, splice the attribute
472 // into it.
473 if (innermost != -1U) {
474 moveAttrFromListToList(attr, declarator.getAttrListRef(),
475 declarator.getTypeObject(innermost).getAttrListRef());
476 return;
477 }
478
479 // Otherwise, diagnose when we're done building the type.
480 spliceAttrOutOfList(attr, declarator.getAttrListRef());
481 state.addIgnoredTypeAttr(attr);
482}
483
484/// A function type attribute was written somewhere in a declaration
485/// *other* than on the declarator itself or in the decl spec. Given
486/// that it didn't apply in whatever position it was written in, try
487/// to move it to a more appropriate position.
488static void distributeFunctionTypeAttr(TypeProcessingState &state,
489 AttributeList &attr,
490 QualType type) {
491 Declarator &declarator = state.getDeclarator();
492
493 // Try to push the attribute from the return type of a function to
494 // the function itself.
495 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
496 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
497 switch (chunk.Kind) {
498 case DeclaratorChunk::Function:
499 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
500 chunk.getAttrListRef());
501 return;
502
503 case DeclaratorChunk::Paren:
504 case DeclaratorChunk::Pointer:
505 case DeclaratorChunk::BlockPointer:
506 case DeclaratorChunk::Array:
507 case DeclaratorChunk::Reference:
508 case DeclaratorChunk::MemberPointer:
509 continue;
510 }
511 }
Chad Rosier91cbbbf2012-06-26 21:41:40 +0000512
John McCall2792fa52011-03-08 04:17:03 +0000513 diagnoseBadTypeAttribute(state.getSema(), attr, type);
John McCall711c52b2011-01-05 12:14:39 +0000514}
515
516/// Try to distribute a function type attribute to the innermost
517/// function chunk or type. Returns true if the attribute was
518/// distributed, false if no location was found.
519static bool
520distributeFunctionTypeAttrToInnermost(TypeProcessingState &state,
521 AttributeList &attr,
522 AttributeList *&attrList,
523 QualType &declSpecType) {
524 Declarator &declarator = state.getDeclarator();
525
526 // Put it on the innermost function chunk, if there is one.
527 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
528 DeclaratorChunk &chunk = declarator.getTypeObject(i);
529 if (chunk.Kind != DeclaratorChunk::Function) continue;
530
531 moveAttrFromListToList(attr, attrList, chunk.getAttrListRef());
532 return true;
533 }
534
John McCallf85e1932011-06-15 23:02:42 +0000535 if (handleFunctionTypeAttr(state, attr, declSpecType)) {
536 spliceAttrOutOfList(attr, attrList);
537 return true;
538 }
539
540 return false;
John McCall711c52b2011-01-05 12:14:39 +0000541}
542
543/// A function type attribute was written in the decl spec. Try to
544/// apply it somewhere.
545static void
546distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state,
547 AttributeList &attr,
548 QualType &declSpecType) {
549 state.saveDeclSpecAttrs();
550
Richard Smith5c521662013-01-15 02:48:13 +0000551 // C++11 attributes before the decl specifiers actually appertain to
552 // the declarators. Move them straight there. We don't support the
553 // 'put them wherever you like' semantics we allow for GNU attributes.
554 if (attr.isCXX11Attribute()) {
555 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
556 state.getDeclarator().getAttrListRef());
557 return;
558 }
559
John McCall711c52b2011-01-05 12:14:39 +0000560 // Try to distribute to the innermost.
561 if (distributeFunctionTypeAttrToInnermost(state, attr,
562 state.getCurrentAttrListRef(),
563 declSpecType))
564 return;
565
566 // If that failed, diagnose the bad attribute when the declarator is
567 // fully built.
568 state.addIgnoredTypeAttr(attr);
569}
570
571/// A function type attribute was written on the declarator. Try to
572/// apply it somewhere.
573static void
574distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state,
575 AttributeList &attr,
576 QualType &declSpecType) {
577 Declarator &declarator = state.getDeclarator();
578
579 // Try to distribute to the innermost.
580 if (distributeFunctionTypeAttrToInnermost(state, attr,
581 declarator.getAttrListRef(),
582 declSpecType))
583 return;
584
585 // If that failed, diagnose the bad attribute when the declarator is
586 // fully built.
587 spliceAttrOutOfList(attr, declarator.getAttrListRef());
588 state.addIgnoredTypeAttr(attr);
589}
590
591/// \brief Given that there are attributes written on the declarator
592/// itself, try to distribute any type attributes to the appropriate
593/// declarator chunk.
594///
595/// These are attributes like the following:
596/// int f ATTR;
597/// int (f ATTR)();
598/// but not necessarily this:
599/// int f() ATTR;
600static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state,
601 QualType &declSpecType) {
602 // Collect all the type attributes from the declarator itself.
603 assert(state.getDeclarator().getAttributes() && "declarator has no attrs!");
604 AttributeList *attr = state.getDeclarator().getAttributes();
605 AttributeList *next;
606 do {
607 next = attr->getNext();
608
Richard Smith5c521662013-01-15 02:48:13 +0000609 // Do not distribute C++11 attributes. They have strict rules for what
610 // they appertain to.
611 if (attr->isCXX11Attribute())
612 continue;
613
John McCall711c52b2011-01-05 12:14:39 +0000614 switch (attr->getKind()) {
615 OBJC_POINTER_TYPE_ATTRS_CASELIST:
616 distributeObjCPointerTypeAttrFromDeclarator(state, *attr, declSpecType);
617 break;
618
Sean Hunt8e083e72012-06-19 23:57:03 +0000619 case AttributeList::AT_NSReturnsRetained:
David Blaikie4e4d0842012-03-11 07:00:24 +0000620 if (!state.getSema().getLangOpts().ObjCAutoRefCount)
John McCallf85e1932011-06-15 23:02:42 +0000621 break;
622 // fallthrough
623
John McCall711c52b2011-01-05 12:14:39 +0000624 FUNCTION_TYPE_ATTRS_CASELIST:
625 distributeFunctionTypeAttrFromDeclarator(state, *attr, declSpecType);
626 break;
627
628 default:
629 break;
630 }
631 } while ((attr = next));
632}
633
634/// Add a synthetic '()' to a block-literal declarator if it is
635/// required, given the return type.
636static void maybeSynthesizeBlockSignature(TypeProcessingState &state,
637 QualType declSpecType) {
638 Declarator &declarator = state.getDeclarator();
639
640 // First, check whether the declarator would produce a function,
641 // i.e. whether the innermost semantic chunk is a function.
642 if (declarator.isFunctionDeclarator()) {
643 // If so, make that declarator a prototyped declarator.
644 declarator.getFunctionTypeInfo().hasPrototype = true;
645 return;
646 }
647
John McCallda263792011-02-08 01:59:10 +0000648 // If there are any type objects, the type as written won't name a
649 // function, regardless of the decl spec type. This is because a
650 // block signature declarator is always an abstract-declarator, and
651 // abstract-declarators can't just be parentheses chunks. Therefore
652 // we need to build a function chunk unless there are no type
653 // objects and the decl spec type is a function.
John McCall711c52b2011-01-05 12:14:39 +0000654 if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType())
655 return;
656
John McCallda263792011-02-08 01:59:10 +0000657 // Note that there *are* cases with invalid declarators where
658 // declarators consist solely of parentheses. In general, these
659 // occur only in failed efforts to make function declarators, so
660 // faking up the function chunk is still the right thing to do.
John McCall711c52b2011-01-05 12:14:39 +0000661
662 // Otherwise, we need to fake up a function declarator.
Daniel Dunbar96a00142012-03-09 18:35:03 +0000663 SourceLocation loc = declarator.getLocStart();
John McCall711c52b2011-01-05 12:14:39 +0000664
665 // ...and *prepend* it to the declarator.
Abramo Bagnara59c0a812012-10-04 21:42:10 +0000666 SourceLocation NoLoc;
John McCall711c52b2011-01-05 12:14:39 +0000667 declarator.AddInnermostTypeInfo(DeclaratorChunk::getFunction(
Abramo Bagnara59c0a812012-10-04 21:42:10 +0000668 /*HasProto=*/true,
669 /*IsAmbiguous=*/false,
670 /*LParenLoc=*/NoLoc,
671 /*ArgInfo=*/0,
672 /*NumArgs=*/0,
673 /*EllipsisLoc=*/NoLoc,
674 /*RParenLoc=*/NoLoc,
675 /*TypeQuals=*/0,
676 /*RefQualifierIsLvalueRef=*/true,
677 /*RefQualifierLoc=*/NoLoc,
678 /*ConstQualifierLoc=*/NoLoc,
679 /*VolatileQualifierLoc=*/NoLoc,
680 /*MutableLoc=*/NoLoc,
681 EST_None,
682 /*ESpecLoc=*/NoLoc,
683 /*Exceptions=*/0,
684 /*ExceptionRanges=*/0,
685 /*NumExceptions=*/0,
686 /*NoexceptExpr=*/0,
687 loc, loc, declarator));
John McCall711c52b2011-01-05 12:14:39 +0000688
689 // For consistency, make sure the state still has us as processing
690 // the decl spec.
691 assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1);
692 state.setCurrentChunkIndex(declarator.getNumTypeObjects());
John McCall04a67a62010-02-05 21:31:56 +0000693}
694
Douglas Gregor930d8b52009-01-30 22:09:00 +0000695/// \brief Convert the specified declspec to the appropriate type
696/// object.
James Dennett1dfbd922012-06-14 21:40:34 +0000697/// \param state Specifies the declarator containing the declaration specifier
698/// to be converted, along with other associated processing state.
Chris Lattner5153ee62009-04-25 08:47:54 +0000699/// \returns The type described by the declaration specifiers. This function
700/// never returns null.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +0000701static QualType ConvertDeclSpecToType(TypeProcessingState &state) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000702 // FIXME: Should move the logic from DeclSpec::Finish to here for validity
703 // checking.
John McCall711c52b2011-01-05 12:14:39 +0000704
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +0000705 Sema &S = state.getSema();
John McCall711c52b2011-01-05 12:14:39 +0000706 Declarator &declarator = state.getDeclarator();
707 const DeclSpec &DS = declarator.getDeclSpec();
708 SourceLocation DeclLoc = declarator.getIdentifierLoc();
Chris Lattner5db2bb12009-10-25 18:21:37 +0000709 if (DeclLoc.isInvalid())
Daniel Dunbar96a00142012-03-09 18:35:03 +0000710 DeclLoc = DS.getLocStart();
Chad Rosier91cbbbf2012-06-26 21:41:40 +0000711
John McCall711c52b2011-01-05 12:14:39 +0000712 ASTContext &Context = S.Context;
Mike Stump1eb44332009-09-09 15:08:12 +0000713
Chris Lattner5db2bb12009-10-25 18:21:37 +0000714 QualType Result;
Reid Spencer5f016e22007-07-11 17:01:13 +0000715 switch (DS.getTypeSpecType()) {
Chris Lattner96b77fc2008-04-02 06:50:17 +0000716 case DeclSpec::TST_void:
717 Result = Context.VoidTy;
718 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000719 case DeclSpec::TST_char:
720 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
Chris Lattnerfab5b452008-02-20 23:53:49 +0000721 Result = Context.CharTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000722 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed)
Chris Lattnerfab5b452008-02-20 23:53:49 +0000723 Result = Context.SignedCharTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000724 else {
725 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
726 "Unknown TSS value");
Chris Lattnerfab5b452008-02-20 23:53:49 +0000727 Result = Context.UnsignedCharTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000728 }
Chris Lattner958858e2008-02-20 21:40:32 +0000729 break;
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000730 case DeclSpec::TST_wchar:
731 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
732 Result = Context.WCharTy;
733 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) {
John McCall711c52b2011-01-05 12:14:39 +0000734 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000735 << DS.getSpecifierName(DS.getTypeSpecType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000736 Result = Context.getSignedWCharType();
737 } else {
738 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
739 "Unknown TSS value");
John McCall711c52b2011-01-05 12:14:39 +0000740 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000741 << DS.getSpecifierName(DS.getTypeSpecType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000742 Result = Context.getUnsignedWCharType();
743 }
744 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000745 case DeclSpec::TST_char16:
746 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
747 "Unknown TSS value");
748 Result = Context.Char16Ty;
749 break;
750 case DeclSpec::TST_char32:
751 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
752 "Unknown TSS value");
753 Result = Context.Char32Ty;
754 break;
Chris Lattnerd658b562008-04-05 06:32:51 +0000755 case DeclSpec::TST_unspecified:
Chris Lattner62f5f7f2008-07-26 00:46:50 +0000756 // "<proto1,proto2>" is an objc qualified ID with a missing id.
Chris Lattner097e9162008-10-20 02:01:50 +0000757 if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) {
John McCallc12c5bb2010-05-15 11:32:37 +0000758 Result = Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
Roman Divacky31ba6132012-09-06 15:59:27 +0000759 (ObjCProtocolDecl*const*)PQ,
John McCallc12c5bb2010-05-15 11:32:37 +0000760 DS.getNumProtocolQualifiers());
761 Result = Context.getObjCObjectPointerType(Result);
Chris Lattner62f5f7f2008-07-26 00:46:50 +0000762 break;
763 }
Chad Rosier91cbbbf2012-06-26 21:41:40 +0000764
Chris Lattner5db2bb12009-10-25 18:21:37 +0000765 // If this is a missing declspec in a block literal return context, then it
766 // is inferred from the return statements inside the block.
Eli Friedmanf88c4002012-01-04 04:41:38 +0000767 // The declspec is always missing in a lambda expr context; it is either
768 // specified with a trailing return type or inferred.
769 if (declarator.getContext() == Declarator::LambdaExprContext ||
770 isOmittedBlockReturnType(declarator)) {
Chris Lattner5db2bb12009-10-25 18:21:37 +0000771 Result = Context.DependentTy;
772 break;
773 }
Mike Stump1eb44332009-09-09 15:08:12 +0000774
Chris Lattnerd658b562008-04-05 06:32:51 +0000775 // Unspecified typespec defaults to int in C90. However, the C90 grammar
776 // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
777 // type-qualifier, or storage-class-specifier. If not, emit an extwarn.
778 // Note that the one exception to this is function definitions, which are
779 // allowed to be completely missing a declspec. This is handled in the
780 // parser already though by it pretending to have seen an 'int' in this
781 // case.
David Blaikie4e4d0842012-03-11 07:00:24 +0000782 if (S.getLangOpts().ImplicitInt) {
Chris Lattner35d276f2009-02-27 18:53:28 +0000783 // In C89 mode, we only warn if there is a completely missing declspec
784 // when one is not allowed.
Chris Lattner3f84ad22009-04-22 05:27:59 +0000785 if (DS.isEmpty()) {
John McCall711c52b2011-01-05 12:14:39 +0000786 S.Diag(DeclLoc, diag::ext_missing_declspec)
Chris Lattner3f84ad22009-04-22 05:27:59 +0000787 << DS.getSourceRange()
Daniel Dunbar96a00142012-03-09 18:35:03 +0000788 << FixItHint::CreateInsertion(DS.getLocStart(), "int");
Chris Lattner3f84ad22009-04-22 05:27:59 +0000789 }
Douglas Gregor4310f4e2009-02-16 22:38:20 +0000790 } else if (!DS.hasTypeSpecifier()) {
Chris Lattnerd658b562008-04-05 06:32:51 +0000791 // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says:
792 // "At least one type specifier shall be given in the declaration
793 // specifiers in each declaration, and in the specifier-qualifier list in
794 // each struct declaration and type name."
Douglas Gregor4310f4e2009-02-16 22:38:20 +0000795 // FIXME: Does Microsoft really have the implicit int extension in C++?
David Blaikie4e4d0842012-03-11 07:00:24 +0000796 if (S.getLangOpts().CPlusPlus &&
797 !S.getLangOpts().MicrosoftExt) {
John McCall711c52b2011-01-05 12:14:39 +0000798 S.Diag(DeclLoc, diag::err_missing_type_specifier)
Chris Lattner3f84ad22009-04-22 05:27:59 +0000799 << DS.getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000800
Chris Lattnerb78d8332009-06-26 04:45:06 +0000801 // When this occurs in C++ code, often something is very broken with the
802 // value being declared, poison it as invalid so we don't get chains of
803 // errors.
John McCall711c52b2011-01-05 12:14:39 +0000804 declarator.setInvalidType(true);
Chris Lattnerb78d8332009-06-26 04:45:06 +0000805 } else {
John McCall711c52b2011-01-05 12:14:39 +0000806 S.Diag(DeclLoc, diag::ext_missing_type_specifier)
Chris Lattner3f84ad22009-04-22 05:27:59 +0000807 << DS.getSourceRange();
Chris Lattnerb78d8332009-06-26 04:45:06 +0000808 }
Chris Lattnerd658b562008-04-05 06:32:51 +0000809 }
Mike Stump1eb44332009-09-09 15:08:12 +0000810
811 // FALL THROUGH.
Chris Lattner3cbc38b2007-08-21 17:02:28 +0000812 case DeclSpec::TST_int: {
Reid Spencer5f016e22007-07-11 17:01:13 +0000813 if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) {
814 switch (DS.getTypeSpecWidth()) {
Chris Lattnerfab5b452008-02-20 23:53:49 +0000815 case DeclSpec::TSW_unspecified: Result = Context.IntTy; break;
816 case DeclSpec::TSW_short: Result = Context.ShortTy; break;
817 case DeclSpec::TSW_long: Result = Context.LongTy; break;
Chris Lattner311157f2009-10-25 18:25:04 +0000818 case DeclSpec::TSW_longlong:
819 Result = Context.LongLongTy;
Chad Rosier91cbbbf2012-06-26 21:41:40 +0000820
Dmitri Gribenkoe3b136b2012-09-24 18:19:21 +0000821 // 'long long' is a C99 or C++11 feature.
822 if (!S.getLangOpts().C99) {
823 if (S.getLangOpts().CPlusPlus)
824 S.Diag(DS.getTypeSpecWidthLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +0000825 S.getLangOpts().CPlusPlus11 ?
Dmitri Gribenkoe3b136b2012-09-24 18:19:21 +0000826 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
827 else
828 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
829 }
Chris Lattner311157f2009-10-25 18:25:04 +0000830 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000831 }
832 } else {
833 switch (DS.getTypeSpecWidth()) {
Chris Lattnerfab5b452008-02-20 23:53:49 +0000834 case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break;
835 case DeclSpec::TSW_short: Result = Context.UnsignedShortTy; break;
836 case DeclSpec::TSW_long: Result = Context.UnsignedLongTy; break;
Chris Lattner311157f2009-10-25 18:25:04 +0000837 case DeclSpec::TSW_longlong:
838 Result = Context.UnsignedLongLongTy;
Chad Rosier91cbbbf2012-06-26 21:41:40 +0000839
Dmitri Gribenkoe3b136b2012-09-24 18:19:21 +0000840 // 'long long' is a C99 or C++11 feature.
841 if (!S.getLangOpts().C99) {
842 if (S.getLangOpts().CPlusPlus)
843 S.Diag(DS.getTypeSpecWidthLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +0000844 S.getLangOpts().CPlusPlus11 ?
Dmitri Gribenkoe3b136b2012-09-24 18:19:21 +0000845 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
846 else
847 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
848 }
Chris Lattner311157f2009-10-25 18:25:04 +0000849 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000850 }
851 }
Chris Lattner958858e2008-02-20 21:40:32 +0000852 break;
Chris Lattner3cbc38b2007-08-21 17:02:28 +0000853 }
Richard Smith5a5a9712012-04-04 06:24:32 +0000854 case DeclSpec::TST_int128:
Richard Smith84268902012-11-29 05:41:51 +0000855 if (!S.PP.getTargetInfo().hasInt128Type())
856 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_int128_unsupported);
Richard Smith5a5a9712012-04-04 06:24:32 +0000857 if (DS.getTypeSpecSign() == DeclSpec::TSS_unsigned)
858 Result = Context.UnsignedInt128Ty;
859 else
860 Result = Context.Int128Ty;
861 break;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000862 case DeclSpec::TST_half: Result = Context.HalfTy; break;
Chris Lattnerfab5b452008-02-20 23:53:49 +0000863 case DeclSpec::TST_float: Result = Context.FloatTy; break;
Chris Lattner958858e2008-02-20 21:40:32 +0000864 case DeclSpec::TST_double:
865 if (DS.getTypeSpecWidth() == DeclSpec::TSW_long)
Chris Lattnerfab5b452008-02-20 23:53:49 +0000866 Result = Context.LongDoubleTy;
Chris Lattner958858e2008-02-20 21:40:32 +0000867 else
Chris Lattnerfab5b452008-02-20 23:53:49 +0000868 Result = Context.DoubleTy;
Peter Collingbourne39d3e7a2011-02-15 19:46:23 +0000869
David Blaikie4e4d0842012-03-11 07:00:24 +0000870 if (S.getLangOpts().OpenCL && !S.getOpenCLOptions().cl_khr_fp64) {
Peter Collingbourne39d3e7a2011-02-15 19:46:23 +0000871 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_double_requires_fp64);
872 declarator.setInvalidType(true);
873 }
Chris Lattner958858e2008-02-20 21:40:32 +0000874 break;
Chris Lattnerfab5b452008-02-20 23:53:49 +0000875 case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool
Reid Spencer5f016e22007-07-11 17:01:13 +0000876 case DeclSpec::TST_decimal32: // _Decimal32
877 case DeclSpec::TST_decimal64: // _Decimal64
878 case DeclSpec::TST_decimal128: // _Decimal128
John McCall711c52b2011-01-05 12:14:39 +0000879 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
Chris Lattner8f12f652009-05-13 05:02:08 +0000880 Result = Context.IntTy;
John McCall711c52b2011-01-05 12:14:39 +0000881 declarator.setInvalidType(true);
Chris Lattner8f12f652009-05-13 05:02:08 +0000882 break;
Chris Lattner99dc9142008-04-13 18:59:07 +0000883 case DeclSpec::TST_class:
Reid Spencer5f016e22007-07-11 17:01:13 +0000884 case DeclSpec::TST_enum:
885 case DeclSpec::TST_union:
Joao Matos6666ed42012-08-31 18:45:21 +0000886 case DeclSpec::TST_struct:
887 case DeclSpec::TST_interface: {
John McCallb3d87482010-08-24 05:47:05 +0000888 TypeDecl *D = dyn_cast_or_null<TypeDecl>(DS.getRepAsDecl());
John McCall6e247262009-10-10 05:48:19 +0000889 if (!D) {
890 // This can happen in C++ with ambiguous lookups.
891 Result = Context.IntTy;
John McCall711c52b2011-01-05 12:14:39 +0000892 declarator.setInvalidType(true);
John McCall6e247262009-10-10 05:48:19 +0000893 break;
894 }
895
Chris Lattnera64ef0a2009-10-25 22:09:09 +0000896 // If the type is deprecated or unavailable, diagnose it.
Abramo Bagnara0daaf322011-03-16 20:16:18 +0000897 S.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeNameLoc());
Chad Rosier91cbbbf2012-06-26 21:41:40 +0000898
Reid Spencer5f016e22007-07-11 17:01:13 +0000899 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
Chris Lattnera64ef0a2009-10-25 22:09:09 +0000900 DS.getTypeSpecSign() == 0 && "No qualifiers on tag names!");
Chad Rosier91cbbbf2012-06-26 21:41:40 +0000901
Reid Spencer5f016e22007-07-11 17:01:13 +0000902 // TypeQuals handled by caller.
Chris Lattnera64ef0a2009-10-25 22:09:09 +0000903 Result = Context.getTypeDeclType(D);
John McCall2191b202009-09-05 06:31:47 +0000904
Abramo Bagnara0daaf322011-03-16 20:16:18 +0000905 // In both C and C++, make an ElaboratedType.
906 ElaboratedTypeKeyword Keyword
907 = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType());
908 Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result);
Chris Lattner958858e2008-02-20 21:40:32 +0000909 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000910 }
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000911 case DeclSpec::TST_typename: {
Reid Spencer5f016e22007-07-11 17:01:13 +0000912 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
913 DS.getTypeSpecSign() == 0 &&
914 "Can't handle qualifiers on typedef names yet!");
John McCall711c52b2011-01-05 12:14:39 +0000915 Result = S.GetTypeFromParser(DS.getRepAsType());
John McCall27940d22010-07-30 05:17:22 +0000916 if (Result.isNull())
John McCall711c52b2011-01-05 12:14:39 +0000917 declarator.setInvalidType(true);
John McCall27940d22010-07-30 05:17:22 +0000918 else if (DeclSpec::ProtocolQualifierListTy PQ
919 = DS.getProtocolQualifiers()) {
John McCallc12c5bb2010-05-15 11:32:37 +0000920 if (const ObjCObjectType *ObjT = Result->getAs<ObjCObjectType>()) {
921 // Silently drop any existing protocol qualifiers.
922 // TODO: determine whether that's the right thing to do.
923 if (ObjT->getNumProtocols())
924 Result = ObjT->getBaseType();
925
926 if (DS.getNumProtocolQualifiers())
927 Result = Context.getObjCObjectType(Result,
Roman Divacky31ba6132012-09-06 15:59:27 +0000928 (ObjCProtocolDecl*const*) PQ,
John McCallc12c5bb2010-05-15 11:32:37 +0000929 DS.getNumProtocolQualifiers());
930 } else if (Result->isObjCIdType()) {
Chris Lattnerae4da612008-07-26 01:53:50 +0000931 // id<protocol-list>
John McCallc12c5bb2010-05-15 11:32:37 +0000932 Result = Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
Roman Divacky31ba6132012-09-06 15:59:27 +0000933 (ObjCProtocolDecl*const*) PQ,
John McCallc12c5bb2010-05-15 11:32:37 +0000934 DS.getNumProtocolQualifiers());
935 Result = Context.getObjCObjectPointerType(Result);
936 } else if (Result->isObjCClassType()) {
Steve Naroff4262a072009-02-23 18:53:24 +0000937 // Class<protocol-list>
John McCallc12c5bb2010-05-15 11:32:37 +0000938 Result = Context.getObjCObjectType(Context.ObjCBuiltinClassTy,
Roman Divacky31ba6132012-09-06 15:59:27 +0000939 (ObjCProtocolDecl*const*) PQ,
John McCallc12c5bb2010-05-15 11:32:37 +0000940 DS.getNumProtocolQualifiers());
941 Result = Context.getObjCObjectPointerType(Result);
Chris Lattner3f84ad22009-04-22 05:27:59 +0000942 } else {
John McCall711c52b2011-01-05 12:14:39 +0000943 S.Diag(DeclLoc, diag::err_invalid_protocol_qualifiers)
Chris Lattner3f84ad22009-04-22 05:27:59 +0000944 << DS.getSourceRange();
John McCall711c52b2011-01-05 12:14:39 +0000945 declarator.setInvalidType(true);
Chris Lattner3f84ad22009-04-22 05:27:59 +0000946 }
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000947 }
Mike Stump1eb44332009-09-09 15:08:12 +0000948
Reid Spencer5f016e22007-07-11 17:01:13 +0000949 // TypeQuals handled by caller.
Chris Lattner958858e2008-02-20 21:40:32 +0000950 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000951 }
Chris Lattner958858e2008-02-20 21:40:32 +0000952 case DeclSpec::TST_typeofType:
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000953 // FIXME: Preserve type source info.
John McCall711c52b2011-01-05 12:14:39 +0000954 Result = S.GetTypeFromParser(DS.getRepAsType());
Chris Lattner958858e2008-02-20 21:40:32 +0000955 assert(!Result.isNull() && "Didn't get a type for typeof?");
Fariborz Jahanian730e1752010-10-06 17:00:02 +0000956 if (!Result->isDependentType())
957 if (const TagType *TT = Result->getAs<TagType>())
John McCall711c52b2011-01-05 12:14:39 +0000958 S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc());
Steve Naroffd1861fd2007-07-31 12:34:36 +0000959 // TypeQuals handled by caller.
Chris Lattnerfab5b452008-02-20 23:53:49 +0000960 Result = Context.getTypeOfType(Result);
Chris Lattner958858e2008-02-20 21:40:32 +0000961 break;
Steve Naroffd1861fd2007-07-31 12:34:36 +0000962 case DeclSpec::TST_typeofExpr: {
John McCallb3d87482010-08-24 05:47:05 +0000963 Expr *E = DS.getRepAsExpr();
Steve Naroffd1861fd2007-07-31 12:34:36 +0000964 assert(E && "Didn't get an expression for typeof?");
965 // TypeQuals handled by caller.
John McCall711c52b2011-01-05 12:14:39 +0000966 Result = S.BuildTypeofExprType(E, DS.getTypeSpecTypeLoc());
Douglas Gregor4b52e252009-12-21 23:17:24 +0000967 if (Result.isNull()) {
968 Result = Context.IntTy;
John McCall711c52b2011-01-05 12:14:39 +0000969 declarator.setInvalidType(true);
Douglas Gregor4b52e252009-12-21 23:17:24 +0000970 }
Chris Lattner958858e2008-02-20 21:40:32 +0000971 break;
Steve Naroffd1861fd2007-07-31 12:34:36 +0000972 }
Anders Carlsson6fd634f2009-06-24 17:47:40 +0000973 case DeclSpec::TST_decltype: {
John McCallb3d87482010-08-24 05:47:05 +0000974 Expr *E = DS.getRepAsExpr();
Anders Carlsson6fd634f2009-06-24 17:47:40 +0000975 assert(E && "Didn't get an expression for decltype?");
976 // TypeQuals handled by caller.
John McCall711c52b2011-01-05 12:14:39 +0000977 Result = S.BuildDecltypeType(E, DS.getTypeSpecTypeLoc());
Anders Carlssonaf017e62009-06-29 22:58:55 +0000978 if (Result.isNull()) {
979 Result = Context.IntTy;
John McCall711c52b2011-01-05 12:14:39 +0000980 declarator.setInvalidType(true);
Anders Carlssonaf017e62009-06-29 22:58:55 +0000981 }
Anders Carlsson6fd634f2009-06-24 17:47:40 +0000982 break;
983 }
Sean Huntca63c202011-05-24 22:41:36 +0000984 case DeclSpec::TST_underlyingType:
Sean Huntdb5d44b2011-05-19 05:37:45 +0000985 Result = S.GetTypeFromParser(DS.getRepAsType());
986 assert(!Result.isNull() && "Didn't get a type for __underlying_type?");
Sean Huntca63c202011-05-24 22:41:36 +0000987 Result = S.BuildUnaryTransformType(Result,
988 UnaryTransformType::EnumUnderlyingType,
989 DS.getTypeSpecTypeLoc());
990 if (Result.isNull()) {
991 Result = Context.IntTy;
992 declarator.setInvalidType(true);
Sean Huntdb5d44b2011-05-19 05:37:45 +0000993 }
Chad Rosier91cbbbf2012-06-26 21:41:40 +0000994 break;
Sean Huntdb5d44b2011-05-19 05:37:45 +0000995
Anders Carlssone89d1592009-06-26 18:41:36 +0000996 case DeclSpec::TST_auto: {
997 // TypeQuals handled by caller.
Richard Smith34b41d92011-02-20 03:19:35 +0000998 Result = Context.getAutoType(QualType());
Anders Carlssone89d1592009-06-26 18:41:36 +0000999 break;
1000 }
Mike Stump1eb44332009-09-09 15:08:12 +00001001
John McCalla5fc4722011-04-09 22:50:59 +00001002 case DeclSpec::TST_unknown_anytype:
1003 Result = Context.UnknownAnyTy;
1004 break;
1005
Eli Friedmanb001de72011-10-06 23:00:33 +00001006 case DeclSpec::TST_atomic:
1007 Result = S.GetTypeFromParser(DS.getRepAsType());
1008 assert(!Result.isNull() && "Didn't get a type for _Atomic?");
1009 Result = S.BuildAtomicType(Result, DS.getTypeSpecTypeLoc());
1010 if (Result.isNull()) {
1011 Result = Context.IntTy;
1012 declarator.setInvalidType(true);
1013 }
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001014 break;
Eli Friedmanb001de72011-10-06 23:00:33 +00001015
Guy Benyeib13621d2012-12-18 14:38:23 +00001016 case DeclSpec::TST_image1d_t:
1017 Result = Context.OCLImage1dTy;
1018 break;
1019
1020 case DeclSpec::TST_image1d_array_t:
1021 Result = Context.OCLImage1dArrayTy;
1022 break;
1023
1024 case DeclSpec::TST_image1d_buffer_t:
1025 Result = Context.OCLImage1dBufferTy;
1026 break;
1027
1028 case DeclSpec::TST_image2d_t:
1029 Result = Context.OCLImage2dTy;
1030 break;
1031
1032 case DeclSpec::TST_image2d_array_t:
1033 Result = Context.OCLImage2dArrayTy;
1034 break;
1035
1036 case DeclSpec::TST_image3d_t:
1037 Result = Context.OCLImage3dTy;
1038 break;
1039
Guy Benyei21f18c42013-02-07 10:55:47 +00001040 case DeclSpec::TST_sampler_t:
1041 Result = Context.OCLSamplerTy;
1042 break;
1043
Guy Benyeie6b9d802013-01-20 12:31:11 +00001044 case DeclSpec::TST_event_t:
1045 Result = Context.OCLEventTy;
1046 break;
1047
Douglas Gregor809070a2009-02-18 17:45:20 +00001048 case DeclSpec::TST_error:
Chris Lattner5153ee62009-04-25 08:47:54 +00001049 Result = Context.IntTy;
John McCall711c52b2011-01-05 12:14:39 +00001050 declarator.setInvalidType(true);
Chris Lattner5153ee62009-04-25 08:47:54 +00001051 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001052 }
Mike Stump1eb44332009-09-09 15:08:12 +00001053
Chris Lattner958858e2008-02-20 21:40:32 +00001054 // Handle complex types.
Douglas Gregorf244cd72009-02-14 21:06:05 +00001055 if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001056 if (S.getLangOpts().Freestanding)
John McCall711c52b2011-01-05 12:14:39 +00001057 S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
Chris Lattnerfab5b452008-02-20 23:53:49 +00001058 Result = Context.getComplexType(Result);
John Thompson82287d12010-02-05 00:12:22 +00001059 } else if (DS.isTypeAltiVecVector()) {
1060 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result));
1061 assert(typeSize > 0 && "type size for vector must be greater than 0 bits");
Bob Wilsone86d78c2010-11-10 21:56:12 +00001062 VectorType::VectorKind VecKind = VectorType::AltiVecVector;
Chris Lattner788b0fd2010-06-23 06:00:24 +00001063 if (DS.isTypeAltiVecPixel())
Bob Wilsone86d78c2010-11-10 21:56:12 +00001064 VecKind = VectorType::AltiVecPixel;
Chris Lattner788b0fd2010-06-23 06:00:24 +00001065 else if (DS.isTypeAltiVecBool())
Bob Wilsone86d78c2010-11-10 21:56:12 +00001066 VecKind = VectorType::AltiVecBool;
1067 Result = Context.getVectorType(Result, 128/typeSize, VecKind);
Douglas Gregorf244cd72009-02-14 21:06:05 +00001068 }
Mike Stump1eb44332009-09-09 15:08:12 +00001069
Argyrios Kyrtzidis47423bd2010-09-23 09:40:31 +00001070 // FIXME: Imaginary.
1071 if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary)
John McCall711c52b2011-01-05 12:14:39 +00001072 S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported);
Mike Stump1eb44332009-09-09 15:08:12 +00001073
John McCall711c52b2011-01-05 12:14:39 +00001074 // Before we process any type attributes, synthesize a block literal
1075 // function declarator if necessary.
1076 if (declarator.getContext() == Declarator::BlockLiteralContext)
1077 maybeSynthesizeBlockSignature(state, Result);
1078
1079 // Apply any type attributes from the decl spec. This may cause the
1080 // list of type attributes to be temporarily saved while the type
1081 // attributes are pushed around.
1082 if (AttributeList *attrs = DS.getAttributes().getList())
Richard Smithf7a05272013-01-14 07:53:01 +00001083 processTypeAttrs(state, Result, TAL_DeclSpec, attrs);
Mike Stump1eb44332009-09-09 15:08:12 +00001084
Chris Lattner96b77fc2008-04-02 06:50:17 +00001085 // Apply const/volatile/restrict qualifiers to T.
1086 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
1087
1088 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
1089 // or incomplete types shall not be restrict-qualified." C++ also allows
1090 // restrict-qualified references.
John McCall0953e762009-09-24 19:53:00 +00001091 if (TypeQuals & DeclSpec::TQ_restrict) {
Fariborz Jahanian2b5ff1a2009-12-07 18:08:58 +00001092 if (Result->isAnyPointerType() || Result->isReferenceType()) {
1093 QualType EltTy;
1094 if (Result->isObjCObjectPointerType())
1095 EltTy = Result;
1096 else
1097 EltTy = Result->isPointerType() ?
1098 Result->getAs<PointerType>()->getPointeeType() :
1099 Result->getAs<ReferenceType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00001100
Douglas Gregorbad0e652009-03-24 20:32:41 +00001101 // If we have a pointer or reference, the pointee must have an object
Chris Lattnerbdcd6372008-04-02 17:35:06 +00001102 // incomplete type.
1103 if (!EltTy->isIncompleteOrObjectType()) {
John McCall711c52b2011-01-05 12:14:39 +00001104 S.Diag(DS.getRestrictSpecLoc(),
Chris Lattnerd3a94e22008-11-20 06:06:08 +00001105 diag::err_typecheck_invalid_restrict_invalid_pointee)
Chris Lattnerd1625842008-11-24 06:25:27 +00001106 << EltTy << DS.getSourceRange();
John McCall0953e762009-09-24 19:53:00 +00001107 TypeQuals &= ~DeclSpec::TQ_restrict; // Remove the restrict qualifier.
Chris Lattnerbdcd6372008-04-02 17:35:06 +00001108 }
1109 } else {
John McCall711c52b2011-01-05 12:14:39 +00001110 S.Diag(DS.getRestrictSpecLoc(),
1111 diag::err_typecheck_invalid_restrict_not_pointer)
Chris Lattnerd1625842008-11-24 06:25:27 +00001112 << Result << DS.getSourceRange();
John McCall0953e762009-09-24 19:53:00 +00001113 TypeQuals &= ~DeclSpec::TQ_restrict; // Remove the restrict qualifier.
Chris Lattner96b77fc2008-04-02 06:50:17 +00001114 }
Chris Lattner96b77fc2008-04-02 06:50:17 +00001115 }
Mike Stump1eb44332009-09-09 15:08:12 +00001116
Chris Lattner96b77fc2008-04-02 06:50:17 +00001117 // Warn about CV qualifiers on functions: C99 6.7.3p8: "If the specification
1118 // of a function type includes any type qualifiers, the behavior is
1119 // undefined."
1120 if (Result->isFunctionType() && TypeQuals) {
1121 // Get some location to point at, either the C or V location.
1122 SourceLocation Loc;
John McCall0953e762009-09-24 19:53:00 +00001123 if (TypeQuals & DeclSpec::TQ_const)
Chris Lattner96b77fc2008-04-02 06:50:17 +00001124 Loc = DS.getConstSpecLoc();
John McCall0953e762009-09-24 19:53:00 +00001125 else if (TypeQuals & DeclSpec::TQ_volatile)
Chris Lattner96b77fc2008-04-02 06:50:17 +00001126 Loc = DS.getVolatileSpecLoc();
John McCall0953e762009-09-24 19:53:00 +00001127 else {
1128 assert((TypeQuals & DeclSpec::TQ_restrict) &&
1129 "Has CVR quals but not C, V, or R?");
1130 Loc = DS.getRestrictSpecLoc();
Chris Lattner96b77fc2008-04-02 06:50:17 +00001131 }
John McCall711c52b2011-01-05 12:14:39 +00001132 S.Diag(Loc, diag::warn_typecheck_function_qualifiers)
Chris Lattnerd1625842008-11-24 06:25:27 +00001133 << Result << DS.getSourceRange();
Chris Lattner96b77fc2008-04-02 06:50:17 +00001134 }
Mike Stump1eb44332009-09-09 15:08:12 +00001135
Douglas Gregorf1f9b4e2008-11-03 15:51:28 +00001136 // C++ [dcl.ref]p1:
1137 // Cv-qualified references are ill-formed except when the
1138 // cv-qualifiers are introduced through the use of a typedef
1139 // (7.1.3) or of a template type argument (14.3), in which
1140 // case the cv-qualifiers are ignored.
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00001141 // FIXME: Shouldn't we be checking SCS_typedef here?
1142 if (DS.getTypeSpecType() == DeclSpec::TST_typename &&
Douglas Gregorf1f9b4e2008-11-03 15:51:28 +00001143 TypeQuals && Result->isReferenceType()) {
John McCall0953e762009-09-24 19:53:00 +00001144 TypeQuals &= ~DeclSpec::TQ_const;
1145 TypeQuals &= ~DeclSpec::TQ_volatile;
Mike Stump1eb44332009-09-09 15:08:12 +00001146 }
1147
Eli Friedmanbc1029b2012-04-05 22:47:34 +00001148 // C90 6.5.3 constraints: "The same type qualifier shall not appear more
1149 // than once in the same specifier-list or qualifier-list, either directly
1150 // or via one or more typedefs."
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001151 if (!S.getLangOpts().C99 && !S.getLangOpts().CPlusPlus
Eli Friedmanbc1029b2012-04-05 22:47:34 +00001152 && TypeQuals & Result.getCVRQualifiers()) {
1153 if (TypeQuals & DeclSpec::TQ_const && Result.isConstQualified()) {
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001154 S.Diag(DS.getConstSpecLoc(), diag::ext_duplicate_declspec)
Eli Friedmanbc1029b2012-04-05 22:47:34 +00001155 << "const";
1156 }
1157
1158 if (TypeQuals & DeclSpec::TQ_volatile && Result.isVolatileQualified()) {
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001159 S.Diag(DS.getVolatileSpecLoc(), diag::ext_duplicate_declspec)
Eli Friedmanbc1029b2012-04-05 22:47:34 +00001160 << "volatile";
1161 }
1162
1163 // C90 doesn't have restrict, so it doesn't force us to produce a warning
1164 // in this case.
1165 }
1166
John McCall0953e762009-09-24 19:53:00 +00001167 Qualifiers Quals = Qualifiers::fromCVRMask(TypeQuals);
1168 Result = Context.getQualifiedType(Result, Quals);
Chris Lattner96b77fc2008-04-02 06:50:17 +00001169 }
John McCall0953e762009-09-24 19:53:00 +00001170
Chris Lattnerf1d705c2008-02-21 01:07:18 +00001171 return Result;
1172}
1173
Douglas Gregorcd281c32009-02-28 00:25:32 +00001174static std::string getPrintableNameForEntity(DeclarationName Entity) {
1175 if (Entity)
1176 return Entity.getAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00001177
Douglas Gregorcd281c32009-02-28 00:25:32 +00001178 return "type name";
1179}
1180
John McCall28654742010-06-05 06:41:15 +00001181QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1182 Qualifiers Qs) {
1183 // Enforce C99 6.7.3p2: "Types other than pointer types derived from
1184 // object or incomplete types shall not be restrict-qualified."
1185 if (Qs.hasRestrict()) {
1186 unsigned DiagID = 0;
1187 QualType ProblemTy;
1188
1189 const Type *Ty = T->getCanonicalTypeInternal().getTypePtr();
1190 if (const ReferenceType *RTy = dyn_cast<ReferenceType>(Ty)) {
1191 if (!RTy->getPointeeType()->isIncompleteOrObjectType()) {
1192 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1193 ProblemTy = T->getAs<ReferenceType>()->getPointeeType();
1194 }
1195 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
1196 if (!PTy->getPointeeType()->isIncompleteOrObjectType()) {
1197 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1198 ProblemTy = T->getAs<PointerType>()->getPointeeType();
1199 }
1200 } else if (const MemberPointerType *PTy = dyn_cast<MemberPointerType>(Ty)) {
1201 if (!PTy->getPointeeType()->isIncompleteOrObjectType()) {
1202 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1203 ProblemTy = T->getAs<PointerType>()->getPointeeType();
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001204 }
John McCall28654742010-06-05 06:41:15 +00001205 } else if (!Ty->isDependentType()) {
1206 // FIXME: this deserves a proper diagnostic
1207 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1208 ProblemTy = T;
1209 }
1210
1211 if (DiagID) {
1212 Diag(Loc, DiagID) << ProblemTy;
1213 Qs.removeRestrict();
1214 }
1215 }
1216
1217 return Context.getQualifiedType(T, Qs);
1218}
1219
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001220/// \brief Build a paren type including \p T.
1221QualType Sema::BuildParenType(QualType T) {
1222 return Context.getParenType(T);
1223}
1224
John McCallf85e1932011-06-15 23:02:42 +00001225/// Given that we're building a pointer or reference to the given
1226static QualType inferARCLifetimeForPointee(Sema &S, QualType type,
1227 SourceLocation loc,
1228 bool isReference) {
1229 // Bail out if retention is unrequired or already specified.
1230 if (!type->isObjCLifetimeType() ||
1231 type.getObjCLifetime() != Qualifiers::OCL_None)
1232 return type;
1233
1234 Qualifiers::ObjCLifetime implicitLifetime = Qualifiers::OCL_None;
1235
1236 // If the object type is const-qualified, we can safely use
1237 // __unsafe_unretained. This is safe (because there are no read
1238 // barriers), and it'll be safe to coerce anything but __weak* to
1239 // the resulting type.
1240 if (type.isConstQualified()) {
1241 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1242
1243 // Otherwise, check whether the static type does not require
1244 // retaining. This currently only triggers for Class (possibly
1245 // protocol-qualifed, and arrays thereof).
1246 } else if (type->isObjCARCImplicitlyUnretainedType()) {
1247 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1248
Eli Friedmanef331b72012-01-20 01:26:23 +00001249 // If we are in an unevaluated context, like sizeof, skip adding a
1250 // qualification.
David Blaikie71f55f72012-08-06 22:47:24 +00001251 } else if (S.isUnevaluatedContext()) {
Eli Friedmanef331b72012-01-20 01:26:23 +00001252 return type;
Argyrios Kyrtzidis5b76f372011-09-20 23:49:22 +00001253
John McCalle8c904f2012-01-26 20:04:03 +00001254 // If that failed, give an error and recover using __strong. __strong
1255 // is the option most likely to prevent spurious second-order diagnostics,
1256 // like when binding a reference to a field.
John McCallf85e1932011-06-15 23:02:42 +00001257 } else {
1258 // These types can show up in private ivars in system headers, so
1259 // we need this to not be an error in those cases. Instead we
1260 // want to delay.
1261 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
Eli Friedmanef331b72012-01-20 01:26:23 +00001262 S.DelayedDiagnostics.add(
1263 sema::DelayedDiagnostic::makeForbiddenType(loc,
1264 diag::err_arc_indirect_no_ownership, type, isReference));
John McCallf85e1932011-06-15 23:02:42 +00001265 } else {
Eli Friedmanef331b72012-01-20 01:26:23 +00001266 S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference;
John McCallf85e1932011-06-15 23:02:42 +00001267 }
John McCalle8c904f2012-01-26 20:04:03 +00001268 implicitLifetime = Qualifiers::OCL_Strong;
John McCallf85e1932011-06-15 23:02:42 +00001269 }
1270 assert(implicitLifetime && "didn't infer any lifetime!");
1271
1272 Qualifiers qs;
1273 qs.addObjCLifetime(implicitLifetime);
1274 return S.Context.getQualifiedType(type, qs);
1275}
1276
Douglas Gregorcd281c32009-02-28 00:25:32 +00001277/// \brief Build a pointer type.
1278///
1279/// \param T The type to which we'll be building a pointer.
1280///
Douglas Gregorcd281c32009-02-28 00:25:32 +00001281/// \param Loc The location of the entity whose type involves this
1282/// pointer type or, if there is no such entity, the location of the
1283/// type that will have pointer type.
1284///
1285/// \param Entity The name of the entity that involves the pointer
1286/// type, if known.
1287///
1288/// \returns A suitable pointer type, if there are no
1289/// errors. Otherwise, returns a NULL type.
John McCall28654742010-06-05 06:41:15 +00001290QualType Sema::BuildPointerType(QualType T,
Douglas Gregorcd281c32009-02-28 00:25:32 +00001291 SourceLocation Loc, DeclarationName Entity) {
1292 if (T->isReferenceType()) {
1293 // C++ 8.3.2p4: There shall be no ... pointers to references ...
1294 Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
John McCallac406052009-10-30 00:37:20 +00001295 << getPrintableNameForEntity(Entity) << T;
Douglas Gregorcd281c32009-02-28 00:25:32 +00001296 return QualType();
1297 }
1298
John McCallc12c5bb2010-05-15 11:32:37 +00001299 assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType");
Douglas Gregor92e986e2010-04-22 16:44:27 +00001300
John McCallf85e1932011-06-15 23:02:42 +00001301 // In ARC, it is forbidden to build pointers to unqualified pointers.
David Blaikie4e4d0842012-03-11 07:00:24 +00001302 if (getLangOpts().ObjCAutoRefCount)
John McCallf85e1932011-06-15 23:02:42 +00001303 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false);
1304
Douglas Gregorcd281c32009-02-28 00:25:32 +00001305 // Build the pointer type.
John McCall28654742010-06-05 06:41:15 +00001306 return Context.getPointerType(T);
Douglas Gregorcd281c32009-02-28 00:25:32 +00001307}
1308
1309/// \brief Build a reference type.
1310///
1311/// \param T The type to which we'll be building a reference.
1312///
Douglas Gregorcd281c32009-02-28 00:25:32 +00001313/// \param Loc The location of the entity whose type involves this
1314/// reference type or, if there is no such entity, the location of the
1315/// type that will have reference type.
1316///
1317/// \param Entity The name of the entity that involves the reference
1318/// type, if known.
1319///
1320/// \returns A suitable reference type, if there are no
1321/// errors. Otherwise, returns a NULL type.
John McCall54e14c42009-10-22 22:37:11 +00001322QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue,
John McCall28654742010-06-05 06:41:15 +00001323 SourceLocation Loc,
John McCall54e14c42009-10-22 22:37:11 +00001324 DeclarationName Entity) {
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001325 assert(Context.getCanonicalType(T) != Context.OverloadTy &&
Douglas Gregor9625e442011-05-21 22:16:50 +00001326 "Unresolved overloaded function type");
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001327
Douglas Gregor69d83162011-01-20 16:08:06 +00001328 // C++0x [dcl.ref]p6:
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001329 // If a typedef (7.1.3), a type template-parameter (14.3.1), or a
1330 // decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a
1331 // type T, an attempt to create the type "lvalue reference to cv TR" creates
1332 // the type "lvalue reference to T", while an attempt to create the type
Douglas Gregor69d83162011-01-20 16:08:06 +00001333 // "rvalue reference to cv TR" creates the type TR.
John McCall54e14c42009-10-22 22:37:11 +00001334 bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
1335
John McCall54e14c42009-10-22 22:37:11 +00001336 // C++ [dcl.ref]p4: There shall be no references to references.
1337 //
1338 // According to C++ DR 106, references to references are only
1339 // diagnosed when they are written directly (e.g., "int & &"),
1340 // but not when they happen via a typedef:
1341 //
1342 // typedef int& intref;
1343 // typedef intref& intref2;
1344 //
1345 // Parser::ParseDeclaratorInternal diagnoses the case where
1346 // references are written directly; here, we handle the
Douglas Gregor69d83162011-01-20 16:08:06 +00001347 // collapsing of references-to-references as described in C++0x.
1348 // DR 106 and 540 introduce reference-collapsing into C++98/03.
Douglas Gregorcd281c32009-02-28 00:25:32 +00001349
1350 // C++ [dcl.ref]p1:
Eli Friedman33a31382009-08-05 19:21:58 +00001351 // A declarator that specifies the type "reference to cv void"
Douglas Gregorcd281c32009-02-28 00:25:32 +00001352 // is ill-formed.
1353 if (T->isVoidType()) {
1354 Diag(Loc, diag::err_reference_to_void);
1355 return QualType();
1356 }
1357
John McCallf85e1932011-06-15 23:02:42 +00001358 // In ARC, it is forbidden to build references to unqualified pointers.
David Blaikie4e4d0842012-03-11 07:00:24 +00001359 if (getLangOpts().ObjCAutoRefCount)
John McCallf85e1932011-06-15 23:02:42 +00001360 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true);
1361
Douglas Gregorcd281c32009-02-28 00:25:32 +00001362 // Handle restrict on references.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001363 if (LValueRef)
John McCall28654742010-06-05 06:41:15 +00001364 return Context.getLValueReferenceType(T, SpelledAsLValue);
1365 return Context.getRValueReferenceType(T);
Douglas Gregorcd281c32009-02-28 00:25:32 +00001366}
1367
Chris Lattnere1eed382011-06-14 06:38:10 +00001368/// Check whether the specified array size makes the array type a VLA. If so,
1369/// return true, if not, return the size of the array in SizeVal.
Richard Smith282e7e62012-02-04 09:53:13 +00001370static bool isArraySizeVLA(Sema &S, Expr *ArraySize, llvm::APSInt &SizeVal) {
1371 // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode
1372 // (like gnu99, but not c99) accept any evaluatable value as an extension.
Douglas Gregorab41fe92012-05-04 22:38:52 +00001373 class VLADiagnoser : public Sema::VerifyICEDiagnoser {
1374 public:
1375 VLADiagnoser() : Sema::VerifyICEDiagnoser(true) {}
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001376
Douglas Gregorab41fe92012-05-04 22:38:52 +00001377 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
1378 }
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001379
Douglas Gregorab41fe92012-05-04 22:38:52 +00001380 virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR) {
1381 S.Diag(Loc, diag::ext_vla_folded_to_constant) << SR;
1382 }
1383 } Diagnoser;
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001384
Douglas Gregorab41fe92012-05-04 22:38:52 +00001385 return S.VerifyIntegerConstantExpression(ArraySize, &SizeVal, Diagnoser,
1386 S.LangOpts.GNUMode).isInvalid();
Chris Lattnere1eed382011-06-14 06:38:10 +00001387}
1388
1389
Douglas Gregorcd281c32009-02-28 00:25:32 +00001390/// \brief Build an array type.
1391///
1392/// \param T The type of each element in the array.
1393///
1394/// \param ASM C99 array size modifier (e.g., '*', 'static').
Mike Stump1eb44332009-09-09 15:08:12 +00001395///
1396/// \param ArraySize Expression describing the size of the array.
Douglas Gregorcd281c32009-02-28 00:25:32 +00001397///
James Dennettefce31f2012-06-22 08:10:18 +00001398/// \param Brackets The range from the opening '[' to the closing ']'.
Douglas Gregorcd281c32009-02-28 00:25:32 +00001399///
1400/// \param Entity The name of the entity that involves the array
1401/// type, if known.
1402///
1403/// \returns A suitable array type, if there are no errors. Otherwise,
1404/// returns a NULL type.
1405QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1406 Expr *ArraySize, unsigned Quals,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001407 SourceRange Brackets, DeclarationName Entity) {
John McCall0953e762009-09-24 19:53:00 +00001408
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001409 SourceLocation Loc = Brackets.getBegin();
David Blaikie4e4d0842012-03-11 07:00:24 +00001410 if (getLangOpts().CPlusPlus) {
Douglas Gregor138bb232010-04-27 19:38:14 +00001411 // C++ [dcl.array]p1:
1412 // T is called the array element type; this type shall not be a reference
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001413 // type, the (possibly cv-qualified) type void, a function type or an
Douglas Gregor138bb232010-04-27 19:38:14 +00001414 // abstract class type.
1415 //
Richard Smithbb351512012-07-07 23:00:31 +00001416 // C++ [dcl.array]p3:
1417 // When several "array of" specifications are adjacent, [...] only the
1418 // first of the constant expressions that specify the bounds of the arrays
1419 // may be omitted.
1420 //
Douglas Gregor138bb232010-04-27 19:38:14 +00001421 // Note: function types are handled in the common path with C.
1422 if (T->isReferenceType()) {
1423 Diag(Loc, diag::err_illegal_decl_array_of_references)
1424 << getPrintableNameForEntity(Entity) << T;
1425 return QualType();
1426 }
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001427
Richard Smithbb351512012-07-07 23:00:31 +00001428 if (T->isVoidType() || T->isIncompleteArrayType()) {
Sebastian Redl923d56d2009-11-05 15:52:31 +00001429 Diag(Loc, diag::err_illegal_decl_array_incomplete_type) << T;
1430 return QualType();
1431 }
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001432
1433 if (RequireNonAbstractType(Brackets.getBegin(), T,
Douglas Gregor138bb232010-04-27 19:38:14 +00001434 diag::err_array_of_abstract_type))
1435 return QualType();
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001436
Sebastian Redl923d56d2009-11-05 15:52:31 +00001437 } else {
Douglas Gregor138bb232010-04-27 19:38:14 +00001438 // C99 6.7.5.2p1: If the element type is an incomplete or function type,
1439 // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
Sebastian Redl923d56d2009-11-05 15:52:31 +00001440 if (RequireCompleteType(Loc, T,
1441 diag::err_illegal_decl_array_incomplete_type))
1442 return QualType();
1443 }
Douglas Gregorcd281c32009-02-28 00:25:32 +00001444
1445 if (T->isFunctionType()) {
1446 Diag(Loc, diag::err_illegal_decl_array_of_functions)
John McCallac406052009-10-30 00:37:20 +00001447 << getPrintableNameForEntity(Entity) << T;
Douglas Gregorcd281c32009-02-28 00:25:32 +00001448 return QualType();
1449 }
Mike Stump1eb44332009-09-09 15:08:12 +00001450
Richard Smith34b41d92011-02-20 03:19:35 +00001451 if (T->getContainedAutoType()) {
1452 Diag(Loc, diag::err_illegal_decl_array_of_auto)
1453 << getPrintableNameForEntity(Entity) << T;
Anders Carlssone7cf07d2009-06-26 19:33:28 +00001454 return QualType();
1455 }
Mike Stump1eb44332009-09-09 15:08:12 +00001456
Ted Kremenek6217b802009-07-29 21:53:49 +00001457 if (const RecordType *EltTy = T->getAs<RecordType>()) {
Douglas Gregorcd281c32009-02-28 00:25:32 +00001458 // If the element type is a struct or union that contains a variadic
1459 // array, accept it as a GNU extension: C99 6.7.2.1p2.
1460 if (EltTy->getDecl()->hasFlexibleArrayMember())
1461 Diag(Loc, diag::ext_flexible_array_in_array) << T;
John McCallc12c5bb2010-05-15 11:32:37 +00001462 } else if (T->isObjCObjectType()) {
Chris Lattnerc7c11b12009-04-27 01:55:56 +00001463 Diag(Loc, diag::err_objc_array_of_interfaces) << T;
1464 return QualType();
Douglas Gregorcd281c32009-02-28 00:25:32 +00001465 }
Mike Stump1eb44332009-09-09 15:08:12 +00001466
John McCall806054d2012-01-11 00:14:46 +00001467 // Do placeholder conversions on the array size expression.
1468 if (ArraySize && ArraySize->hasPlaceholderType()) {
1469 ExprResult Result = CheckPlaceholderExpr(ArraySize);
1470 if (Result.isInvalid()) return QualType();
1471 ArraySize = Result.take();
1472 }
1473
John McCall5e3c67b2010-12-15 04:42:30 +00001474 // Do lvalue-to-rvalue conversions on the array size expression.
John Wiegley429bb272011-04-08 18:41:53 +00001475 if (ArraySize && !ArraySize->isRValue()) {
1476 ExprResult Result = DefaultLvalueConversion(ArraySize);
1477 if (Result.isInvalid())
1478 return QualType();
1479
1480 ArraySize = Result.take();
1481 }
John McCall5e3c67b2010-12-15 04:42:30 +00001482
Douglas Gregorcd281c32009-02-28 00:25:32 +00001483 // C99 6.7.5.2p1: The size expression shall have integer type.
Richard Smith282e7e62012-02-04 09:53:13 +00001484 // C++11 allows contextual conversions to such types.
Richard Smith80ad52f2013-01-02 11:42:31 +00001485 if (!getLangOpts().CPlusPlus11 &&
Richard Smith282e7e62012-02-04 09:53:13 +00001486 ArraySize && !ArraySize->isTypeDependent() &&
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001487 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
Douglas Gregorcd281c32009-02-28 00:25:32 +00001488 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
1489 << ArraySize->getType() << ArraySize->getSourceRange();
Douglas Gregorcd281c32009-02-28 00:25:32 +00001490 return QualType();
1491 }
Richard Smith282e7e62012-02-04 09:53:13 +00001492
Douglas Gregor2767ce22010-08-18 00:39:00 +00001493 llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType()));
Douglas Gregorcd281c32009-02-28 00:25:32 +00001494 if (!ArraySize) {
Eli Friedmanf91f5c82009-04-26 21:57:51 +00001495 if (ASM == ArrayType::Star)
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001496 T = Context.getVariableArrayType(T, 0, ASM, Quals, Brackets);
Eli Friedmanf91f5c82009-04-26 21:57:51 +00001497 else
1498 T = Context.getIncompleteArrayType(T, ASM, Quals);
Douglas Gregorac06a0e2010-05-18 23:01:22 +00001499 } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) {
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001500 T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets);
Richard Smith282e7e62012-02-04 09:53:13 +00001501 } else if ((!T->isDependentType() && !T->isIncompleteType() &&
1502 !T->isConstantSizeType()) ||
1503 isArraySizeVLA(*this, ArraySize, ConstVal)) {
1504 // Even in C++11, don't allow contextual conversions in the array bound
1505 // of a VLA.
Richard Smith80ad52f2013-01-02 11:42:31 +00001506 if (getLangOpts().CPlusPlus11 &&
Richard Smith282e7e62012-02-04 09:53:13 +00001507 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
1508 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
1509 << ArraySize->getType() << ArraySize->getSourceRange();
1510 return QualType();
1511 }
1512
Chris Lattnere1eed382011-06-14 06:38:10 +00001513 // C99: an array with an element type that has a non-constant-size is a VLA.
Chris Lattnere1eed382011-06-14 06:38:10 +00001514 // C99: an array with a non-ICE size is a VLA. We accept any expression
1515 // that we can fold to a non-zero positive value as an extension.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001516 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
Douglas Gregorcd281c32009-02-28 00:25:32 +00001517 } else {
1518 // C99 6.7.5.2p1: If the expression is a constant expression, it shall
1519 // have a value greater than zero.
Sebastian Redl923d56d2009-11-05 15:52:31 +00001520 if (ConstVal.isSigned() && ConstVal.isNegative()) {
Chandler Carruthb2b5cc02011-01-04 04:44:35 +00001521 if (Entity)
1522 Diag(ArraySize->getLocStart(), diag::err_decl_negative_array_size)
1523 << getPrintableNameForEntity(Entity) << ArraySize->getSourceRange();
1524 else
1525 Diag(ArraySize->getLocStart(), diag::err_typecheck_negative_array_size)
1526 << ArraySize->getSourceRange();
Sebastian Redl923d56d2009-11-05 15:52:31 +00001527 return QualType();
1528 }
1529 if (ConstVal == 0) {
Douglas Gregor02024a92010-03-28 02:42:43 +00001530 // GCC accepts zero sized static arrays. We allow them when
1531 // we're not in a SFINAE context.
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001532 Diag(ArraySize->getLocStart(),
Douglas Gregor02024a92010-03-28 02:42:43 +00001533 isSFINAEContext()? diag::err_typecheck_zero_array_size
1534 : diag::ext_typecheck_zero_array_size)
Sebastian Redl923d56d2009-11-05 15:52:31 +00001535 << ArraySize->getSourceRange();
Peter Collingbourne20cdbeb2011-10-16 21:17:32 +00001536
1537 if (ASM == ArrayType::Static) {
1538 Diag(ArraySize->getLocStart(),
1539 diag::warn_typecheck_zero_static_array_size)
1540 << ArraySize->getSourceRange();
1541 ASM = ArrayType::Normal;
1542 }
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001543 } else if (!T->isDependentType() && !T->isVariablyModifiedType() &&
Douglas Gregor2767ce22010-08-18 00:39:00 +00001544 !T->isIncompleteType()) {
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001545 // Is the array too large?
Douglas Gregor2767ce22010-08-18 00:39:00 +00001546 unsigned ActiveSizeBits
1547 = ConstantArrayType::getNumAddressingBits(Context, T, ConstVal);
1548 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
1549 Diag(ArraySize->getLocStart(), diag::err_array_too_large)
1550 << ConstVal.toString(10)
1551 << ArraySize->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001552 }
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001553
John McCall46a617a2009-10-16 00:14:28 +00001554 T = Context.getConstantArrayType(T, ConstVal, ASM, Quals);
Douglas Gregorcd281c32009-02-28 00:25:32 +00001555 }
Joey Gouly617bb312013-01-17 17:35:00 +00001556
1557 // OpenCL v1.2 s6.9.d: variable length arrays are not supported.
1558 if (getLangOpts().OpenCL && T->isVariableArrayType()) {
1559 Diag(Loc, diag::err_opencl_vla);
1560 return QualType();
1561 }
David Chisnallaf407762010-01-11 23:08:08 +00001562 // If this is not C99, extwarn about VLA's and C99 array size modifiers.
David Blaikie4e4d0842012-03-11 07:00:24 +00001563 if (!getLangOpts().C99) {
Douglas Gregor0fddb972010-05-22 16:17:30 +00001564 if (T->isVariableArrayType()) {
1565 // Prohibit the use of non-POD types in VLAs.
John McCallf85e1932011-06-15 23:02:42 +00001566 QualType BaseT = Context.getBaseElementType(T);
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001567 if (!T->isDependentType() &&
Douglas Gregor3c7236e2013-01-08 00:01:45 +00001568 !BaseT.isPODType(Context) &&
1569 !BaseT->isObjCLifetimeType()) {
Douglas Gregor0fddb972010-05-22 16:17:30 +00001570 Diag(Loc, diag::err_vla_non_pod)
John McCallf85e1932011-06-15 23:02:42 +00001571 << BaseT;
Douglas Gregor0fddb972010-05-22 16:17:30 +00001572 return QualType();
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001573 }
Douglas Gregora481ec42010-05-23 19:57:01 +00001574 // Prohibit the use of VLAs during template argument deduction.
1575 else if (isSFINAEContext()) {
1576 Diag(Loc, diag::err_vla_in_sfinae);
1577 return QualType();
1578 }
Douglas Gregor0fddb972010-05-22 16:17:30 +00001579 // Just extwarn about VLAs.
1580 else
1581 Diag(Loc, diag::ext_vla);
1582 } else if (ASM != ArrayType::Normal || Quals != 0)
Richard Smithd7c56e12011-12-29 21:57:33 +00001583 Diag(Loc,
David Blaikie4e4d0842012-03-11 07:00:24 +00001584 getLangOpts().CPlusPlus? diag::err_c99_array_usage_cxx
Richard Smithd7c56e12011-12-29 21:57:33 +00001585 : diag::ext_c99_array_usage) << ASM;
Douglas Gregorcd281c32009-02-28 00:25:32 +00001586 }
1587
Dmitri Gribenko630f4bb2013-01-23 20:02:51 +00001588 if (T->isVariableArrayType()) {
1589 // Warn about VLAs for -Wvla.
1590 Diag(Loc, diag::warn_vla_used);
1591 }
1592
Douglas Gregorcd281c32009-02-28 00:25:32 +00001593 return T;
1594}
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001595
1596/// \brief Build an ext-vector type.
1597///
1598/// Run the required checks for the extended vector type.
John McCall9ae2f072010-08-23 23:25:46 +00001599QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize,
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001600 SourceLocation AttrLoc) {
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001601 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1602 // in conjunction with complex types (pointers, arrays, functions, etc.).
Mike Stump1eb44332009-09-09 15:08:12 +00001603 if (!T->isDependentType() &&
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001604 !T->isIntegerType() && !T->isRealFloatingType()) {
1605 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
1606 return QualType();
1607 }
1608
John McCall9ae2f072010-08-23 23:25:46 +00001609 if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) {
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001610 llvm::APSInt vecSize(32);
John McCall9ae2f072010-08-23 23:25:46 +00001611 if (!ArraySize->isIntegerConstantExpr(vecSize, Context)) {
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001612 Diag(AttrLoc, diag::err_attribute_argument_not_int)
John McCall9ae2f072010-08-23 23:25:46 +00001613 << "ext_vector_type" << ArraySize->getSourceRange();
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001614 return QualType();
1615 }
Mike Stump1eb44332009-09-09 15:08:12 +00001616
1617 // unlike gcc's vector_size attribute, the size is specified as the
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001618 // number of elements, not the number of bytes.
Mike Stump1eb44332009-09-09 15:08:12 +00001619 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
1620
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001621 if (vectorSize == 0) {
1622 Diag(AttrLoc, diag::err_attribute_zero_size)
John McCall9ae2f072010-08-23 23:25:46 +00001623 << ArraySize->getSourceRange();
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001624 return QualType();
1625 }
Mike Stump1eb44332009-09-09 15:08:12 +00001626
Douglas Gregor4ac01402011-06-15 16:02:29 +00001627 return Context.getExtVectorType(T, vectorSize);
Mike Stump1eb44332009-09-09 15:08:12 +00001628 }
1629
John McCall9ae2f072010-08-23 23:25:46 +00001630 return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc);
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001631}
Mike Stump1eb44332009-09-09 15:08:12 +00001632
Douglas Gregor724651c2009-02-28 01:04:19 +00001633/// \brief Build a function type.
1634///
1635/// This routine checks the function type according to C++ rules and
1636/// under the assumption that the result type and parameter types have
1637/// just been instantiated from a template. It therefore duplicates
Douglas Gregor2943aed2009-03-03 04:44:36 +00001638/// some of the behavior of GetTypeForDeclarator, but in a much
Douglas Gregor724651c2009-02-28 01:04:19 +00001639/// simpler form that is only suitable for this narrow use case.
1640///
1641/// \param T The return type of the function.
1642///
1643/// \param ParamTypes The parameter types of the function. This array
1644/// will be modified to account for adjustments to the types of the
1645/// function parameters.
1646///
1647/// \param NumParamTypes The number of parameter types in ParamTypes.
1648///
1649/// \param Variadic Whether this is a variadic function type.
1650///
Richard Smitheefb3d52012-02-10 09:58:53 +00001651/// \param HasTrailingReturn Whether this function has a trailing return type.
1652///
Douglas Gregor724651c2009-02-28 01:04:19 +00001653/// \param Quals The cvr-qualifiers to be applied to the function type.
1654///
1655/// \param Loc The location of the entity whose type involves this
1656/// function type or, if there is no such entity, the location of the
1657/// type that will have function type.
1658///
1659/// \param Entity The name of the entity that involves the function
1660/// type, if known.
1661///
1662/// \returns A suitable function type, if there are no
1663/// errors. Otherwise, returns a NULL type.
1664QualType Sema::BuildFunctionType(QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00001665 QualType *ParamTypes,
Douglas Gregor724651c2009-02-28 01:04:19 +00001666 unsigned NumParamTypes,
Richard Smitheefb3d52012-02-10 09:58:53 +00001667 bool Variadic, bool HasTrailingReturn,
1668 unsigned Quals,
Douglas Gregorc938c162011-01-26 05:01:58 +00001669 RefQualifierKind RefQualifier,
Eli Friedmanfa869542010-08-05 02:54:05 +00001670 SourceLocation Loc, DeclarationName Entity,
John McCalle23cf432010-12-14 08:05:40 +00001671 FunctionType::ExtInfo Info) {
Douglas Gregor724651c2009-02-28 01:04:19 +00001672 if (T->isArrayType() || T->isFunctionType()) {
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001673 Diag(Loc, diag::err_func_returning_array_function)
Douglas Gregor58408bc2010-01-11 18:46:21 +00001674 << T->isFunctionType() << T;
Douglas Gregor724651c2009-02-28 01:04:19 +00001675 return QualType();
1676 }
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001677
1678 // Functions cannot return half FP.
1679 if (T->isHalfType()) {
1680 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 <<
1681 FixItHint::CreateInsertion(Loc, "*");
1682 return QualType();
1683 }
1684
Douglas Gregor724651c2009-02-28 01:04:19 +00001685 bool Invalid = false;
1686 for (unsigned Idx = 0; Idx < NumParamTypes; ++Idx) {
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001687 // FIXME: Loc is too inprecise here, should use proper locations for args.
Douglas Gregor79e6bd32011-07-12 04:42:08 +00001688 QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001689 if (ParamType->isVoidType()) {
Douglas Gregor724651c2009-02-28 01:04:19 +00001690 Diag(Loc, diag::err_param_with_void_type);
1691 Invalid = true;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001692 } else if (ParamType->isHalfType()) {
1693 // Disallow half FP arguments.
1694 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 <<
1695 FixItHint::CreateInsertion(Loc, "*");
1696 Invalid = true;
Douglas Gregor724651c2009-02-28 01:04:19 +00001697 }
Douglas Gregorcd281c32009-02-28 00:25:32 +00001698
John McCall54e14c42009-10-22 22:37:11 +00001699 ParamTypes[Idx] = ParamType;
Douglas Gregor724651c2009-02-28 01:04:19 +00001700 }
1701
1702 if (Invalid)
1703 return QualType();
1704
John McCalle23cf432010-12-14 08:05:40 +00001705 FunctionProtoType::ExtProtoInfo EPI;
1706 EPI.Variadic = Variadic;
Richard Smitheefb3d52012-02-10 09:58:53 +00001707 EPI.HasTrailingReturn = HasTrailingReturn;
John McCalle23cf432010-12-14 08:05:40 +00001708 EPI.TypeQuals = Quals;
Douglas Gregorc938c162011-01-26 05:01:58 +00001709 EPI.RefQualifier = RefQualifier;
John McCalle23cf432010-12-14 08:05:40 +00001710 EPI.ExtInfo = Info;
1711
1712 return Context.getFunctionType(T, ParamTypes, NumParamTypes, EPI);
Douglas Gregor724651c2009-02-28 01:04:19 +00001713}
Mike Stump1eb44332009-09-09 15:08:12 +00001714
Douglas Gregor949bf692009-06-09 22:17:39 +00001715/// \brief Build a member pointer type \c T Class::*.
1716///
1717/// \param T the type to which the member pointer refers.
1718/// \param Class the class type into which the member pointer points.
Douglas Gregor949bf692009-06-09 22:17:39 +00001719/// \param Loc the location where this type begins
1720/// \param Entity the name of the entity that will have this member pointer type
1721///
1722/// \returns a member pointer type, if successful, or a NULL type if there was
1723/// an error.
Mike Stump1eb44332009-09-09 15:08:12 +00001724QualType Sema::BuildMemberPointerType(QualType T, QualType Class,
John McCall28654742010-06-05 06:41:15 +00001725 SourceLocation Loc,
Douglas Gregor949bf692009-06-09 22:17:39 +00001726 DeclarationName Entity) {
1727 // Verify that we're not building a pointer to pointer to function with
1728 // exception specification.
1729 if (CheckDistantExceptionSpec(T)) {
1730 Diag(Loc, diag::err_distant_exception_spec);
1731
1732 // FIXME: If we're doing this as part of template instantiation,
1733 // we should return immediately.
1734
1735 // Build the type anyway, but use the canonical type so that the
1736 // exception specifiers are stripped off.
1737 T = Context.getCanonicalType(T);
1738 }
1739
Sebastian Redl73780122010-06-09 21:19:43 +00001740 // C++ 8.3.3p3: A pointer to member shall not point to ... a member
Douglas Gregor949bf692009-06-09 22:17:39 +00001741 // with reference type, or "cv void."
1742 if (T->isReferenceType()) {
Anders Carlsson8d4655d2009-06-30 00:06:57 +00001743 Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
John McCallac406052009-10-30 00:37:20 +00001744 << (Entity? Entity.getAsString() : "type name") << T;
Douglas Gregor949bf692009-06-09 22:17:39 +00001745 return QualType();
1746 }
1747
1748 if (T->isVoidType()) {
1749 Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
1750 << (Entity? Entity.getAsString() : "type name");
1751 return QualType();
1752 }
1753
Douglas Gregor949bf692009-06-09 22:17:39 +00001754 if (!Class->isDependentType() && !Class->isRecordType()) {
1755 Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
1756 return QualType();
1757 }
1758
John McCallb8b2c9d2013-01-25 22:30:49 +00001759 // C++ allows the class type in a member pointer to be an incomplete type.
1760 // In the Microsoft ABI, the size of the member pointer can vary
1761 // according to the class type, which means that we really need a
1762 // complete type if possible, which means we need to instantiate templates.
1763 //
1764 // For now, just require a complete type, which will instantiate
1765 // templates. This will also error if the type is just forward-declared,
1766 // which is a bug, but it's a bug that saves us from dealing with some
1767 // complexities at the moment.
1768 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
Joao Matos679fc932012-09-04 17:18:12 +00001769 RequireCompleteType(Loc, Class, diag::err_incomplete_type))
1770 return QualType();
1771
John McCall28654742010-06-05 06:41:15 +00001772 return Context.getMemberPointerType(T, Class.getTypePtr());
Douglas Gregor949bf692009-06-09 22:17:39 +00001773}
Mike Stump1eb44332009-09-09 15:08:12 +00001774
Anders Carlsson9a917e42009-06-12 22:56:54 +00001775/// \brief Build a block pointer type.
1776///
1777/// \param T The type to which we'll be building a block pointer.
1778///
James Dennettefce31f2012-06-22 08:10:18 +00001779/// \param Loc The source location, used for diagnostics.
Anders Carlsson9a917e42009-06-12 22:56:54 +00001780///
Anders Carlsson9a917e42009-06-12 22:56:54 +00001781/// \param Entity The name of the entity that involves the block pointer
1782/// type, if known.
1783///
1784/// \returns A suitable block pointer type, if there are no
1785/// errors. Otherwise, returns a NULL type.
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001786QualType Sema::BuildBlockPointerType(QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00001787 SourceLocation Loc,
Anders Carlsson9a917e42009-06-12 22:56:54 +00001788 DeclarationName Entity) {
John McCall0953e762009-09-24 19:53:00 +00001789 if (!T->isFunctionType()) {
Anders Carlsson9a917e42009-06-12 22:56:54 +00001790 Diag(Loc, diag::err_nonfunction_block_type);
1791 return QualType();
1792 }
Mike Stump1eb44332009-09-09 15:08:12 +00001793
John McCall28654742010-06-05 06:41:15 +00001794 return Context.getBlockPointerType(T);
Anders Carlsson9a917e42009-06-12 22:56:54 +00001795}
1796
John McCallb3d87482010-08-24 05:47:05 +00001797QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) {
1798 QualType QT = Ty.get();
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001799 if (QT.isNull()) {
John McCalla93c9342009-12-07 02:54:59 +00001800 if (TInfo) *TInfo = 0;
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001801 return QualType();
1802 }
1803
John McCalla93c9342009-12-07 02:54:59 +00001804 TypeSourceInfo *DI = 0;
John McCallf4c73712011-01-19 06:33:43 +00001805 if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001806 QT = LIT->getType();
John McCalla93c9342009-12-07 02:54:59 +00001807 DI = LIT->getTypeSourceInfo();
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001808 }
Mike Stump1eb44332009-09-09 15:08:12 +00001809
John McCalla93c9342009-12-07 02:54:59 +00001810 if (TInfo) *TInfo = DI;
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001811 return QT;
1812}
1813
Argyrios Kyrtzidisa8349f52011-07-01 22:23:05 +00001814static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
1815 Qualifiers::ObjCLifetime ownership,
1816 unsigned chunkIndex);
1817
John McCallf85e1932011-06-15 23:02:42 +00001818/// Given that this is the declaration of a parameter under ARC,
1819/// attempt to infer attributes and such for pointer-to-whatever
1820/// types.
1821static void inferARCWriteback(TypeProcessingState &state,
1822 QualType &declSpecType) {
1823 Sema &S = state.getSema();
1824 Declarator &declarator = state.getDeclarator();
1825
1826 // TODO: should we care about decl qualifiers?
1827
1828 // Check whether the declarator has the expected form. We walk
1829 // from the inside out in order to make the block logic work.
1830 unsigned outermostPointerIndex = 0;
1831 bool isBlockPointer = false;
1832 unsigned numPointers = 0;
1833 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
1834 unsigned chunkIndex = i;
1835 DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex);
1836 switch (chunk.Kind) {
1837 case DeclaratorChunk::Paren:
1838 // Ignore parens.
1839 break;
1840
1841 case DeclaratorChunk::Reference:
1842 case DeclaratorChunk::Pointer:
1843 // Count the number of pointers. Treat references
1844 // interchangeably as pointers; if they're mis-ordered, normal
1845 // type building will discover that.
1846 outermostPointerIndex = chunkIndex;
1847 numPointers++;
1848 break;
1849
1850 case DeclaratorChunk::BlockPointer:
1851 // If we have a pointer to block pointer, that's an acceptable
1852 // indirect reference; anything else is not an application of
1853 // the rules.
1854 if (numPointers != 1) return;
1855 numPointers++;
1856 outermostPointerIndex = chunkIndex;
1857 isBlockPointer = true;
1858
1859 // We don't care about pointer structure in return values here.
1860 goto done;
1861
1862 case DeclaratorChunk::Array: // suppress if written (id[])?
1863 case DeclaratorChunk::Function:
1864 case DeclaratorChunk::MemberPointer:
1865 return;
1866 }
1867 }
1868 done:
1869
1870 // If we have *one* pointer, then we want to throw the qualifier on
1871 // the declaration-specifiers, which means that it needs to be a
1872 // retainable object type.
1873 if (numPointers == 1) {
1874 // If it's not a retainable object type, the rule doesn't apply.
1875 if (!declSpecType->isObjCRetainableType()) return;
1876
1877 // If it already has lifetime, don't do anything.
1878 if (declSpecType.getObjCLifetime()) return;
1879
1880 // Otherwise, modify the type in-place.
1881 Qualifiers qs;
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001882
John McCallf85e1932011-06-15 23:02:42 +00001883 if (declSpecType->isObjCARCImplicitlyUnretainedType())
1884 qs.addObjCLifetime(Qualifiers::OCL_ExplicitNone);
1885 else
1886 qs.addObjCLifetime(Qualifiers::OCL_Autoreleasing);
1887 declSpecType = S.Context.getQualifiedType(declSpecType, qs);
1888
1889 // If we have *two* pointers, then we want to throw the qualifier on
1890 // the outermost pointer.
1891 } else if (numPointers == 2) {
1892 // If we don't have a block pointer, we need to check whether the
1893 // declaration-specifiers gave us something that will turn into a
1894 // retainable object pointer after we slap the first pointer on it.
1895 if (!isBlockPointer && !declSpecType->isObjCObjectType())
1896 return;
1897
1898 // Look for an explicit lifetime attribute there.
1899 DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex);
Argyrios Kyrtzidis1c73dcb2011-07-01 22:23:03 +00001900 if (chunk.Kind != DeclaratorChunk::Pointer &&
1901 chunk.Kind != DeclaratorChunk::BlockPointer)
1902 return;
John McCallf85e1932011-06-15 23:02:42 +00001903 for (const AttributeList *attr = chunk.getAttrs(); attr;
1904 attr = attr->getNext())
Sean Hunt8e083e72012-06-19 23:57:03 +00001905 if (attr->getKind() == AttributeList::AT_ObjCOwnership)
John McCallf85e1932011-06-15 23:02:42 +00001906 return;
1907
Argyrios Kyrtzidisa8349f52011-07-01 22:23:05 +00001908 transferARCOwnershipToDeclaratorChunk(state, Qualifiers::OCL_Autoreleasing,
1909 outermostPointerIndex);
John McCallf85e1932011-06-15 23:02:42 +00001910
1911 // Any other number of pointers/references does not trigger the rule.
1912 } else return;
1913
1914 // TODO: mark whether we did this inference?
1915}
1916
Chandler Carruthd067c072011-02-23 18:51:59 +00001917static void DiagnoseIgnoredQualifiers(unsigned Quals,
1918 SourceLocation ConstQualLoc,
1919 SourceLocation VolatileQualLoc,
1920 SourceLocation RestrictQualLoc,
1921 Sema& S) {
1922 std::string QualStr;
1923 unsigned NumQuals = 0;
1924 SourceLocation Loc;
1925
1926 FixItHint ConstFixIt;
1927 FixItHint VolatileFixIt;
1928 FixItHint RestrictFixIt;
1929
Hans Wennborga08fcb82011-06-03 17:37:26 +00001930 const SourceManager &SM = S.getSourceManager();
1931
Chandler Carruthd067c072011-02-23 18:51:59 +00001932 // FIXME: The locations here are set kind of arbitrarily. It'd be nicer to
1933 // find a range and grow it to encompass all the qualifiers, regardless of
1934 // the order in which they textually appear.
1935 if (Quals & Qualifiers::Const) {
1936 ConstFixIt = FixItHint::CreateRemoval(ConstQualLoc);
Chandler Carruthd067c072011-02-23 18:51:59 +00001937 QualStr = "const";
Hans Wennborga08fcb82011-06-03 17:37:26 +00001938 ++NumQuals;
1939 if (!Loc.isValid() || SM.isBeforeInTranslationUnit(ConstQualLoc, Loc))
1940 Loc = ConstQualLoc;
Chandler Carruthd067c072011-02-23 18:51:59 +00001941 }
1942 if (Quals & Qualifiers::Volatile) {
1943 VolatileFixIt = FixItHint::CreateRemoval(VolatileQualLoc);
Hans Wennborga08fcb82011-06-03 17:37:26 +00001944 QualStr += (NumQuals == 0 ? "volatile" : " volatile");
Chandler Carruthd067c072011-02-23 18:51:59 +00001945 ++NumQuals;
Hans Wennborga08fcb82011-06-03 17:37:26 +00001946 if (!Loc.isValid() || SM.isBeforeInTranslationUnit(VolatileQualLoc, Loc))
1947 Loc = VolatileQualLoc;
Chandler Carruthd067c072011-02-23 18:51:59 +00001948 }
1949 if (Quals & Qualifiers::Restrict) {
1950 RestrictFixIt = FixItHint::CreateRemoval(RestrictQualLoc);
Hans Wennborga08fcb82011-06-03 17:37:26 +00001951 QualStr += (NumQuals == 0 ? "restrict" : " restrict");
Chandler Carruthd067c072011-02-23 18:51:59 +00001952 ++NumQuals;
Hans Wennborga08fcb82011-06-03 17:37:26 +00001953 if (!Loc.isValid() || SM.isBeforeInTranslationUnit(RestrictQualLoc, Loc))
1954 Loc = RestrictQualLoc;
Chandler Carruthd067c072011-02-23 18:51:59 +00001955 }
1956
1957 assert(NumQuals > 0 && "No known qualifiers?");
1958
1959 S.Diag(Loc, diag::warn_qual_return_type)
Hans Wennborga08fcb82011-06-03 17:37:26 +00001960 << QualStr << NumQuals << ConstFixIt << VolatileFixIt << RestrictFixIt;
Chandler Carruthd067c072011-02-23 18:51:59 +00001961}
1962
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001963static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state,
1964 TypeSourceInfo *&ReturnTypeInfo) {
1965 Sema &SemaRef = state.getSema();
1966 Declarator &D = state.getDeclarator();
Douglas Gregor930d8b52009-01-30 22:09:00 +00001967 QualType T;
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001968 ReturnTypeInfo = 0;
1969
1970 // The TagDecl owned by the DeclSpec.
Argyrios Kyrtzidisd3880f82011-06-28 03:01:18 +00001971 TagDecl *OwnedTagDecl = 0;
John McCall711c52b2011-01-05 12:14:39 +00001972
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001973 switch (D.getName().getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001974 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001975 case UnqualifiedId::IK_OperatorFunctionId:
Sebastian Redl8999fe12011-03-14 18:08:30 +00001976 case UnqualifiedId::IK_Identifier:
Sean Hunt0486d742009-11-28 04:44:28 +00001977 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001978 case UnqualifiedId::IK_TemplateId:
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001979 T = ConvertDeclSpecToType(state);
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001980
Douglas Gregor591bd3c2010-02-08 22:07:33 +00001981 if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) {
Argyrios Kyrtzidisd3880f82011-06-28 03:01:18 +00001982 OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
Abramo Bagnara15987972011-03-08 22:33:38 +00001983 // Owned declaration is embedded in declarator.
Argyrios Kyrtzidisd3880f82011-06-28 03:01:18 +00001984 OwnedTagDecl->setEmbeddedInDeclarator(true);
Douglas Gregor591bd3c2010-02-08 22:07:33 +00001985 }
Douglas Gregor930d8b52009-01-30 22:09:00 +00001986 break;
1987
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001988 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00001989 case UnqualifiedId::IK_ConstructorTemplateId:
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001990 case UnqualifiedId::IK_DestructorName:
Douglas Gregor930d8b52009-01-30 22:09:00 +00001991 // Constructors and destructors don't have return types. Use
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001992 // "void" instead.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001993 T = SemaRef.Context.VoidTy;
Rafael Espindolaa78a6402012-07-31 01:54:04 +00001994 if (AttributeList *attrs = D.getDeclSpec().getAttributes().getList())
Richard Smithf7a05272013-01-14 07:53:01 +00001995 processTypeAttrs(state, T, TAL_DeclSpec, attrs);
Douglas Gregor930d8b52009-01-30 22:09:00 +00001996 break;
Douglas Gregor48026d22010-01-11 18:40:55 +00001997
1998 case UnqualifiedId::IK_ConversionFunctionId:
1999 // The result type of a conversion function is the type that it
2000 // converts to.
Chad Rosier91cbbbf2012-06-26 21:41:40 +00002001 T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId,
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002002 &ReturnTypeInfo);
Douglas Gregor48026d22010-01-11 18:40:55 +00002003 break;
Douglas Gregor930d8b52009-01-30 22:09:00 +00002004 }
Douglas Gregordab60ad2010-10-01 18:44:50 +00002005
John McCall711c52b2011-01-05 12:14:39 +00002006 if (D.getAttributes())
2007 distributeTypeAttrsFromDeclarator(state, T);
2008
Richard Smithd37b3602012-02-10 11:05:11 +00002009 // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context.
2010 // In C++11, a function declarator using 'auto' must have a trailing return
Richard Smith8110f042011-02-22 01:22:29 +00002011 // type (this is checked later) and we can skip this. In other languages
2012 // using auto, we need to check regardless.
Richard Smith34b41d92011-02-20 03:19:35 +00002013 if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto &&
Richard Smith80ad52f2013-01-02 11:42:31 +00002014 (!SemaRef.getLangOpts().CPlusPlus11 || !D.isFunctionDeclarator())) {
Anders Carlssonbaf45d32009-06-26 22:18:59 +00002015 int Error = -1;
Mike Stump1eb44332009-09-09 15:08:12 +00002016
Anders Carlssonbaf45d32009-06-26 22:18:59 +00002017 switch (D.getContext()) {
2018 case Declarator::KNRTypeListContext:
David Blaikieb219cfc2011-09-23 05:06:16 +00002019 llvm_unreachable("K&R type lists aren't allowed in C++");
Eli Friedmanf88c4002012-01-04 04:41:38 +00002020 case Declarator::LambdaExprContext:
2021 llvm_unreachable("Can't specify a type specifier in lambda grammar");
John McCallcdda47f2011-10-01 09:56:14 +00002022 case Declarator::ObjCParameterContext:
2023 case Declarator::ObjCResultContext:
Anders Carlssonbaf45d32009-06-26 22:18:59 +00002024 case Declarator::PrototypeContext:
2025 Error = 0; // Function prototype
2026 break;
2027 case Declarator::MemberContext:
Richard Smith7a614d82011-06-11 17:19:42 +00002028 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)
2029 break;
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002030 switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) {
David Blaikieeb2d1f12011-09-23 20:26:49 +00002031 case TTK_Enum: llvm_unreachable("unhandled tag kind");
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002032 case TTK_Struct: Error = 1; /* Struct member */ break;
2033 case TTK_Union: Error = 2; /* Union member */ break;
2034 case TTK_Class: Error = 3; /* Class member */ break;
Joao Matos6666ed42012-08-31 18:45:21 +00002035 case TTK_Interface: Error = 4; /* Interface member */ break;
Mike Stump1eb44332009-09-09 15:08:12 +00002036 }
Anders Carlssonbaf45d32009-06-26 22:18:59 +00002037 break;
2038 case Declarator::CXXCatchContext:
Argyrios Kyrtzidis17b63992011-07-01 22:22:40 +00002039 case Declarator::ObjCCatchContext:
Joao Matos6666ed42012-08-31 18:45:21 +00002040 Error = 5; // Exception declaration
Anders Carlssonbaf45d32009-06-26 22:18:59 +00002041 break;
2042 case Declarator::TemplateParamContext:
Joao Matos6666ed42012-08-31 18:45:21 +00002043 Error = 6; // Template parameter
Anders Carlssonbaf45d32009-06-26 22:18:59 +00002044 break;
2045 case Declarator::BlockLiteralContext:
Joao Matos6666ed42012-08-31 18:45:21 +00002046 Error = 7; // Block literal
Richard Smith34b41d92011-02-20 03:19:35 +00002047 break;
2048 case Declarator::TemplateTypeArgContext:
Joao Matos6666ed42012-08-31 18:45:21 +00002049 Error = 8; // Template type argument
Richard Smith34b41d92011-02-20 03:19:35 +00002050 break;
Richard Smith162e1c12011-04-15 14:24:37 +00002051 case Declarator::AliasDeclContext:
Richard Smith3e4c6c42011-05-05 21:57:07 +00002052 case Declarator::AliasTemplateContext:
Joao Matos6666ed42012-08-31 18:45:21 +00002053 Error = 10; // Type alias
Richard Smith162e1c12011-04-15 14:24:37 +00002054 break;
Richard Smith7796eb52012-03-12 08:56:40 +00002055 case Declarator::TrailingReturnContext:
Joao Matos6666ed42012-08-31 18:45:21 +00002056 Error = 11; // Function return type
Richard Smith7796eb52012-03-12 08:56:40 +00002057 break;
Richard Smith34b41d92011-02-20 03:19:35 +00002058 case Declarator::TypeNameContext:
Joao Matos6666ed42012-08-31 18:45:21 +00002059 Error = 12; // Generic
Anders Carlssonbaf45d32009-06-26 22:18:59 +00002060 break;
2061 case Declarator::FileContext:
2062 case Declarator::BlockContext:
2063 case Declarator::ForContext:
2064 case Declarator::ConditionContext:
Argyrios Kyrtzidis0b8c98f2011-06-28 03:01:23 +00002065 case Declarator::CXXNewContext:
Anders Carlssonbaf45d32009-06-26 22:18:59 +00002066 break;
2067 }
2068
Richard Smithddc83f92011-02-21 23:18:00 +00002069 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
Joao Matos6666ed42012-08-31 18:45:21 +00002070 Error = 9;
Richard Smithddc83f92011-02-21 23:18:00 +00002071
Richard Smith8110f042011-02-22 01:22:29 +00002072 // In Objective-C it is an error to use 'auto' on a function declarator.
2073 if (D.isFunctionDeclarator())
Joao Matos6666ed42012-08-31 18:45:21 +00002074 Error = 11;
Richard Smith8110f042011-02-22 01:22:29 +00002075
Richard Smithd37b3602012-02-10 11:05:11 +00002076 // C++11 [dcl.spec.auto]p2: 'auto' is always fine if the declarator
Richard Smithe7397c62011-02-22 00:36:53 +00002077 // contains a trailing return type. That is only legal at the outermost
2078 // level. Check all declarator chunks (outermost first) anyway, to give
2079 // better diagnostics.
Richard Smith80ad52f2013-01-02 11:42:31 +00002080 if (SemaRef.getLangOpts().CPlusPlus11 && Error != -1) {
Richard Smithe7397c62011-02-22 00:36:53 +00002081 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
2082 unsigned chunkIndex = e - i - 1;
2083 state.setCurrentChunkIndex(chunkIndex);
2084 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
2085 if (DeclType.Kind == DeclaratorChunk::Function) {
2086 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
Richard Smith54655be2012-06-12 01:51:59 +00002087 if (FTI.hasTrailingReturnType()) {
Richard Smithe7397c62011-02-22 00:36:53 +00002088 Error = -1;
2089 break;
2090 }
2091 }
2092 }
2093 }
2094
Anders Carlssonbaf45d32009-06-26 22:18:59 +00002095 if (Error != -1) {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002096 SemaRef.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
2097 diag::err_auto_not_allowed)
Anders Carlssonbaf45d32009-06-26 22:18:59 +00002098 << Error;
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002099 T = SemaRef.Context.IntTy;
Anders Carlssonbaf45d32009-06-26 22:18:59 +00002100 D.setInvalidType(true);
Richard Smith0aa86c02011-10-15 05:42:01 +00002101 } else
2102 SemaRef.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
2103 diag::warn_cxx98_compat_auto_type_specifier);
Anders Carlssonbaf45d32009-06-26 22:18:59 +00002104 }
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002105
David Blaikie4e4d0842012-03-11 07:00:24 +00002106 if (SemaRef.getLangOpts().CPlusPlus &&
John McCall5e1cdac2011-10-07 06:10:15 +00002107 OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002108 // Check the contexts where C++ forbids the declaration of a new class
2109 // or enumeration in a type-specifier-seq.
2110 switch (D.getContext()) {
Richard Smith7796eb52012-03-12 08:56:40 +00002111 case Declarator::TrailingReturnContext:
2112 // Class and enumeration definitions are syntactically not allowed in
2113 // trailing return types.
2114 llvm_unreachable("parser should not have allowed this");
2115 break;
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002116 case Declarator::FileContext:
2117 case Declarator::MemberContext:
2118 case Declarator::BlockContext:
2119 case Declarator::ForContext:
2120 case Declarator::BlockLiteralContext:
Eli Friedmanf88c4002012-01-04 04:41:38 +00002121 case Declarator::LambdaExprContext:
Richard Smithd37b3602012-02-10 11:05:11 +00002122 // C++11 [dcl.type]p3:
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002123 // A type-specifier-seq shall not define a class or enumeration unless
2124 // it appears in the type-id of an alias-declaration (7.1.3) that is not
2125 // the declaration of a template-declaration.
2126 case Declarator::AliasDeclContext:
2127 break;
2128 case Declarator::AliasTemplateContext:
2129 SemaRef.Diag(OwnedTagDecl->getLocation(),
2130 diag::err_type_defined_in_alias_template)
2131 << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
Enea Zaffanella601e6e82013-01-11 14:34:39 +00002132 D.setInvalidType(true);
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002133 break;
2134 case Declarator::TypeNameContext:
2135 case Declarator::TemplateParamContext:
2136 case Declarator::CXXNewContext:
2137 case Declarator::CXXCatchContext:
2138 case Declarator::ObjCCatchContext:
2139 case Declarator::TemplateTypeArgContext:
2140 SemaRef.Diag(OwnedTagDecl->getLocation(),
2141 diag::err_type_defined_in_type_specifier)
2142 << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
Enea Zaffanella601e6e82013-01-11 14:34:39 +00002143 D.setInvalidType(true);
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002144 break;
2145 case Declarator::PrototypeContext:
John McCallcdda47f2011-10-01 09:56:14 +00002146 case Declarator::ObjCParameterContext:
2147 case Declarator::ObjCResultContext:
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002148 case Declarator::KNRTypeListContext:
2149 // C++ [dcl.fct]p6:
2150 // Types shall not be defined in return or parameter types.
2151 SemaRef.Diag(OwnedTagDecl->getLocation(),
2152 diag::err_type_defined_in_param_type)
2153 << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
Enea Zaffanella601e6e82013-01-11 14:34:39 +00002154 D.setInvalidType(true);
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002155 break;
2156 case Declarator::ConditionContext:
2157 // C++ 6.4p2:
2158 // The type-specifier-seq shall not contain typedef and shall not declare
2159 // a new class or enumeration.
2160 SemaRef.Diag(OwnedTagDecl->getLocation(),
2161 diag::err_type_defined_in_condition);
Enea Zaffanella601e6e82013-01-11 14:34:39 +00002162 D.setInvalidType(true);
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002163 break;
2164 }
2165 }
2166
2167 return T;
2168}
2169
Benjamin Kramera08c2fb2012-02-24 22:19:42 +00002170static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){
Richard Smithd37b3602012-02-10 11:05:11 +00002171 std::string Quals =
2172 Qualifiers::fromCVRMask(FnTy->getTypeQuals()).getAsString();
2173
2174 switch (FnTy->getRefQualifier()) {
2175 case RQ_None:
2176 break;
2177
2178 case RQ_LValue:
2179 if (!Quals.empty())
2180 Quals += ' ';
2181 Quals += '&';
2182 break;
2183
2184 case RQ_RValue:
2185 if (!Quals.empty())
2186 Quals += ' ';
2187 Quals += "&&";
2188 break;
2189 }
2190
2191 return Quals;
2192}
2193
2194/// Check that the function type T, which has a cv-qualifier or a ref-qualifier,
2195/// can be contained within the declarator chunk DeclType, and produce an
2196/// appropriate diagnostic if not.
2197static void checkQualifiedFunction(Sema &S, QualType T,
2198 DeclaratorChunk &DeclType) {
2199 // C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6: a function type with a
2200 // cv-qualifier or a ref-qualifier can only appear at the topmost level
2201 // of a type.
2202 int DiagKind = -1;
2203 switch (DeclType.Kind) {
2204 case DeclaratorChunk::Paren:
2205 case DeclaratorChunk::MemberPointer:
2206 // These cases are permitted.
2207 return;
2208 case DeclaratorChunk::Array:
2209 case DeclaratorChunk::Function:
2210 // These cases don't allow function types at all; no need to diagnose the
2211 // qualifiers separately.
2212 return;
2213 case DeclaratorChunk::BlockPointer:
2214 DiagKind = 0;
2215 break;
2216 case DeclaratorChunk::Pointer:
2217 DiagKind = 1;
2218 break;
2219 case DeclaratorChunk::Reference:
2220 DiagKind = 2;
2221 break;
2222 }
2223
2224 assert(DiagKind != -1);
2225 S.Diag(DeclType.Loc, diag::err_compound_qualified_function_type)
2226 << DiagKind << isa<FunctionType>(T.IgnoreParens()) << T
2227 << getFunctionQualifiersAsString(T->castAs<FunctionProtoType>());
2228}
2229
Richard Smithb9c62612012-07-30 21:30:52 +00002230/// Produce an approprioate diagnostic for an ambiguity between a function
2231/// declarator and a C++ direct-initializer.
2232static void warnAboutAmbiguousFunction(Sema &S, Declarator &D,
2233 DeclaratorChunk &DeclType, QualType RT) {
2234 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
2235 assert(FTI.isAmbiguous && "no direct-initializer / function ambiguity");
2236
2237 // If the return type is void there is no ambiguity.
2238 if (RT->isVoidType())
2239 return;
2240
2241 // An initializer for a non-class type can have at most one argument.
2242 if (!RT->isRecordType() && FTI.NumArgs > 1)
2243 return;
2244
2245 // An initializer for a reference must have exactly one argument.
2246 if (RT->isReferenceType() && FTI.NumArgs != 1)
2247 return;
2248
2249 // Only warn if this declarator is declaring a function at block scope, and
2250 // doesn't have a storage class (such as 'extern') specified.
2251 if (!D.isFunctionDeclarator() ||
2252 D.getFunctionDefinitionKind() != FDK_Declaration ||
2253 !S.CurContext->isFunctionOrMethod() ||
2254 D.getDeclSpec().getStorageClassSpecAsWritten()
2255 != DeclSpec::SCS_unspecified)
2256 return;
2257
2258 // Inside a condition, a direct initializer is not permitted. We allow one to
2259 // be parsed in order to give better diagnostics in condition parsing.
2260 if (D.getContext() == Declarator::ConditionContext)
2261 return;
2262
2263 SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc);
2264
Richard Smithd64effc2012-07-30 21:42:05 +00002265 S.Diag(DeclType.Loc,
2266 FTI.NumArgs ? diag::warn_parens_disambiguated_as_function_declaration
2267 : diag::warn_empty_parens_are_function_decl)
2268 << ParenRange;
Richard Smithb9c62612012-07-30 21:30:52 +00002269
Richard Smithd64effc2012-07-30 21:42:05 +00002270 // If the declaration looks like:
2271 // T var1,
2272 // f();
2273 // and name lookup finds a function named 'f', then the ',' was
2274 // probably intended to be a ';'.
2275 if (!D.isFirstDeclarator() && D.getIdentifier()) {
2276 FullSourceLoc Comma(D.getCommaLoc(), S.SourceMgr);
2277 FullSourceLoc Name(D.getIdentifierLoc(), S.SourceMgr);
2278 if (Comma.getFileID() != Name.getFileID() ||
2279 Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) {
2280 LookupResult Result(S, D.getIdentifier(), SourceLocation(),
2281 Sema::LookupOrdinaryName);
2282 if (S.LookupName(Result, S.getCurScope()))
2283 S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call)
2284 << FixItHint::CreateReplacement(D.getCommaLoc(), ";")
2285 << D.getIdentifier();
2286 }
2287 }
2288
2289 if (FTI.NumArgs > 0) {
2290 // For a declaration with parameters, eg. "T var(T());", suggest adding parens
2291 // around the first parameter to turn the declaration into a variable
2292 // declaration.
Richard Smithb9c62612012-07-30 21:30:52 +00002293 SourceRange Range = FTI.ArgInfo[0].Param->getSourceRange();
2294 SourceLocation B = Range.getBegin();
2295 SourceLocation E = S.PP.getLocForEndOfToken(Range.getEnd());
2296 // FIXME: Maybe we should suggest adding braces instead of parens
2297 // in C++11 for classes that don't have an initializer_list constructor.
2298 S.Diag(B, diag::note_additional_parens_for_variable_declaration)
2299 << FixItHint::CreateInsertion(B, "(")
2300 << FixItHint::CreateInsertion(E, ")");
Richard Smithd64effc2012-07-30 21:42:05 +00002301 } else {
2302 // For a declaration without parameters, eg. "T var();", suggest replacing the
2303 // parens with an initializer to turn the declaration into a variable
2304 // declaration.
Richard Smithb9c62612012-07-30 21:30:52 +00002305 const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
Richard Smithd64effc2012-07-30 21:42:05 +00002306
Richard Smithb9c62612012-07-30 21:30:52 +00002307 // Empty parens mean value-initialization, and no parens mean
2308 // default initialization. These are equivalent if the default
2309 // constructor is user-provided or if zero-initialization is a
2310 // no-op.
2311 if (RD && RD->hasDefinition() &&
2312 (RD->isEmpty() || RD->hasUserProvidedDefaultConstructor()))
2313 S.Diag(DeclType.Loc, diag::note_empty_parens_default_ctor)
2314 << FixItHint::CreateRemoval(ParenRange);
2315 else {
2316 std::string Init = S.getFixItZeroInitializerForType(RT);
Richard Smith80ad52f2013-01-02 11:42:31 +00002317 if (Init.empty() && S.LangOpts.CPlusPlus11)
Richard Smithb9c62612012-07-30 21:30:52 +00002318 Init = "{}";
2319 if (!Init.empty())
2320 S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize)
2321 << FixItHint::CreateReplacement(ParenRange, Init);
2322 }
2323 }
2324}
2325
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002326static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
2327 QualType declSpecType,
2328 TypeSourceInfo *TInfo) {
2329
2330 QualType T = declSpecType;
2331 Declarator &D = state.getDeclarator();
2332 Sema &S = state.getSema();
2333 ASTContext &Context = S.Context;
David Blaikie4e4d0842012-03-11 07:00:24 +00002334 const LangOptions &LangOpts = S.getLangOpts();
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002335
Douglas Gregorcd281c32009-02-28 00:25:32 +00002336 // The name we're declaring, if any.
2337 DeclarationName Name;
2338 if (D.getIdentifier())
2339 Name = D.getIdentifier();
Mike Stump1eb44332009-09-09 15:08:12 +00002340
Richard Smith162e1c12011-04-15 14:24:37 +00002341 // Does this declaration declare a typedef-name?
2342 bool IsTypedefName =
2343 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef ||
Richard Smith3e4c6c42011-05-05 21:57:07 +00002344 D.getContext() == Declarator::AliasDeclContext ||
2345 D.getContext() == Declarator::AliasTemplateContext;
Richard Smith162e1c12011-04-15 14:24:37 +00002346
Richard Smithd37b3602012-02-10 11:05:11 +00002347 // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
2348 bool IsQualifiedFunction = T->isFunctionProtoType() &&
2349 (T->castAs<FunctionProtoType>()->getTypeQuals() != 0 ||
2350 T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None);
2351
Mike Stump98eb8a72009-02-04 22:31:32 +00002352 // Walk the DeclTypeInfo, building the recursive type as we go.
2353 // DeclTypeInfos are ordered from the identifier out, which is
2354 // opposite of what we want :).
Sebastian Redl8ce35b02009-10-25 21:45:37 +00002355 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
John McCall711c52b2011-01-05 12:14:39 +00002356 unsigned chunkIndex = e - i - 1;
2357 state.setCurrentChunkIndex(chunkIndex);
2358 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
Richard Smithd37b3602012-02-10 11:05:11 +00002359 if (IsQualifiedFunction) {
2360 checkQualifiedFunction(S, T, DeclType);
2361 IsQualifiedFunction = DeclType.Kind == DeclaratorChunk::Paren;
2362 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002363 switch (DeclType.Kind) {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002364 case DeclaratorChunk::Paren:
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002365 T = S.BuildParenType(T);
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002366 break;
Steve Naroff5618bd42008-08-27 16:04:49 +00002367 case DeclaratorChunk::BlockPointer:
Chris Lattner9af55002009-03-27 04:18:06 +00002368 // If blocks are disabled, emit an error.
2369 if (!LangOpts.Blocks)
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002370 S.Diag(DeclType.Loc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +00002371
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002372 T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name);
John McCall28654742010-06-05 06:41:15 +00002373 if (DeclType.Cls.TypeQuals)
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002374 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals);
Steve Naroff5618bd42008-08-27 16:04:49 +00002375 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002376 case DeclaratorChunk::Pointer:
Sebastian Redl6a7330c2009-05-29 15:01:05 +00002377 // Verify that we're not building a pointer to pointer to function with
2378 // exception specification.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002379 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
2380 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
Sebastian Redl6a7330c2009-05-29 15:01:05 +00002381 D.setInvalidType(true);
2382 // Build the type anyway.
2383 }
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002384 if (LangOpts.ObjC1 && T->getAs<ObjCObjectType>()) {
John McCallc12c5bb2010-05-15 11:32:37 +00002385 T = Context.getObjCObjectPointerType(T);
John McCall28654742010-06-05 06:41:15 +00002386 if (DeclType.Ptr.TypeQuals)
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002387 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
Steve Naroff14108da2009-07-10 23:34:53 +00002388 break;
2389 }
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002390 T = S.BuildPointerType(T, DeclType.Loc, Name);
John McCall28654742010-06-05 06:41:15 +00002391 if (DeclType.Ptr.TypeQuals)
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002392 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
John McCall711c52b2011-01-05 12:14:39 +00002393
Reid Spencer5f016e22007-07-11 17:01:13 +00002394 break;
John McCall0953e762009-09-24 19:53:00 +00002395 case DeclaratorChunk::Reference: {
Sebastian Redl6a7330c2009-05-29 15:01:05 +00002396 // Verify that we're not building a reference to pointer to function with
2397 // exception specification.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002398 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
2399 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
Sebastian Redl6a7330c2009-05-29 15:01:05 +00002400 D.setInvalidType(true);
2401 // Build the type anyway.
2402 }
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002403 T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name);
John McCall28654742010-06-05 06:41:15 +00002404
2405 Qualifiers Quals;
2406 if (DeclType.Ref.HasRestrict)
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002407 T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict);
Reid Spencer5f016e22007-07-11 17:01:13 +00002408 break;
John McCall0953e762009-09-24 19:53:00 +00002409 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002410 case DeclaratorChunk::Array: {
Sebastian Redl6a7330c2009-05-29 15:01:05 +00002411 // Verify that we're not building an array of pointers to function with
2412 // exception specification.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002413 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
2414 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
Sebastian Redl6a7330c2009-05-29 15:01:05 +00002415 D.setInvalidType(true);
2416 // Build the type anyway.
2417 }
Chris Lattnerfd89bc82008-04-02 01:05:10 +00002418 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
Chris Lattner94f81fd2007-08-28 16:54:00 +00002419 Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
Reid Spencer5f016e22007-07-11 17:01:13 +00002420 ArrayType::ArraySizeModifier ASM;
2421 if (ATI.isStar)
2422 ASM = ArrayType::Star;
2423 else if (ATI.hasStatic)
2424 ASM = ArrayType::Static;
2425 else
2426 ASM = ArrayType::Normal;
John McCallc05a94b2011-03-23 23:43:04 +00002427 if (ASM == ArrayType::Star && !D.isPrototypeContext()) {
Eli Friedmanf91f5c82009-04-26 21:57:51 +00002428 // FIXME: This check isn't quite right: it allows star in prototypes
2429 // for function definitions, and disallows some edge cases detailed
2430 // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002431 S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
Eli Friedmanf91f5c82009-04-26 21:57:51 +00002432 ASM = ArrayType::Normal;
2433 D.setInvalidType(true);
2434 }
Hans Wennborg7f397c52012-08-15 07:42:30 +00002435
2436 // C99 6.7.5.2p1: The optional type qualifiers and the keyword static
2437 // shall appear only in a declaration of a function parameter with an
2438 // array type, ...
2439 if (ASM == ArrayType::Static || ATI.TypeQuals) {
Matt Beaumont-Gay99570a52012-08-15 19:53:19 +00002440 if (!(D.isPrototypeContext() ||
2441 D.getContext() == Declarator::KNRTypeListContext)) {
Hans Wennborg7f397c52012-08-15 07:42:30 +00002442 S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype) <<
2443 (ASM == ArrayType::Static ? "'static'" : "type qualifier");
2444 // Remove the 'static' and the type qualifiers.
2445 if (ASM == ArrayType::Static)
2446 ASM = ArrayType::Normal;
2447 ATI.TypeQuals = 0;
2448 D.setInvalidType(true);
2449 }
2450
2451 // C99 6.7.5.2p1: ... and then only in the outermost array type
2452 // derivation.
2453 unsigned x = chunkIndex;
2454 while (x != 0) {
2455 // Walk outwards along the declarator chunks.
2456 x--;
2457 const DeclaratorChunk &DC = D.getTypeObject(x);
2458 switch (DC.Kind) {
2459 case DeclaratorChunk::Paren:
2460 continue;
2461 case DeclaratorChunk::Array:
2462 case DeclaratorChunk::Pointer:
2463 case DeclaratorChunk::Reference:
2464 case DeclaratorChunk::MemberPointer:
2465 S.Diag(DeclType.Loc, diag::err_array_static_not_outermost) <<
2466 (ASM == ArrayType::Static ? "'static'" : "type qualifier");
2467 if (ASM == ArrayType::Static)
2468 ASM = ArrayType::Normal;
2469 ATI.TypeQuals = 0;
2470 D.setInvalidType(true);
2471 break;
2472 case DeclaratorChunk::Function:
2473 case DeclaratorChunk::BlockPointer:
2474 // These are invalid anyway, so just ignore.
2475 break;
2476 }
2477 }
2478 }
2479
Eli Friedman8ac2c662011-11-11 02:00:42 +00002480 T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals,
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002481 SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
Reid Spencer5f016e22007-07-11 17:01:13 +00002482 break;
2483 }
Sebastian Redlf30208a2009-01-24 21:16:55 +00002484 case DeclaratorChunk::Function: {
Reid Spencer5f016e22007-07-11 17:01:13 +00002485 // If the function declarator has a prototype (i.e. it is not () and
2486 // does not have a K&R-style identifier list), then the arguments are part
2487 // of the type, otherwise the argument list is ().
2488 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
Richard Smithd37b3602012-02-10 11:05:11 +00002489 IsQualifiedFunction = FTI.TypeQuals || FTI.hasRefQualifier();
Sebastian Redl3cc97262009-05-31 11:47:27 +00002490
Richard Smithe7397c62011-02-22 00:36:53 +00002491 // Check for auto functions and trailing return type and adjust the
2492 // return type accordingly.
2493 if (!D.isInvalidType()) {
2494 // trailing-return-type is only required if we're declaring a function,
2495 // and not, for instance, a pointer to a function.
2496 if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto &&
Richard Smith54655be2012-06-12 01:51:59 +00002497 !FTI.hasTrailingReturnType() && chunkIndex == 0) {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002498 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
Richard Smithe7397c62011-02-22 00:36:53 +00002499 diag::err_auto_missing_trailing_return);
2500 T = Context.IntTy;
2501 D.setInvalidType(true);
Richard Smith54655be2012-06-12 01:51:59 +00002502 } else if (FTI.hasTrailingReturnType()) {
Richard Smithe7397c62011-02-22 00:36:53 +00002503 // T must be exactly 'auto' at this point. See CWG issue 681.
2504 if (isa<ParenType>(T)) {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002505 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
Richard Smithe7397c62011-02-22 00:36:53 +00002506 diag::err_trailing_return_in_parens)
2507 << T << D.getDeclSpec().getSourceRange();
2508 D.setInvalidType(true);
Eli Friedmanf88c4002012-01-04 04:41:38 +00002509 } else if (D.getContext() != Declarator::LambdaExprContext &&
2510 (T.hasQualifiers() || !isa<AutoType>(T))) {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002511 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
Richard Smithe7397c62011-02-22 00:36:53 +00002512 diag::err_trailing_return_without_auto)
2513 << T << D.getDeclSpec().getSourceRange();
2514 D.setInvalidType(true);
2515 }
Richard Smith54655be2012-06-12 01:51:59 +00002516 T = S.GetTypeFromParser(FTI.getTrailingReturnType(), &TInfo);
2517 if (T.isNull()) {
2518 // An error occurred parsing the trailing return type.
2519 T = Context.IntTy;
2520 D.setInvalidType(true);
2521 }
Richard Smithe7397c62011-02-22 00:36:53 +00002522 }
2523 }
2524
Chris Lattnercd881292007-12-19 05:31:29 +00002525 // C99 6.7.5.3p1: The return type may not be a function or array type.
Douglas Gregor58408bc2010-01-11 18:46:21 +00002526 // For conversion functions, we'll diagnose this particular error later.
Douglas Gregor48026d22010-01-11 18:40:55 +00002527 if ((T->isArrayType() || T->isFunctionType()) &&
2528 (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId)) {
Argyrios Kyrtzidis98650442011-01-25 23:16:33 +00002529 unsigned diagID = diag::err_func_returning_array_function;
Argyrios Kyrtzidisa4356ad2011-01-26 01:26:44 +00002530 // Last processing chunk in block context means this function chunk
2531 // represents the block.
2532 if (chunkIndex == 0 &&
2533 D.getContext() == Declarator::BlockLiteralContext)
Argyrios Kyrtzidis98650442011-01-25 23:16:33 +00002534 diagID = diag::err_block_returning_array_function;
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002535 S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T;
Chris Lattnercd881292007-12-19 05:31:29 +00002536 T = Context.IntTy;
2537 D.setInvalidType(true);
2538 }
Sebastian Redl465226e2009-05-27 22:11:52 +00002539
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00002540 // Do not allow returning half FP value.
2541 // FIXME: This really should be in BuildFunctionType.
2542 if (T->isHalfType()) {
Joey Gouly19dbb202013-01-23 11:56:20 +00002543 if (S.getLangOpts().OpenCL) {
2544 if (!S.getOpenCLOptions().cl_khr_fp16) {
2545 S.Diag(D.getIdentifierLoc(), diag::err_opencl_half_return) << T;
2546 D.setInvalidType(true);
2547 }
2548 } else {
2549 S.Diag(D.getIdentifierLoc(),
2550 diag::err_parameters_retval_cannot_have_fp16_type) << 1;
2551 D.setInvalidType(true);
2552 }
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00002553 }
2554
Douglas Gregor5291c3c2010-07-13 08:18:22 +00002555 // cv-qualifiers on return types are pointless except when the type is a
2556 // class type in C++.
Douglas Gregorfff95132011-03-01 17:04:42 +00002557 if (isa<PointerType>(T) && T.getLocalCVRQualifiers() &&
Rafael Espindola1e153942011-03-11 04:56:58 +00002558 (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId) &&
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002559 (!LangOpts.CPlusPlus || !T->isDependentType())) {
Chandler Carruthd067c072011-02-23 18:51:59 +00002560 assert(chunkIndex + 1 < e && "No DeclaratorChunk for the return type?");
2561 DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1);
2562 assert(ReturnTypeChunk.Kind == DeclaratorChunk::Pointer);
2563
2564 DeclaratorChunk::PointerTypeInfo &PTI = ReturnTypeChunk.Ptr;
2565
2566 DiagnoseIgnoredQualifiers(PTI.TypeQuals,
2567 SourceLocation::getFromRawEncoding(PTI.ConstQualLoc),
2568 SourceLocation::getFromRawEncoding(PTI.VolatileQualLoc),
2569 SourceLocation::getFromRawEncoding(PTI.RestrictQualLoc),
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002570 S);
Chandler Carruthd067c072011-02-23 18:51:59 +00002571
2572 } else if (T.getCVRQualifiers() && D.getDeclSpec().getTypeQualifiers() &&
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002573 (!LangOpts.CPlusPlus ||
Douglas Gregor5291c3c2010-07-13 08:18:22 +00002574 (!T->isDependentType() && !T->isRecordType()))) {
Chandler Carruthd067c072011-02-23 18:51:59 +00002575
2576 DiagnoseIgnoredQualifiers(D.getDeclSpec().getTypeQualifiers(),
2577 D.getDeclSpec().getConstSpecLoc(),
2578 D.getDeclSpec().getVolatileSpecLoc(),
2579 D.getDeclSpec().getRestrictSpecLoc(),
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002580 S);
Douglas Gregor5291c3c2010-07-13 08:18:22 +00002581 }
Chandler Carruthd067c072011-02-23 18:51:59 +00002582
Douglas Gregor02dd7982013-01-17 23:36:45 +00002583 // Objective-C ARC ownership qualifiers are ignored on the function
2584 // return type (by type canonicalization). Complain if this attribute
2585 // was written here.
2586 if (T.getQualifiers().hasObjCLifetime()) {
2587 SourceLocation AttrLoc;
2588 if (chunkIndex + 1 < D.getNumTypeObjects()) {
2589 DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1);
2590 for (const AttributeList *Attr = ReturnTypeChunk.getAttrs();
2591 Attr; Attr = Attr->getNext()) {
2592 if (Attr->getKind() == AttributeList::AT_ObjCOwnership) {
2593 AttrLoc = Attr->getLoc();
2594 break;
2595 }
2596 }
2597 }
2598 if (AttrLoc.isInvalid()) {
2599 for (const AttributeList *Attr
2600 = D.getDeclSpec().getAttributes().getList();
2601 Attr; Attr = Attr->getNext()) {
2602 if (Attr->getKind() == AttributeList::AT_ObjCOwnership) {
2603 AttrLoc = Attr->getLoc();
2604 break;
2605 }
2606 }
2607 }
2608
2609 if (AttrLoc.isValid()) {
2610 // The ownership attributes are almost always written via
2611 // the predefined
2612 // __strong/__weak/__autoreleasing/__unsafe_unretained.
2613 if (AttrLoc.isMacroID())
2614 AttrLoc = S.SourceMgr.getImmediateExpansionRange(AttrLoc).first;
2615
2616 S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type)
2617 << T.getQualifiers().getObjCLifetime();
2618 }
2619 }
2620
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002621 if (LangOpts.CPlusPlus && D.getDeclSpec().isTypeSpecOwned()) {
Douglas Gregor402abb52009-05-28 23:31:59 +00002622 // C++ [dcl.fct]p6:
2623 // Types shall not be defined in return or parameter types.
John McCallb3d87482010-08-24 05:47:05 +00002624 TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
John McCall5e1cdac2011-10-07 06:10:15 +00002625 if (Tag->isCompleteDefinition())
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002626 S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
Douglas Gregor402abb52009-05-28 23:31:59 +00002627 << Context.getTypeDeclType(Tag);
2628 }
2629
Sebastian Redl3cc97262009-05-31 11:47:27 +00002630 // Exception specs are not allowed in typedefs. Complain, but add it
2631 // anyway.
Richard Smith162e1c12011-04-15 14:24:37 +00002632 if (IsTypedefName && FTI.getExceptionSpecType())
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002633 S.Diag(FTI.getExceptionSpecLoc(), diag::err_exception_spec_in_typedef)
Richard Smith3e4c6c42011-05-05 21:57:07 +00002634 << (D.getContext() == Declarator::AliasDeclContext ||
2635 D.getContext() == Declarator::AliasTemplateContext);
Sebastian Redl3cc97262009-05-31 11:47:27 +00002636
Richard Smithb9c62612012-07-30 21:30:52 +00002637 // If we see "T var();" or "T var(T());" at block scope, it is probably
2638 // an attempt to initialize a variable, not a function declaration.
2639 if (FTI.isAmbiguous)
2640 warnAboutAmbiguousFunction(S, D, DeclType, T);
2641
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002642 if (!FTI.NumArgs && !FTI.isVariadic && !LangOpts.CPlusPlus) {
John McCall28654742010-06-05 06:41:15 +00002643 // Simple void foo(), where the incoming T is the result type.
2644 T = Context.getFunctionNoProtoType(T);
2645 } else {
2646 // We allow a zero-parameter variadic function in C if the
2647 // function is marked with the "overloadable" attribute. Scan
2648 // for this attribute now.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002649 if (!FTI.NumArgs && FTI.isVariadic && !LangOpts.CPlusPlus) {
Douglas Gregor965acbb2009-02-18 07:07:28 +00002650 bool Overloadable = false;
2651 for (const AttributeList *Attrs = D.getAttributes();
2652 Attrs; Attrs = Attrs->getNext()) {
Sean Hunt8e083e72012-06-19 23:57:03 +00002653 if (Attrs->getKind() == AttributeList::AT_Overloadable) {
Douglas Gregor965acbb2009-02-18 07:07:28 +00002654 Overloadable = true;
2655 break;
2656 }
2657 }
2658
2659 if (!Overloadable)
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002660 S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_arg);
Argyrios Kyrtzidisc6f73452008-10-16 17:31:08 +00002661 }
John McCall28654742010-06-05 06:41:15 +00002662
2663 if (FTI.NumArgs && FTI.ArgInfo[0].Param == 0) {
Chris Lattner788b0fd2010-06-23 06:00:24 +00002664 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function
2665 // definition.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002666 S.Diag(FTI.ArgInfo[0].IdentLoc, diag::err_ident_list_in_fn_declaration);
John McCall28654742010-06-05 06:41:15 +00002667 D.setInvalidType(true);
Argyrios Kyrtzidisd5668a22013-02-22 06:58:32 +00002668 // Recover by creating a K&R-style function type.
2669 T = Context.getFunctionNoProtoType(T);
John McCall28654742010-06-05 06:41:15 +00002670 break;
2671 }
2672
John McCalle23cf432010-12-14 08:05:40 +00002673 FunctionProtoType::ExtProtoInfo EPI;
2674 EPI.Variadic = FTI.isVariadic;
Richard Smith54655be2012-06-12 01:51:59 +00002675 EPI.HasTrailingReturn = FTI.hasTrailingReturnType();
John McCalle23cf432010-12-14 08:05:40 +00002676 EPI.TypeQuals = FTI.TypeQuals;
Douglas Gregorc938c162011-01-26 05:01:58 +00002677 EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None
2678 : FTI.RefQualifierIsLValueRef? RQ_LValue
2679 : RQ_RValue;
Chad Rosier91cbbbf2012-06-26 21:41:40 +00002680
Reid Spencer5f016e22007-07-11 17:01:13 +00002681 // Otherwise, we have a function with an argument list that is
2682 // potentially variadic.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002683 SmallVector<QualType, 16> ArgTys;
John McCall28654742010-06-05 06:41:15 +00002684 ArgTys.reserve(FTI.NumArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002685
Chris Lattner5f9e2722011-07-23 10:55:15 +00002686 SmallVector<bool, 16> ConsumedArguments;
John McCallf85e1932011-06-15 23:02:42 +00002687 ConsumedArguments.reserve(FTI.NumArgs);
2688 bool HasAnyConsumedArguments = false;
2689
Reid Spencer5f016e22007-07-11 17:01:13 +00002690 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
John McCalld226f652010-08-21 09:40:31 +00002691 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
Chris Lattner8123a952008-04-10 02:22:51 +00002692 QualType ArgTy = Param->getType();
Chris Lattner78c75fb2007-07-21 05:30:18 +00002693 assert(!ArgTy.isNull() && "Couldn't parse type?");
Douglas Gregor2dc0e642009-03-23 23:06:20 +00002694
2695 // Adjust the parameter type.
Chad Rosier91cbbbf2012-06-26 21:41:40 +00002696 assert((ArgTy == Context.getAdjustedParameterType(ArgTy)) &&
Douglas Gregor79e6bd32011-07-12 04:42:08 +00002697 "Unadjusted type?");
Douglas Gregor2dc0e642009-03-23 23:06:20 +00002698
Reid Spencer5f016e22007-07-11 17:01:13 +00002699 // Look for 'void'. void is allowed only as a single argument to a
2700 // function with no other parameters (C99 6.7.5.3p10). We record
Douglas Gregor72564e72009-02-26 23:50:07 +00002701 // int(void) as a FunctionProtoType with an empty argument list.
Douglas Gregor2dc0e642009-03-23 23:06:20 +00002702 if (ArgTy->isVoidType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002703 // If this is something like 'float(int, void)', reject it. 'void'
2704 // is an incomplete type (C99 6.2.5p19) and function decls cannot
2705 // have arguments of incomplete type.
2706 if (FTI.NumArgs != 1 || FTI.isVariadic) {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002707 S.Diag(DeclType.Loc, diag::err_void_only_param);
Chris Lattner2ff54262007-07-21 05:18:12 +00002708 ArgTy = Context.IntTy;
Chris Lattner8123a952008-04-10 02:22:51 +00002709 Param->setType(ArgTy);
Chris Lattner2ff54262007-07-21 05:18:12 +00002710 } else if (FTI.ArgInfo[i].Ident) {
2711 // Reject, but continue to parse 'int(void abc)'.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002712 S.Diag(FTI.ArgInfo[i].IdentLoc,
Chris Lattner4565d4e2007-07-21 05:26:43 +00002713 diag::err_param_with_void_type);
Chris Lattner2ff54262007-07-21 05:18:12 +00002714 ArgTy = Context.IntTy;
Chris Lattner8123a952008-04-10 02:22:51 +00002715 Param->setType(ArgTy);
Chris Lattner2ff54262007-07-21 05:18:12 +00002716 } else {
2717 // Reject, but continue to parse 'float(const void)'.
John McCall0953e762009-09-24 19:53:00 +00002718 if (ArgTy.hasQualifiers())
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002719 S.Diag(DeclType.Loc, diag::err_void_param_qualified);
Mike Stump1eb44332009-09-09 15:08:12 +00002720
Chris Lattner2ff54262007-07-21 05:18:12 +00002721 // Do not add 'void' to the ArgTys list.
2722 break;
2723 }
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00002724 } else if (ArgTy->isHalfType()) {
2725 // Disallow half FP arguments.
2726 // FIXME: This really should be in BuildFunctionType.
Joey Gouly19dbb202013-01-23 11:56:20 +00002727 if (S.getLangOpts().OpenCL) {
2728 if (!S.getOpenCLOptions().cl_khr_fp16) {
2729 S.Diag(Param->getLocation(),
2730 diag::err_opencl_half_argument) << ArgTy;
2731 D.setInvalidType();
John McCall9dd74c52013-02-12 01:29:43 +00002732 Param->setInvalidDecl();
Joey Gouly19dbb202013-01-23 11:56:20 +00002733 }
2734 } else {
2735 S.Diag(Param->getLocation(),
2736 diag::err_parameters_retval_cannot_have_fp16_type) << 0;
2737 D.setInvalidType();
2738 }
Eli Friedmaneb4b7052008-08-25 21:31:01 +00002739 } else if (!FTI.hasPrototype) {
2740 if (ArgTy->isPromotableIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00002741 ArgTy = Context.getPromotedIntegerType(ArgTy);
John McCalleecf5fa2011-03-09 04:22:44 +00002742 Param->setKNRPromoted(true);
John McCall183700f2009-09-21 23:43:11 +00002743 } else if (const BuiltinType* BTy = ArgTy->getAs<BuiltinType>()) {
John McCalleecf5fa2011-03-09 04:22:44 +00002744 if (BTy->getKind() == BuiltinType::Float) {
Eli Friedmaneb4b7052008-08-25 21:31:01 +00002745 ArgTy = Context.DoubleTy;
John McCalleecf5fa2011-03-09 04:22:44 +00002746 Param->setKNRPromoted(true);
2747 }
Eli Friedmaneb4b7052008-08-25 21:31:01 +00002748 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002749 }
Fariborz Jahanian56a965c2010-09-08 21:36:35 +00002750
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002751 if (LangOpts.ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00002752 bool Consumed = Param->hasAttr<NSConsumedAttr>();
2753 ConsumedArguments.push_back(Consumed);
2754 HasAnyConsumedArguments |= Consumed;
2755 }
2756
John McCall54e14c42009-10-22 22:37:11 +00002757 ArgTys.push_back(ArgTy);
Reid Spencer5f016e22007-07-11 17:01:13 +00002758 }
Sebastian Redl465226e2009-05-27 22:11:52 +00002759
John McCallf85e1932011-06-15 23:02:42 +00002760 if (HasAnyConsumedArguments)
2761 EPI.ConsumedArguments = ConsumedArguments.data();
2762
Chris Lattner5f9e2722011-07-23 10:55:15 +00002763 SmallVector<QualType, 4> Exceptions;
Douglas Gregor74e2fc32012-04-16 18:27:27 +00002764 SmallVector<ParsedType, 2> DynamicExceptions;
2765 SmallVector<SourceRange, 2> DynamicExceptionRanges;
2766 Expr *NoexceptExpr = 0;
Chad Rosier91cbbbf2012-06-26 21:41:40 +00002767
Sebastian Redl8b5b4092011-03-06 10:52:04 +00002768 if (FTI.getExceptionSpecType() == EST_Dynamic) {
Douglas Gregor74e2fc32012-04-16 18:27:27 +00002769 // FIXME: It's rather inefficient to have to split into two vectors
2770 // here.
2771 unsigned N = FTI.NumExceptions;
2772 DynamicExceptions.reserve(N);
2773 DynamicExceptionRanges.reserve(N);
2774 for (unsigned I = 0; I != N; ++I) {
2775 DynamicExceptions.push_back(FTI.Exceptions[I].Ty);
2776 DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range);
John McCalle23cf432010-12-14 08:05:40 +00002777 }
Sebastian Redl8b5b4092011-03-06 10:52:04 +00002778 } else if (FTI.getExceptionSpecType() == EST_ComputedNoexcept) {
Douglas Gregor74e2fc32012-04-16 18:27:27 +00002779 NoexceptExpr = FTI.NoexceptExpr;
2780 }
Chad Rosier91cbbbf2012-06-26 21:41:40 +00002781
Douglas Gregor74e2fc32012-04-16 18:27:27 +00002782 S.checkExceptionSpecification(FTI.getExceptionSpecType(),
2783 DynamicExceptions,
2784 DynamicExceptionRanges,
2785 NoexceptExpr,
2786 Exceptions,
2787 EPI);
Chad Rosier91cbbbf2012-06-26 21:41:40 +00002788
John McCalle23cf432010-12-14 08:05:40 +00002789 T = Context.getFunctionType(T, ArgTys.data(), ArgTys.size(), EPI);
Reid Spencer5f016e22007-07-11 17:01:13 +00002790 }
John McCall04a67a62010-02-05 21:31:56 +00002791
Reid Spencer5f016e22007-07-11 17:01:13 +00002792 break;
2793 }
Sebastian Redlf30208a2009-01-24 21:16:55 +00002794 case DeclaratorChunk::MemberPointer:
2795 // The scope spec must refer to a class, or be dependent.
Abramo Bagnara7bd06762010-08-13 12:56:25 +00002796 CXXScopeSpec &SS = DeclType.Mem.Scope();
Sebastian Redlf30208a2009-01-24 21:16:55 +00002797 QualType ClsType;
Abramo Bagnara7bd06762010-08-13 12:56:25 +00002798 if (SS.isInvalid()) {
Jeffrey Yasskinedc28772010-04-07 23:29:58 +00002799 // Avoid emitting extra errors if we already errored on the scope.
2800 D.setInvalidType(true);
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002801 } else if (S.isDependentScopeSpecifier(SS) ||
2802 dyn_cast_or_null<CXXRecordDecl>(S.computeDeclContext(SS))) {
Mike Stump1eb44332009-09-09 15:08:12 +00002803 NestedNameSpecifier *NNS
Abramo Bagnara7bd06762010-08-13 12:56:25 +00002804 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
Douglas Gregor87c12c42009-11-04 16:49:01 +00002805 NestedNameSpecifier *NNSPrefix = NNS->getPrefix();
2806 switch (NNS->getKind()) {
2807 case NestedNameSpecifier::Identifier:
Abramo Bagnara7bd06762010-08-13 12:56:25 +00002808 ClsType = Context.getDependentNameType(ETK_None, NNSPrefix,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002809 NNS->getAsIdentifier());
Douglas Gregor87c12c42009-11-04 16:49:01 +00002810 break;
2811
2812 case NestedNameSpecifier::Namespace:
Douglas Gregor14aba762011-02-24 02:36:08 +00002813 case NestedNameSpecifier::NamespaceAlias:
Douglas Gregor87c12c42009-11-04 16:49:01 +00002814 case NestedNameSpecifier::Global:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002815 llvm_unreachable("Nested-name-specifier must name a type");
Abramo Bagnara7bd06762010-08-13 12:56:25 +00002816
Douglas Gregor87c12c42009-11-04 16:49:01 +00002817 case NestedNameSpecifier::TypeSpec:
2818 case NestedNameSpecifier::TypeSpecWithTemplate:
2819 ClsType = QualType(NNS->getAsType(), 0);
Abramo Bagnara91ce2c42011-03-10 10:18:27 +00002820 // Note: if the NNS has a prefix and ClsType is a nondependent
2821 // TemplateSpecializationType, then the NNS prefix is NOT included
2822 // in ClsType; hence we wrap ClsType into an ElaboratedType.
2823 // NOTE: in particular, no wrap occurs if ClsType already is an
2824 // Elaborated, DependentName, or DependentTemplateSpecialization.
2825 if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType()))
Abramo Bagnara7bd06762010-08-13 12:56:25 +00002826 ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType);
Douglas Gregor87c12c42009-11-04 16:49:01 +00002827 break;
2828 }
Sebastian Redlf30208a2009-01-24 21:16:55 +00002829 } else {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002830 S.Diag(DeclType.Mem.Scope().getBeginLoc(),
Douglas Gregor949bf692009-06-09 22:17:39 +00002831 diag::err_illegal_decl_mempointer_in_nonclass)
2832 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
2833 << DeclType.Mem.Scope().getRange();
Sebastian Redlf30208a2009-01-24 21:16:55 +00002834 D.setInvalidType(true);
Sebastian Redlf30208a2009-01-24 21:16:55 +00002835 }
2836
Douglas Gregor949bf692009-06-09 22:17:39 +00002837 if (!ClsType.isNull())
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002838 T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc, D.getIdentifier());
Douglas Gregor949bf692009-06-09 22:17:39 +00002839 if (T.isNull()) {
2840 T = Context.IntTy;
Sebastian Redlf30208a2009-01-24 21:16:55 +00002841 D.setInvalidType(true);
John McCall28654742010-06-05 06:41:15 +00002842 } else if (DeclType.Mem.TypeQuals) {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002843 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals);
Sebastian Redlf30208a2009-01-24 21:16:55 +00002844 }
Sebastian Redlf30208a2009-01-24 21:16:55 +00002845 break;
2846 }
2847
Douglas Gregorcd281c32009-02-28 00:25:32 +00002848 if (T.isNull()) {
2849 D.setInvalidType(true);
2850 T = Context.IntTy;
2851 }
2852
Chris Lattnerc9b346d2008-06-29 00:50:08 +00002853 // See if there are any attributes on this declarator chunk.
John McCall711c52b2011-01-05 12:14:39 +00002854 if (AttributeList *attrs = const_cast<AttributeList*>(DeclType.getAttrs()))
Richard Smithf7a05272013-01-14 07:53:01 +00002855 processTypeAttrs(state, T, TAL_DeclChunk, attrs);
Reid Spencer5f016e22007-07-11 17:01:13 +00002856 }
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00002857
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002858 if (LangOpts.CPlusPlus && T->isFunctionType()) {
John McCall183700f2009-09-21 23:43:11 +00002859 const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
Chris Lattner778ed742009-10-25 17:36:50 +00002860 assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00002861
Chad Rosier91cbbbf2012-06-26 21:41:40 +00002862 // C++ 8.3.5p4:
Douglas Gregor708f3b82010-10-14 22:03:51 +00002863 // A cv-qualifier-seq shall only be part of the function type
2864 // for a nonstatic member function, the function type to which a pointer
2865 // to member refers, or the top-level function type of a function typedef
2866 // declaration.
Douglas Gregor683a81f2011-01-31 16:09:46 +00002867 //
2868 // Core issue 547 also allows cv-qualifiers on function types that are
2869 // top-level template type arguments.
John McCall613ef3d2010-10-19 01:54:45 +00002870 bool FreeFunction;
2871 if (!D.getCXXScopeSpec().isSet()) {
Eli Friedman906a7e12012-01-06 03:05:34 +00002872 FreeFunction = ((D.getContext() != Declarator::MemberContext &&
2873 D.getContext() != Declarator::LambdaExprContext) ||
John McCall613ef3d2010-10-19 01:54:45 +00002874 D.getDeclSpec().isFriendSpecified());
2875 } else {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002876 DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec());
John McCall613ef3d2010-10-19 01:54:45 +00002877 FreeFunction = (DC && !DC->isRecord());
2878 }
2879
Richard Smithd37b3602012-02-10 11:05:11 +00002880 // C++11 [dcl.fct]p6 (w/DR1417):
2881 // An attempt to specify a function type with a cv-qualifier-seq or a
2882 // ref-qualifier (including by typedef-name) is ill-formed unless it is:
2883 // - the function type for a non-static member function,
2884 // - the function type to which a pointer to member refers,
2885 // - the top-level function type of a function typedef declaration or
2886 // alias-declaration,
2887 // - the type-id in the default argument of a type-parameter, or
2888 // - the type-id of a template-argument for a type-parameter
2889 if (IsQualifiedFunction &&
2890 !(!FreeFunction &&
2891 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) &&
2892 !IsTypedefName &&
2893 D.getContext() != Declarator::TemplateTypeArgContext) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00002894 SourceLocation Loc = D.getLocStart();
Richard Smithd37b3602012-02-10 11:05:11 +00002895 SourceRange RemovalRange;
2896 unsigned I;
2897 if (D.isFunctionDeclarator(I)) {
2898 SmallVector<SourceLocation, 4> RemovalLocs;
2899 const DeclaratorChunk &Chunk = D.getTypeObject(I);
2900 assert(Chunk.Kind == DeclaratorChunk::Function);
2901 if (Chunk.Fun.hasRefQualifier())
2902 RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc());
2903 if (Chunk.Fun.TypeQuals & Qualifiers::Const)
2904 RemovalLocs.push_back(Chunk.Fun.getConstQualifierLoc());
2905 if (Chunk.Fun.TypeQuals & Qualifiers::Volatile)
2906 RemovalLocs.push_back(Chunk.Fun.getVolatileQualifierLoc());
2907 // FIXME: We do not track the location of the __restrict qualifier.
2908 //if (Chunk.Fun.TypeQuals & Qualifiers::Restrict)
2909 // RemovalLocs.push_back(Chunk.Fun.getRestrictQualifierLoc());
2910 if (!RemovalLocs.empty()) {
2911 std::sort(RemovalLocs.begin(), RemovalLocs.end(),
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +00002912 BeforeThanCompare<SourceLocation>(S.getSourceManager()));
Richard Smithd37b3602012-02-10 11:05:11 +00002913 RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back());
2914 Loc = RemovalLocs.front();
Douglas Gregorc938c162011-01-26 05:01:58 +00002915 }
2916 }
Richard Smithd37b3602012-02-10 11:05:11 +00002917
2918 S.Diag(Loc, diag::err_invalid_qualified_function_type)
2919 << FreeFunction << D.isFunctionDeclarator() << T
2920 << getFunctionQualifiersAsString(FnTy)
2921 << FixItHint::CreateRemoval(RemovalRange);
2922
2923 // Strip the cv-qualifiers and ref-qualifiers from the type.
2924 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
2925 EPI.TypeQuals = 0;
2926 EPI.RefQualifier = RQ_None;
2927
Chad Rosier91cbbbf2012-06-26 21:41:40 +00002928 T = Context.getFunctionType(FnTy->getResultType(),
Richard Smithd37b3602012-02-10 11:05:11 +00002929 FnTy->arg_type_begin(),
2930 FnTy->getNumArgs(), EPI);
Richard Smithe9253222012-10-24 23:51:56 +00002931 // Rebuild any parens around the identifier in the function type.
2932 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
2933 if (D.getTypeObject(i).Kind != DeclaratorChunk::Paren)
2934 break;
2935 T = S.BuildParenType(T);
2936 }
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00002937 }
2938 }
Mike Stump1eb44332009-09-09 15:08:12 +00002939
John McCall711c52b2011-01-05 12:14:39 +00002940 // Apply any undistributed attributes from the declarator.
2941 if (!T.isNull())
2942 if (AttributeList *attrs = D.getAttributes())
Richard Smithf7a05272013-01-14 07:53:01 +00002943 processTypeAttrs(state, T, TAL_DeclName, attrs);
John McCall711c52b2011-01-05 12:14:39 +00002944
2945 // Diagnose any ignored type attributes.
2946 if (!T.isNull()) state.diagnoseIgnoredTypeAttrs(T);
2947
Peter Collingbourne148f1f72011-03-20 08:06:45 +00002948 // C++0x [dcl.constexpr]p9:
2949 // A constexpr specifier used in an object declaration declares the object
Chad Rosier91cbbbf2012-06-26 21:41:40 +00002950 // as const.
Peter Collingbourne148f1f72011-03-20 08:06:45 +00002951 if (D.getDeclSpec().isConstexprSpecified() && T->isObjectType()) {
Sebastian Redl73780122010-06-09 21:19:43 +00002952 T.addConst();
2953 }
2954
Chad Rosier91cbbbf2012-06-26 21:41:40 +00002955 // If there was an ellipsis in the declarator, the declaration declares a
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002956 // parameter pack whose type may be a pack expansion type.
2957 if (D.hasEllipsis() && !T.isNull()) {
2958 // C++0x [dcl.fct]p13:
Chad Rosier91cbbbf2012-06-26 21:41:40 +00002959 // A declarator-id or abstract-declarator containing an ellipsis shall
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002960 // only be used in a parameter-declaration. Such a parameter-declaration
2961 // is a parameter pack (14.5.3). [...]
2962 switch (D.getContext()) {
2963 case Declarator::PrototypeContext:
2964 // C++0x [dcl.fct]p13:
Chad Rosier91cbbbf2012-06-26 21:41:40 +00002965 // [...] When it is part of a parameter-declaration-clause, the
2966 // parameter pack is a function parameter pack (14.5.3). The type T
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002967 // of the declarator-id of the function parameter pack shall contain
Chad Rosier91cbbbf2012-06-26 21:41:40 +00002968 // a template parameter pack; each template parameter pack in T is
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002969 // expanded by the function parameter pack.
2970 //
2971 // We represent function parameter packs as function parameters whose
2972 // type is a pack expansion.
2973 if (!T->containsUnexpandedParameterPack()) {
Chad Rosier91cbbbf2012-06-26 21:41:40 +00002974 S.Diag(D.getEllipsisLoc(),
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002975 diag::err_function_parameter_pack_without_parameter_packs)
2976 << T << D.getSourceRange();
2977 D.setEllipsisLoc(SourceLocation());
2978 } else {
David Blaikie66874fb2013-02-21 01:47:18 +00002979 T = Context.getPackExpansionType(T, None);
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002980 }
2981 break;
Chad Rosier91cbbbf2012-06-26 21:41:40 +00002982
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002983 case Declarator::TemplateParamContext:
2984 // C++0x [temp.param]p15:
Chad Rosier91cbbbf2012-06-26 21:41:40 +00002985 // If a template-parameter is a [...] is a parameter-declaration that
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002986 // declares a parameter pack (8.3.5), then the template-parameter is a
2987 // template parameter pack (14.5.3).
2988 //
2989 // Note: core issue 778 clarifies that, if there are any unexpanded
2990 // parameter packs in the type of the non-type template parameter, then
2991 // it expands those parameter packs.
2992 if (T->containsUnexpandedParameterPack())
David Blaikie66874fb2013-02-21 01:47:18 +00002993 T = Context.getPackExpansionType(T, None);
Richard Smithe5acd132011-10-14 20:31:37 +00002994 else
2995 S.Diag(D.getEllipsisLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +00002996 LangOpts.CPlusPlus11
Richard Smithe5acd132011-10-14 20:31:37 +00002997 ? diag::warn_cxx98_compat_variadic_templates
2998 : diag::ext_variadic_templates);
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002999 break;
Chad Rosier91cbbbf2012-06-26 21:41:40 +00003000
Douglas Gregora8bc8c92010-12-23 22:44:42 +00003001 case Declarator::FileContext:
3002 case Declarator::KNRTypeListContext:
John McCallcdda47f2011-10-01 09:56:14 +00003003 case Declarator::ObjCParameterContext: // FIXME: special diagnostic here?
3004 case Declarator::ObjCResultContext: // FIXME: special diagnostic here?
Douglas Gregora8bc8c92010-12-23 22:44:42 +00003005 case Declarator::TypeNameContext:
Argyrios Kyrtzidis0b8c98f2011-06-28 03:01:23 +00003006 case Declarator::CXXNewContext:
Richard Smith162e1c12011-04-15 14:24:37 +00003007 case Declarator::AliasDeclContext:
Richard Smith3e4c6c42011-05-05 21:57:07 +00003008 case Declarator::AliasTemplateContext:
Douglas Gregora8bc8c92010-12-23 22:44:42 +00003009 case Declarator::MemberContext:
3010 case Declarator::BlockContext:
3011 case Declarator::ForContext:
3012 case Declarator::ConditionContext:
3013 case Declarator::CXXCatchContext:
Argyrios Kyrtzidis17b63992011-07-01 22:22:40 +00003014 case Declarator::ObjCCatchContext:
Douglas Gregora8bc8c92010-12-23 22:44:42 +00003015 case Declarator::BlockLiteralContext:
Eli Friedmanf88c4002012-01-04 04:41:38 +00003016 case Declarator::LambdaExprContext:
Richard Smith7796eb52012-03-12 08:56:40 +00003017 case Declarator::TrailingReturnContext:
Douglas Gregor683a81f2011-01-31 16:09:46 +00003018 case Declarator::TemplateTypeArgContext:
Douglas Gregora8bc8c92010-12-23 22:44:42 +00003019 // FIXME: We may want to allow parameter packs in block-literal contexts
3020 // in the future.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00003021 S.Diag(D.getEllipsisLoc(), diag::err_ellipsis_in_declarator_not_parameter);
Douglas Gregora8bc8c92010-12-23 22:44:42 +00003022 D.setEllipsisLoc(SourceLocation());
3023 break;
3024 }
3025 }
Richard Smithe7397c62011-02-22 00:36:53 +00003026
John McCallbf1a0282010-06-04 23:28:52 +00003027 if (T.isNull())
3028 return Context.getNullTypeSourceInfo();
3029 else if (D.isInvalidType())
3030 return Context.getTrivialTypeSourceInfo(T);
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +00003031
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00003032 return S.GetTypeSourceInfoForDeclarator(D, T, TInfo);
3033}
3034
3035/// GetTypeForDeclarator - Convert the type for the specified
3036/// declarator to Type instances.
3037///
3038/// The result of this call will never be null, but the associated
3039/// type may be a null type if there's an unrecoverable error.
3040TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) {
3041 // Determine the type of the declarator. Not all forms of declarator
3042 // have a type.
3043
3044 TypeProcessingState state(*this, D);
3045
3046 TypeSourceInfo *ReturnTypeInfo = 0;
3047 QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
3048 if (T.isNull())
3049 return Context.getNullTypeSourceInfo();
3050
David Blaikie4e4d0842012-03-11 07:00:24 +00003051 if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount)
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00003052 inferARCWriteback(state, T);
Chad Rosier91cbbbf2012-06-26 21:41:40 +00003053
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00003054 return GetFullTypeForDeclarator(state, T, ReturnTypeInfo);
Reid Spencer5f016e22007-07-11 17:01:13 +00003055}
3056
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00003057static void transferARCOwnershipToDeclSpec(Sema &S,
3058 QualType &declSpecTy,
3059 Qualifiers::ObjCLifetime ownership) {
3060 if (declSpecTy->isObjCRetainableType() &&
3061 declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) {
3062 Qualifiers qs;
3063 qs.addObjCLifetime(ownership);
3064 declSpecTy = S.Context.getQualifiedType(declSpecTy, qs);
3065 }
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00003066}
3067
3068static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
3069 Qualifiers::ObjCLifetime ownership,
3070 unsigned chunkIndex) {
3071 Sema &S = state.getSema();
3072 Declarator &D = state.getDeclarator();
3073
3074 // Look for an explicit lifetime attribute.
3075 DeclaratorChunk &chunk = D.getTypeObject(chunkIndex);
3076 for (const AttributeList *attr = chunk.getAttrs(); attr;
3077 attr = attr->getNext())
Sean Hunt8e083e72012-06-19 23:57:03 +00003078 if (attr->getKind() == AttributeList::AT_ObjCOwnership)
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00003079 return;
3080
3081 const char *attrStr = 0;
3082 switch (ownership) {
David Blaikie30263482012-01-20 21:50:17 +00003083 case Qualifiers::OCL_None: llvm_unreachable("no ownership!");
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00003084 case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break;
3085 case Qualifiers::OCL_Strong: attrStr = "strong"; break;
3086 case Qualifiers::OCL_Weak: attrStr = "weak"; break;
3087 case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break;
3088 }
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00003089
3090 // If there wasn't one, add one (with an invalid source location
3091 // so that we don't make an AttributedType for it).
3092 AttributeList *attr = D.getAttributePool()
3093 .create(&S.Context.Idents.get("objc_ownership"), SourceLocation(),
3094 /*scope*/ 0, SourceLocation(),
3095 &S.Context.Idents.get(attrStr), SourceLocation(),
Sean Hunt93f95f22012-06-18 16:13:52 +00003096 /*args*/ 0, 0, AttributeList::AS_GNU);
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00003097 spliceAttrIntoList(*attr, chunk.getAttrListRef());
3098
3099 // TODO: mark whether we did this inference?
3100}
3101
Benjamin Kramer48d798c2012-06-02 10:20:41 +00003102/// \brief Used for transferring ownership in casts resulting in l-values.
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00003103static void transferARCOwnership(TypeProcessingState &state,
3104 QualType &declSpecTy,
3105 Qualifiers::ObjCLifetime ownership) {
3106 Sema &S = state.getSema();
3107 Declarator &D = state.getDeclarator();
3108
3109 int inner = -1;
Argyrios Kyrtzidis6ee54922011-10-28 22:54:28 +00003110 bool hasIndirection = false;
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00003111 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
3112 DeclaratorChunk &chunk = D.getTypeObject(i);
3113 switch (chunk.Kind) {
3114 case DeclaratorChunk::Paren:
3115 // Ignore parens.
3116 break;
3117
3118 case DeclaratorChunk::Array:
3119 case DeclaratorChunk::Reference:
3120 case DeclaratorChunk::Pointer:
Argyrios Kyrtzidis6ee54922011-10-28 22:54:28 +00003121 if (inner != -1)
3122 hasIndirection = true;
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00003123 inner = i;
3124 break;
3125
3126 case DeclaratorChunk::BlockPointer:
Argyrios Kyrtzidis6ee54922011-10-28 22:54:28 +00003127 if (inner != -1)
3128 transferARCOwnershipToDeclaratorChunk(state, ownership, i);
3129 return;
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00003130
3131 case DeclaratorChunk::Function:
3132 case DeclaratorChunk::MemberPointer:
3133 return;
3134 }
3135 }
3136
3137 if (inner == -1)
Argyrios Kyrtzidis6ee54922011-10-28 22:54:28 +00003138 return;
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00003139
Chad Rosier91cbbbf2012-06-26 21:41:40 +00003140 DeclaratorChunk &chunk = D.getTypeObject(inner);
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00003141 if (chunk.Kind == DeclaratorChunk::Pointer) {
3142 if (declSpecTy->isObjCRetainableType())
3143 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
Argyrios Kyrtzidis6ee54922011-10-28 22:54:28 +00003144 if (declSpecTy->isObjCObjectType() && hasIndirection)
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00003145 return transferARCOwnershipToDeclaratorChunk(state, ownership, inner);
3146 } else {
3147 assert(chunk.Kind == DeclaratorChunk::Array ||
3148 chunk.Kind == DeclaratorChunk::Reference);
3149 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
3150 }
3151}
3152
3153TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) {
3154 TypeProcessingState state(*this, D);
3155
3156 TypeSourceInfo *ReturnTypeInfo = 0;
3157 QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
3158 if (declSpecTy.isNull())
3159 return Context.getNullTypeSourceInfo();
3160
David Blaikie4e4d0842012-03-11 07:00:24 +00003161 if (getLangOpts().ObjCAutoRefCount) {
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00003162 Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy);
3163 if (ownership != Qualifiers::OCL_None)
3164 transferARCOwnership(state, declSpecTy, ownership);
3165 }
3166
3167 return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo);
3168}
3169
John McCall14aa2172011-03-04 04:00:19 +00003170/// Map an AttributedType::Kind to an AttributeList::Kind.
3171static AttributeList::Kind getAttrListKind(AttributedType::Kind kind) {
3172 switch (kind) {
3173 case AttributedType::attr_address_space:
Sean Hunt8e083e72012-06-19 23:57:03 +00003174 return AttributeList::AT_AddressSpace;
John McCall14aa2172011-03-04 04:00:19 +00003175 case AttributedType::attr_regparm:
Sean Hunt8e083e72012-06-19 23:57:03 +00003176 return AttributeList::AT_Regparm;
John McCall14aa2172011-03-04 04:00:19 +00003177 case AttributedType::attr_vector_size:
Sean Hunt8e083e72012-06-19 23:57:03 +00003178 return AttributeList::AT_VectorSize;
John McCall14aa2172011-03-04 04:00:19 +00003179 case AttributedType::attr_neon_vector_type:
Sean Hunt8e083e72012-06-19 23:57:03 +00003180 return AttributeList::AT_NeonVectorType;
John McCall14aa2172011-03-04 04:00:19 +00003181 case AttributedType::attr_neon_polyvector_type:
Sean Hunt8e083e72012-06-19 23:57:03 +00003182 return AttributeList::AT_NeonPolyVectorType;
John McCall14aa2172011-03-04 04:00:19 +00003183 case AttributedType::attr_objc_gc:
Sean Hunt8e083e72012-06-19 23:57:03 +00003184 return AttributeList::AT_ObjCGC;
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00003185 case AttributedType::attr_objc_ownership:
Sean Hunt8e083e72012-06-19 23:57:03 +00003186 return AttributeList::AT_ObjCOwnership;
John McCall14aa2172011-03-04 04:00:19 +00003187 case AttributedType::attr_noreturn:
Sean Hunt8e083e72012-06-19 23:57:03 +00003188 return AttributeList::AT_NoReturn;
John McCall14aa2172011-03-04 04:00:19 +00003189 case AttributedType::attr_cdecl:
Sean Hunt8e083e72012-06-19 23:57:03 +00003190 return AttributeList::AT_CDecl;
John McCall14aa2172011-03-04 04:00:19 +00003191 case AttributedType::attr_fastcall:
Sean Hunt8e083e72012-06-19 23:57:03 +00003192 return AttributeList::AT_FastCall;
John McCall14aa2172011-03-04 04:00:19 +00003193 case AttributedType::attr_stdcall:
Sean Hunt8e083e72012-06-19 23:57:03 +00003194 return AttributeList::AT_StdCall;
John McCall14aa2172011-03-04 04:00:19 +00003195 case AttributedType::attr_thiscall:
Sean Hunt8e083e72012-06-19 23:57:03 +00003196 return AttributeList::AT_ThisCall;
John McCall14aa2172011-03-04 04:00:19 +00003197 case AttributedType::attr_pascal:
Sean Hunt8e083e72012-06-19 23:57:03 +00003198 return AttributeList::AT_Pascal;
Anton Korobeynikov414d8962011-04-14 20:06:49 +00003199 case AttributedType::attr_pcs:
Sean Hunt8e083e72012-06-19 23:57:03 +00003200 return AttributeList::AT_Pcs;
Derek Schuff263366f2012-10-16 22:30:41 +00003201 case AttributedType::attr_pnaclcall:
3202 return AttributeList::AT_PnaclCall;
Guy Benyei38980082012-12-25 08:53:55 +00003203 case AttributedType::attr_inteloclbicc:
3204 return AttributeList::AT_IntelOclBicc;
John McCall14aa2172011-03-04 04:00:19 +00003205 }
3206 llvm_unreachable("unexpected attribute kind!");
John McCall14aa2172011-03-04 04:00:19 +00003207}
3208
3209static void fillAttributedTypeLoc(AttributedTypeLoc TL,
3210 const AttributeList *attrs) {
3211 AttributedType::Kind kind = TL.getAttrKind();
3212
3213 assert(attrs && "no type attributes in the expected location!");
3214 AttributeList::Kind parsedKind = getAttrListKind(kind);
3215 while (attrs->getKind() != parsedKind) {
3216 attrs = attrs->getNext();
3217 assert(attrs && "no matching attribute in expected location!");
3218 }
3219
3220 TL.setAttrNameLoc(attrs->getLoc());
3221 if (TL.hasAttrExprOperand())
3222 TL.setAttrExprOperand(attrs->getArg(0));
3223 else if (TL.hasAttrEnumOperand())
3224 TL.setAttrEnumOperandLoc(attrs->getParameterLoc());
3225
3226 // FIXME: preserve this information to here.
3227 if (TL.hasAttrOperand())
3228 TL.setAttrOperandParensRange(SourceRange());
3229}
3230
John McCall51bd8032009-10-18 01:05:36 +00003231namespace {
3232 class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
Douglas Gregorc21c7e92011-01-25 19:13:18 +00003233 ASTContext &Context;
John McCall51bd8032009-10-18 01:05:36 +00003234 const DeclSpec &DS;
Argyrios Kyrtzidisf352bdd2009-09-29 19:43:35 +00003235
John McCall51bd8032009-10-18 01:05:36 +00003236 public:
Chad Rosier91cbbbf2012-06-26 21:41:40 +00003237 TypeSpecLocFiller(ASTContext &Context, const DeclSpec &DS)
Douglas Gregorc21c7e92011-01-25 19:13:18 +00003238 : Context(Context), DS(DS) {}
Argyrios Kyrtzidisf352bdd2009-09-29 19:43:35 +00003239
John McCall14aa2172011-03-04 04:00:19 +00003240 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
3241 fillAttributedTypeLoc(TL, DS.getAttributes().getList());
3242 Visit(TL.getModifiedLoc());
3243 }
John McCall51bd8032009-10-18 01:05:36 +00003244 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
3245 Visit(TL.getUnqualifiedLoc());
3246 }
3247 void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
3248 TL.setNameLoc(DS.getTypeSpecTypeLoc());
3249 }
3250 void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
3251 TL.setNameLoc(DS.getTypeSpecTypeLoc());
Fariborz Jahanian1de6a6c2012-05-09 21:49:29 +00003252 // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires
3253 // addition field. What we have is good enough for dispay of location
3254 // of 'fixit' on interface name.
3255 TL.setNameEndLoc(DS.getLocEnd());
John McCallc12c5bb2010-05-15 11:32:37 +00003256 }
3257 void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
3258 // Handle the base type, which might not have been written explicitly.
3259 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
3260 TL.setHasBaseTypeAsWritten(false);
Douglas Gregorc21c7e92011-01-25 19:13:18 +00003261 TL.getBaseLoc().initialize(Context, SourceLocation());
John McCallc12c5bb2010-05-15 11:32:37 +00003262 } else {
3263 TL.setHasBaseTypeAsWritten(true);
3264 Visit(TL.getBaseLoc());
3265 }
Argyrios Kyrtzidiseb667592009-09-29 19:45:22 +00003266
John McCallc12c5bb2010-05-15 11:32:37 +00003267 // Protocol qualifiers.
John McCall54e14c42009-10-22 22:37:11 +00003268 if (DS.getProtocolQualifiers()) {
3269 assert(TL.getNumProtocols() > 0);
3270 assert(TL.getNumProtocols() == DS.getNumProtocolQualifiers());
3271 TL.setLAngleLoc(DS.getProtocolLAngleLoc());
3272 TL.setRAngleLoc(DS.getSourceRange().getEnd());
3273 for (unsigned i = 0, e = DS.getNumProtocolQualifiers(); i != e; ++i)
3274 TL.setProtocolLoc(i, DS.getProtocolLocs()[i]);
3275 } else {
3276 assert(TL.getNumProtocols() == 0);
3277 TL.setLAngleLoc(SourceLocation());
3278 TL.setRAngleLoc(SourceLocation());
3279 }
3280 }
3281 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCall54e14c42009-10-22 22:37:11 +00003282 TL.setStarLoc(SourceLocation());
John McCallc12c5bb2010-05-15 11:32:37 +00003283 Visit(TL.getPointeeLoc());
John McCall51bd8032009-10-18 01:05:36 +00003284 }
John McCall833ca992009-10-29 08:12:44 +00003285 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
John McCalla93c9342009-12-07 02:54:59 +00003286 TypeSourceInfo *TInfo = 0;
John McCallb3d87482010-08-24 05:47:05 +00003287 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
John McCall833ca992009-10-29 08:12:44 +00003288
3289 // If we got no declarator info from previous Sema routines,
3290 // just fill with the typespec loc.
John McCalla93c9342009-12-07 02:54:59 +00003291 if (!TInfo) {
Abramo Bagnara0daaf322011-03-16 20:16:18 +00003292 TL.initialize(Context, DS.getTypeSpecTypeNameLoc());
John McCall833ca992009-10-29 08:12:44 +00003293 return;
3294 }
3295
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00003296 TypeLoc OldTL = TInfo->getTypeLoc();
3297 if (TInfo->getType()->getAs<ElaboratedType>()) {
David Blaikie39e6ab42013-02-18 22:06:02 +00003298 ElaboratedTypeLoc ElabTL = OldTL.castAs<ElaboratedTypeLoc>();
3299 TemplateSpecializationTypeLoc NamedTL = ElabTL.getNamedTypeLoc()
3300 .castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00003301 TL.copy(NamedTL);
3302 }
3303 else
David Blaikie39e6ab42013-02-18 22:06:02 +00003304 TL.copy(OldTL.castAs<TemplateSpecializationTypeLoc>());
John McCall833ca992009-10-29 08:12:44 +00003305 }
John McCallcfb708c2010-01-13 20:03:27 +00003306 void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
3307 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr);
3308 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
3309 TL.setParensRange(DS.getTypeofParensRange());
3310 }
3311 void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
3312 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType);
3313 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
3314 TL.setParensRange(DS.getTypeofParensRange());
John McCallb3d87482010-08-24 05:47:05 +00003315 assert(DS.getRepAsType());
John McCallcfb708c2010-01-13 20:03:27 +00003316 TypeSourceInfo *TInfo = 0;
John McCallb3d87482010-08-24 05:47:05 +00003317 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
John McCallcfb708c2010-01-13 20:03:27 +00003318 TL.setUnderlyingTInfo(TInfo);
3319 }
Sean Huntca63c202011-05-24 22:41:36 +00003320 void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
3321 // FIXME: This holds only because we only have one unary transform.
3322 assert(DS.getTypeSpecType() == DeclSpec::TST_underlyingType);
3323 TL.setKWLoc(DS.getTypeSpecTypeLoc());
3324 TL.setParensRange(DS.getTypeofParensRange());
3325 assert(DS.getRepAsType());
3326 TypeSourceInfo *TInfo = 0;
3327 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
3328 TL.setUnderlyingTInfo(TInfo);
3329 }
Douglas Gregorddf889a2010-01-18 18:04:31 +00003330 void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
3331 // By default, use the source location of the type specifier.
3332 TL.setBuiltinLoc(DS.getTypeSpecTypeLoc());
3333 if (TL.needsExtraLocalData()) {
3334 // Set info for the written builtin specifiers.
3335 TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs();
3336 // Try to have a meaningful source location.
3337 if (TL.getWrittenSignSpec() != TSS_unspecified)
3338 // Sign spec loc overrides the others (e.g., 'unsigned long').
3339 TL.setBuiltinLoc(DS.getTypeSpecSignLoc());
3340 else if (TL.getWrittenWidthSpec() != TSW_unspecified)
3341 // Width spec loc overrides type spec loc (e.g., 'short int').
3342 TL.setBuiltinLoc(DS.getTypeSpecWidthLoc());
3343 }
3344 }
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00003345 void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
3346 ElaboratedTypeKeyword Keyword
3347 = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
Nico Weber253e80b2010-11-22 10:30:56 +00003348 if (DS.getTypeSpecType() == TST_typename) {
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00003349 TypeSourceInfo *TInfo = 0;
John McCallb3d87482010-08-24 05:47:05 +00003350 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00003351 if (TInfo) {
David Blaikie39e6ab42013-02-18 22:06:02 +00003352 TL.copy(TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>());
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00003353 return;
3354 }
3355 }
Abramo Bagnara38a42912012-02-06 19:09:27 +00003356 TL.setElaboratedKeywordLoc(Keyword != ETK_None
3357 ? DS.getTypeSpecTypeLoc()
3358 : SourceLocation());
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00003359 const CXXScopeSpec& SS = DS.getTypeSpecScope();
Douglas Gregor9e876872011-03-01 18:12:44 +00003360 TL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00003361 Visit(TL.getNextTypeLoc().getUnqualifiedLoc());
3362 }
3363 void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
Abramo Bagnara66581d42012-02-06 22:45:07 +00003364 assert(DS.getTypeSpecType() == TST_typename);
3365 TypeSourceInfo *TInfo = 0;
3366 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
3367 assert(TInfo);
David Blaikie39e6ab42013-02-18 22:06:02 +00003368 TL.copy(TInfo->getTypeLoc().castAs<DependentNameTypeLoc>());
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00003369 }
John McCall33500952010-06-11 00:33:02 +00003370 void VisitDependentTemplateSpecializationTypeLoc(
3371 DependentTemplateSpecializationTypeLoc TL) {
Abramo Bagnara66581d42012-02-06 22:45:07 +00003372 assert(DS.getTypeSpecType() == TST_typename);
3373 TypeSourceInfo *TInfo = 0;
3374 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
3375 assert(TInfo);
David Blaikie39e6ab42013-02-18 22:06:02 +00003376 TL.copy(
3377 TInfo->getTypeLoc().castAs<DependentTemplateSpecializationTypeLoc>());
Abramo Bagnara0daaf322011-03-16 20:16:18 +00003378 }
3379 void VisitTagTypeLoc(TagTypeLoc TL) {
3380 TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
John McCall33500952010-06-11 00:33:02 +00003381 }
Eli Friedmanb001de72011-10-06 23:00:33 +00003382 void VisitAtomicTypeLoc(AtomicTypeLoc TL) {
3383 TL.setKWLoc(DS.getTypeSpecTypeLoc());
3384 TL.setParensRange(DS.getTypeofParensRange());
Chad Rosier91cbbbf2012-06-26 21:41:40 +00003385
Douglas Gregor43fe2452011-10-09 18:45:17 +00003386 TypeSourceInfo *TInfo = 0;
3387 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
Jordan Rose41f3f3a2013-03-05 01:27:54 +00003388 assert(TInfo);
Douglas Gregor43fe2452011-10-09 18:45:17 +00003389 TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
Eli Friedmanb001de72011-10-06 23:00:33 +00003390 }
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00003391
John McCall51bd8032009-10-18 01:05:36 +00003392 void VisitTypeLoc(TypeLoc TL) {
3393 // FIXME: add other typespec types and change this to an assert.
Douglas Gregorc21c7e92011-01-25 19:13:18 +00003394 TL.initialize(Context, DS.getTypeSpecTypeLoc());
John McCall51bd8032009-10-18 01:05:36 +00003395 }
3396 };
Argyrios Kyrtzidisf352bdd2009-09-29 19:43:35 +00003397
John McCall51bd8032009-10-18 01:05:36 +00003398 class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
Abramo Bagnarab6ab6c12011-03-05 14:42:21 +00003399 ASTContext &Context;
John McCall51bd8032009-10-18 01:05:36 +00003400 const DeclaratorChunk &Chunk;
3401
3402 public:
Abramo Bagnarab6ab6c12011-03-05 14:42:21 +00003403 DeclaratorLocFiller(ASTContext &Context, const DeclaratorChunk &Chunk)
3404 : Context(Context), Chunk(Chunk) {}
John McCall51bd8032009-10-18 01:05:36 +00003405
3406 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00003407 llvm_unreachable("qualified type locs not expected here!");
John McCall51bd8032009-10-18 01:05:36 +00003408 }
3409
John McCallf85e1932011-06-15 23:02:42 +00003410 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
3411 fillAttributedTypeLoc(TL, Chunk.getAttrs());
3412 }
John McCall51bd8032009-10-18 01:05:36 +00003413 void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
3414 assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
3415 TL.setCaretLoc(Chunk.Loc);
3416 }
3417 void VisitPointerTypeLoc(PointerTypeLoc TL) {
3418 assert(Chunk.Kind == DeclaratorChunk::Pointer);
3419 TL.setStarLoc(Chunk.Loc);
3420 }
3421 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
3422 assert(Chunk.Kind == DeclaratorChunk::Pointer);
3423 TL.setStarLoc(Chunk.Loc);
3424 }
3425 void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
3426 assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
Abramo Bagnarab6ab6c12011-03-05 14:42:21 +00003427 const CXXScopeSpec& SS = Chunk.Mem.Scope();
3428 NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context);
3429
3430 const Type* ClsTy = TL.getClass();
3431 QualType ClsQT = QualType(ClsTy, 0);
3432 TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0);
3433 // Now copy source location info into the type loc component.
3434 TypeLoc ClsTL = ClsTInfo->getTypeLoc();
3435 switch (NNSLoc.getNestedNameSpecifier()->getKind()) {
3436 case NestedNameSpecifier::Identifier:
3437 assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc");
3438 {
David Blaikie39e6ab42013-02-18 22:06:02 +00003439 DependentNameTypeLoc DNTLoc = ClsTL.castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +00003440 DNTLoc.setElaboratedKeywordLoc(SourceLocation());
Abramo Bagnarab6ab6c12011-03-05 14:42:21 +00003441 DNTLoc.setQualifierLoc(NNSLoc.getPrefix());
3442 DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc());
3443 }
3444 break;
3445
3446 case NestedNameSpecifier::TypeSpec:
3447 case NestedNameSpecifier::TypeSpecWithTemplate:
3448 if (isa<ElaboratedType>(ClsTy)) {
David Blaikie39e6ab42013-02-18 22:06:02 +00003449 ElaboratedTypeLoc ETLoc = ClsTL.castAs<ElaboratedTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +00003450 ETLoc.setElaboratedKeywordLoc(SourceLocation());
Abramo Bagnarab6ab6c12011-03-05 14:42:21 +00003451 ETLoc.setQualifierLoc(NNSLoc.getPrefix());
3452 TypeLoc NamedTL = ETLoc.getNamedTypeLoc();
3453 NamedTL.initializeFullCopy(NNSLoc.getTypeLoc());
3454 } else {
3455 ClsTL.initializeFullCopy(NNSLoc.getTypeLoc());
3456 }
3457 break;
3458
3459 case NestedNameSpecifier::Namespace:
3460 case NestedNameSpecifier::NamespaceAlias:
3461 case NestedNameSpecifier::Global:
3462 llvm_unreachable("Nested-name-specifier must name a type");
Abramo Bagnarab6ab6c12011-03-05 14:42:21 +00003463 }
3464
3465 // Finally fill in MemberPointerLocInfo fields.
John McCall51bd8032009-10-18 01:05:36 +00003466 TL.setStarLoc(Chunk.Loc);
Abramo Bagnarab6ab6c12011-03-05 14:42:21 +00003467 TL.setClassTInfo(ClsTInfo);
John McCall51bd8032009-10-18 01:05:36 +00003468 }
3469 void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
3470 assert(Chunk.Kind == DeclaratorChunk::Reference);
John McCall54e14c42009-10-22 22:37:11 +00003471 // 'Amp' is misleading: this might have been originally
3472 /// spelled with AmpAmp.
John McCall51bd8032009-10-18 01:05:36 +00003473 TL.setAmpLoc(Chunk.Loc);
3474 }
3475 void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
3476 assert(Chunk.Kind == DeclaratorChunk::Reference);
3477 assert(!Chunk.Ref.LValueRef);
3478 TL.setAmpAmpLoc(Chunk.Loc);
3479 }
3480 void VisitArrayTypeLoc(ArrayTypeLoc TL) {
3481 assert(Chunk.Kind == DeclaratorChunk::Array);
3482 TL.setLBracketLoc(Chunk.Loc);
3483 TL.setRBracketLoc(Chunk.EndLoc);
3484 TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
3485 }
3486 void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
3487 assert(Chunk.Kind == DeclaratorChunk::Function);
Abramo Bagnara796aa442011-03-12 11:17:06 +00003488 TL.setLocalRangeBegin(Chunk.Loc);
3489 TL.setLocalRangeEnd(Chunk.EndLoc);
John McCall51bd8032009-10-18 01:05:36 +00003490
3491 const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
Abramo Bagnara59c0a812012-10-04 21:42:10 +00003492 TL.setLParenLoc(FTI.getLParenLoc());
3493 TL.setRParenLoc(FTI.getRParenLoc());
John McCall54e14c42009-10-22 22:37:11 +00003494 for (unsigned i = 0, e = TL.getNumArgs(), tpi = 0; i != e; ++i) {
John McCalld226f652010-08-21 09:40:31 +00003495 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
John McCall54e14c42009-10-22 22:37:11 +00003496 TL.setArg(tpi++, Param);
John McCall51bd8032009-10-18 01:05:36 +00003497 }
3498 // FIXME: exception specs
3499 }
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003500 void VisitParenTypeLoc(ParenTypeLoc TL) {
3501 assert(Chunk.Kind == DeclaratorChunk::Paren);
3502 TL.setLParenLoc(Chunk.Loc);
3503 TL.setRParenLoc(Chunk.EndLoc);
3504 }
John McCall51bd8032009-10-18 01:05:36 +00003505
3506 void VisitTypeLoc(TypeLoc TL) {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00003507 llvm_unreachable("unsupported TypeLoc kind in declarator!");
John McCall51bd8032009-10-18 01:05:36 +00003508 }
3509 };
Argyrios Kyrtzidisf352bdd2009-09-29 19:43:35 +00003510}
3511
John McCalla93c9342009-12-07 02:54:59 +00003512/// \brief Create and instantiate a TypeSourceInfo with type source information.
Argyrios Kyrtzidis4adab7f2009-08-19 01:28:06 +00003513///
3514/// \param T QualType referring to the type as written in source code.
Douglas Gregor05baacb2010-04-12 23:19:01 +00003515///
3516/// \param ReturnTypeInfo For declarators whose return type does not show
3517/// up in the normal place in the declaration specifiers (such as a C++
3518/// conversion function), this pointer will refer to a type source information
3519/// for that return type.
John McCalla93c9342009-12-07 02:54:59 +00003520TypeSourceInfo *
Douglas Gregor05baacb2010-04-12 23:19:01 +00003521Sema::GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
3522 TypeSourceInfo *ReturnTypeInfo) {
John McCalla93c9342009-12-07 02:54:59 +00003523 TypeSourceInfo *TInfo = Context.CreateTypeSourceInfo(T);
3524 UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc();
Argyrios Kyrtzidis4adab7f2009-08-19 01:28:06 +00003525
Douglas Gregora8bc8c92010-12-23 22:44:42 +00003526 // Handle parameter packs whose type is a pack expansion.
3527 if (isa<PackExpansionType>(T)) {
David Blaikie39e6ab42013-02-18 22:06:02 +00003528 CurrTL.castAs<PackExpansionTypeLoc>().setEllipsisLoc(D.getEllipsisLoc());
Chad Rosier91cbbbf2012-06-26 21:41:40 +00003529 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
Douglas Gregora8bc8c92010-12-23 22:44:42 +00003530 }
Chad Rosier91cbbbf2012-06-26 21:41:40 +00003531
Sebastian Redl8ce35b02009-10-25 21:45:37 +00003532 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
David Blaikie39e6ab42013-02-18 22:06:02 +00003533 while (AttributedTypeLoc TL = CurrTL.getAs<AttributedTypeLoc>()) {
John McCall14aa2172011-03-04 04:00:19 +00003534 fillAttributedTypeLoc(TL, D.getTypeObject(i).getAttrs());
3535 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
3536 }
3537
Abramo Bagnarab6ab6c12011-03-05 14:42:21 +00003538 DeclaratorLocFiller(Context, D.getTypeObject(i)).Visit(CurrTL);
John McCall51bd8032009-10-18 01:05:36 +00003539 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
Argyrios Kyrtzidis4adab7f2009-08-19 01:28:06 +00003540 }
Chad Rosier91cbbbf2012-06-26 21:41:40 +00003541
John McCallb3d87482010-08-24 05:47:05 +00003542 // If we have different source information for the return type, use
3543 // that. This really only applies to C++ conversion functions.
3544 if (ReturnTypeInfo) {
Douglas Gregor05baacb2010-04-12 23:19:01 +00003545 TypeLoc TL = ReturnTypeInfo->getTypeLoc();
3546 assert(TL.getFullDataSize() == CurrTL.getFullDataSize());
3547 memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize());
John McCallb3d87482010-08-24 05:47:05 +00003548 } else {
Douglas Gregorc21c7e92011-01-25 19:13:18 +00003549 TypeSpecLocFiller(Context, D.getDeclSpec()).Visit(CurrTL);
Douglas Gregor05baacb2010-04-12 23:19:01 +00003550 }
Chad Rosier91cbbbf2012-06-26 21:41:40 +00003551
John McCalla93c9342009-12-07 02:54:59 +00003552 return TInfo;
Argyrios Kyrtzidis4adab7f2009-08-19 01:28:06 +00003553}
3554
John McCalla93c9342009-12-07 02:54:59 +00003555/// \brief Create a LocInfoType to hold the given QualType and TypeSourceInfo.
John McCallb3d87482010-08-24 05:47:05 +00003556ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) {
Argyrios Kyrtzidis1bb8a452009-08-19 01:28:17 +00003557 // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
3558 // and Sema during declaration parsing. Try deallocating/caching them when
3559 // it's appropriate, instead of allocating them and keeping them around.
Chad Rosier91cbbbf2012-06-26 21:41:40 +00003560 LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType),
Douglas Gregoreb0eb492010-12-10 08:12:03 +00003561 TypeAlignment);
John McCalla93c9342009-12-07 02:54:59 +00003562 new (LocT) LocInfoType(T, TInfo);
Argyrios Kyrtzidis1bb8a452009-08-19 01:28:17 +00003563 assert(LocT->getTypeClass() != T->getTypeClass() &&
3564 "LocInfoType's TypeClass conflicts with an existing Type class");
John McCallb3d87482010-08-24 05:47:05 +00003565 return ParsedType::make(QualType(LocT, 0));
Argyrios Kyrtzidis1bb8a452009-08-19 01:28:17 +00003566}
3567
3568void LocInfoType::getAsStringInternal(std::string &Str,
3569 const PrintingPolicy &Policy) const {
David Blaikieb219cfc2011-09-23 05:06:16 +00003570 llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*"
Argyrios Kyrtzidis35d44e52009-08-19 01:46:06 +00003571 " was used directly instead of getting the QualType through"
3572 " GetTypeFromParser");
Argyrios Kyrtzidis1bb8a452009-08-19 01:28:17 +00003573}
3574
John McCallf312b1e2010-08-26 23:41:50 +00003575TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003576 // C99 6.7.6: Type names have no identifier. This is already validated by
3577 // the parser.
3578 assert(D.getIdentifier() == 0 && "Type name should have no identifier!");
Mike Stump1eb44332009-09-09 15:08:12 +00003579
Argyrios Kyrtzidisd3880f82011-06-28 03:01:18 +00003580 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCallbf1a0282010-06-04 23:28:52 +00003581 QualType T = TInfo->getType();
Chris Lattner5153ee62009-04-25 08:47:54 +00003582 if (D.isInvalidType())
Douglas Gregor809070a2009-02-18 17:45:20 +00003583 return true;
Steve Naroff5912a352007-08-28 20:14:24 +00003584
John McCalle82247a2011-10-01 05:17:03 +00003585 // Make sure there are no unused decl attributes on the declarator.
John McCallcdda47f2011-10-01 09:56:14 +00003586 // We don't want to do this for ObjC parameters because we're going
3587 // to apply them to the actual parameter declaration.
Richard Smith6b3d3e52013-02-20 19:22:51 +00003588 // Likewise, we don't want to do this for alias declarations, because
3589 // we are actually going to build a declaration from this eventually.
3590 if (D.getContext() != Declarator::ObjCParameterContext &&
3591 D.getContext() != Declarator::AliasDeclContext &&
3592 D.getContext() != Declarator::AliasTemplateContext)
John McCallcdda47f2011-10-01 09:56:14 +00003593 checkUnusedDeclAttributes(D);
John McCalle82247a2011-10-01 05:17:03 +00003594
David Blaikie4e4d0842012-03-11 07:00:24 +00003595 if (getLangOpts().CPlusPlus) {
Douglas Gregor402abb52009-05-28 23:31:59 +00003596 // Check that there are no default arguments (C++ only).
Douglas Gregor6d6eb572008-05-07 04:49:29 +00003597 CheckExtraCXXDefaultArguments(D);
Douglas Gregor402abb52009-05-28 23:31:59 +00003598 }
3599
John McCallb3d87482010-08-24 05:47:05 +00003600 return CreateParsedType(T, TInfo);
Reid Spencer5f016e22007-07-11 17:01:13 +00003601}
3602
Douglas Gregore97179c2011-09-08 01:46:34 +00003603ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) {
3604 QualType T = Context.getObjCInstanceType();
3605 TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
3606 return CreateParsedType(T, TInfo);
3607}
3608
3609
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003610//===----------------------------------------------------------------------===//
3611// Type Attribute Processing
3612//===----------------------------------------------------------------------===//
3613
3614/// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
3615/// specified type. The attribute contains 1 argument, the id of the address
3616/// space for the type.
Mike Stump1eb44332009-09-09 15:08:12 +00003617static void HandleAddressSpaceTypeAttribute(QualType &Type,
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003618 const AttributeList &Attr, Sema &S){
John McCall0953e762009-09-24 19:53:00 +00003619
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003620 // If this type is already address space qualified, reject it.
Peter Collingbourne29e3ef82011-07-27 20:29:53 +00003621 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified by
3622 // qualifiers for two or more different address spaces."
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003623 if (Type.getAddressSpace()) {
3624 S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers);
Abramo Bagnarae215f722010-04-30 13:10:51 +00003625 Attr.setInvalid();
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003626 return;
3627 }
Mike Stump1eb44332009-09-09 15:08:12 +00003628
Peter Collingbourne020972d2011-07-27 20:30:05 +00003629 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be
3630 // qualified by an address-space qualifier."
3631 if (Type->isFunctionType()) {
3632 S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type);
3633 Attr.setInvalid();
3634 return;
3635 }
3636
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003637 // Check the attribute arguments.
3638 if (Attr.getNumArgs() != 1) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003639 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
Abramo Bagnarae215f722010-04-30 13:10:51 +00003640 Attr.setInvalid();
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003641 return;
3642 }
3643 Expr *ASArgExpr = static_cast<Expr *>(Attr.getArg(0));
3644 llvm::APSInt addrSpace(32);
Douglas Gregorac06a0e2010-05-18 23:01:22 +00003645 if (ASArgExpr->isTypeDependent() || ASArgExpr->isValueDependent() ||
3646 !ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003647 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_not_int)
3648 << ASArgExpr->getSourceRange();
Abramo Bagnarae215f722010-04-30 13:10:51 +00003649 Attr.setInvalid();
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003650 return;
3651 }
3652
John McCallefadb772009-07-28 06:52:18 +00003653 // Bounds checking.
3654 if (addrSpace.isSigned()) {
3655 if (addrSpace.isNegative()) {
3656 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_negative)
3657 << ASArgExpr->getSourceRange();
Abramo Bagnarae215f722010-04-30 13:10:51 +00003658 Attr.setInvalid();
John McCallefadb772009-07-28 06:52:18 +00003659 return;
3660 }
3661 addrSpace.setIsSigned(false);
3662 }
3663 llvm::APSInt max(addrSpace.getBitWidth());
John McCall0953e762009-09-24 19:53:00 +00003664 max = Qualifiers::MaxAddressSpace;
John McCallefadb772009-07-28 06:52:18 +00003665 if (addrSpace > max) {
3666 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_too_high)
John McCall0953e762009-09-24 19:53:00 +00003667 << Qualifiers::MaxAddressSpace << ASArgExpr->getSourceRange();
Abramo Bagnarae215f722010-04-30 13:10:51 +00003668 Attr.setInvalid();
John McCallefadb772009-07-28 06:52:18 +00003669 return;
3670 }
3671
Mike Stump1eb44332009-09-09 15:08:12 +00003672 unsigned ASIdx = static_cast<unsigned>(addrSpace.getZExtValue());
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00003673 Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003674}
3675
John McCalld85bf9d2012-02-08 00:46:41 +00003676/// Does this type have a "direct" ownership qualifier? That is,
3677/// is it written like "__strong id", as opposed to something like
3678/// "typeof(foo)", where that happens to be strong?
3679static bool hasDirectOwnershipQualifier(QualType type) {
3680 // Fast path: no qualifier at all.
3681 assert(type.getQualifiers().hasObjCLifetime());
3682
3683 while (true) {
3684 // __strong id
3685 if (const AttributedType *attr = dyn_cast<AttributedType>(type)) {
3686 if (attr->getAttrKind() == AttributedType::attr_objc_ownership)
3687 return true;
3688
3689 type = attr->getModifiedType();
3690
3691 // X *__strong (...)
3692 } else if (const ParenType *paren = dyn_cast<ParenType>(type)) {
3693 type = paren->getInnerType();
Chad Rosier91cbbbf2012-06-26 21:41:40 +00003694
John McCalld85bf9d2012-02-08 00:46:41 +00003695 // That's it for things we want to complain about. In particular,
3696 // we do not want to look through typedefs, typeof(expr),
3697 // typeof(type), or any other way that the type is somehow
3698 // abstracted.
3699 } else {
Chad Rosier91cbbbf2012-06-26 21:41:40 +00003700
John McCalld85bf9d2012-02-08 00:46:41 +00003701 return false;
3702 }
3703 }
3704}
3705
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00003706/// handleObjCOwnershipTypeAttr - Process an objc_ownership
John McCallf85e1932011-06-15 23:02:42 +00003707/// attribute on the specified type.
3708///
3709/// Returns 'true' if the attribute was handled.
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00003710static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
John McCallf85e1932011-06-15 23:02:42 +00003711 AttributeList &attr,
3712 QualType &type) {
Argyrios Kyrtzidise71202e2011-11-04 20:37:24 +00003713 bool NonObjCPointer = false;
3714
3715 if (!type->isDependentType()) {
3716 if (const PointerType *ptr = type->getAs<PointerType>()) {
3717 QualType pointee = ptr->getPointeeType();
3718 if (pointee->isObjCRetainableType() || pointee->isPointerType())
3719 return false;
3720 // It is important not to lose the source info that there was an attribute
3721 // applied to non-objc pointer. We will create an attributed type but
3722 // its type will be the same as the original type.
3723 NonObjCPointer = true;
3724 } else if (!type->isObjCRetainableType()) {
3725 return false;
3726 }
John McCallb2381b12013-03-01 07:58:16 +00003727
3728 // Don't accept an ownership attribute in the declspec if it would
3729 // just be the return type of a block pointer.
3730 if (state.isProcessingDeclSpec()) {
3731 Declarator &D = state.getDeclarator();
3732 if (maybeMovePastReturnType(D, D.getNumTypeObjects()))
3733 return false;
3734 }
Argyrios Kyrtzidise71202e2011-11-04 20:37:24 +00003735 }
John McCallf85e1932011-06-15 23:02:42 +00003736
3737 Sema &S = state.getSema();
Argyrios Kyrtzidis440ec2e2011-09-28 18:35:06 +00003738 SourceLocation AttrLoc = attr.getLoc();
3739 if (AttrLoc.isMacroID())
3740 AttrLoc = S.getSourceManager().getImmediateExpansionRange(AttrLoc).first;
John McCallf85e1932011-06-15 23:02:42 +00003741
John McCallf85e1932011-06-15 23:02:42 +00003742 if (!attr.getParameterName()) {
Argyrios Kyrtzidis440ec2e2011-09-28 18:35:06 +00003743 S.Diag(AttrLoc, diag::err_attribute_argument_n_not_string)
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00003744 << "objc_ownership" << 1;
John McCallf85e1932011-06-15 23:02:42 +00003745 attr.setInvalid();
3746 return true;
3747 }
3748
John McCalld85bf9d2012-02-08 00:46:41 +00003749 // Consume lifetime attributes without further comment outside of
3750 // ARC mode.
David Blaikie4e4d0842012-03-11 07:00:24 +00003751 if (!S.getLangOpts().ObjCAutoRefCount)
John McCalld85bf9d2012-02-08 00:46:41 +00003752 return true;
3753
John McCallf85e1932011-06-15 23:02:42 +00003754 Qualifiers::ObjCLifetime lifetime;
3755 if (attr.getParameterName()->isStr("none"))
3756 lifetime = Qualifiers::OCL_ExplicitNone;
3757 else if (attr.getParameterName()->isStr("strong"))
3758 lifetime = Qualifiers::OCL_Strong;
3759 else if (attr.getParameterName()->isStr("weak"))
3760 lifetime = Qualifiers::OCL_Weak;
3761 else if (attr.getParameterName()->isStr("autoreleasing"))
3762 lifetime = Qualifiers::OCL_Autoreleasing;
3763 else {
Argyrios Kyrtzidis440ec2e2011-09-28 18:35:06 +00003764 S.Diag(AttrLoc, diag::warn_attribute_type_not_supported)
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00003765 << "objc_ownership" << attr.getParameterName();
John McCallf85e1932011-06-15 23:02:42 +00003766 attr.setInvalid();
3767 return true;
3768 }
3769
John McCalld85bf9d2012-02-08 00:46:41 +00003770 SplitQualType underlyingType = type.split();
3771
3772 // Check for redundant/conflicting ownership qualifiers.
3773 if (Qualifiers::ObjCLifetime previousLifetime
3774 = type.getQualifiers().getObjCLifetime()) {
3775 // If it's written directly, that's an error.
3776 if (hasDirectOwnershipQualifier(type)) {
3777 S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant)
3778 << type;
3779 return true;
3780 }
3781
3782 // Otherwise, if the qualifiers actually conflict, pull sugar off
3783 // until we reach a type that is directly qualified.
3784 if (previousLifetime != lifetime) {
3785 // This should always terminate: the canonical type is
3786 // qualified, so some bit of sugar must be hiding it.
3787 while (!underlyingType.Quals.hasObjCLifetime()) {
3788 underlyingType = underlyingType.getSingleStepDesugaredType();
3789 }
3790 underlyingType.Quals.removeObjCLifetime();
3791 }
3792 }
3793
3794 underlyingType.Quals.addObjCLifetime(lifetime);
John McCallf85e1932011-06-15 23:02:42 +00003795
Argyrios Kyrtzidise71202e2011-11-04 20:37:24 +00003796 if (NonObjCPointer) {
3797 StringRef name = attr.getName()->getName();
3798 switch (lifetime) {
3799 case Qualifiers::OCL_None:
3800 case Qualifiers::OCL_ExplicitNone:
3801 break;
3802 case Qualifiers::OCL_Strong: name = "__strong"; break;
3803 case Qualifiers::OCL_Weak: name = "__weak"; break;
3804 case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break;
3805 }
3806 S.Diag(AttrLoc, diag::warn_objc_object_attribute_wrong_type)
3807 << name << type;
3808 }
3809
John McCallf85e1932011-06-15 23:02:42 +00003810 QualType origType = type;
Argyrios Kyrtzidise71202e2011-11-04 20:37:24 +00003811 if (!NonObjCPointer)
John McCalld85bf9d2012-02-08 00:46:41 +00003812 type = S.Context.getQualifiedType(underlyingType);
John McCallf85e1932011-06-15 23:02:42 +00003813
3814 // If we have a valid source location for the attribute, use an
3815 // AttributedType instead.
Argyrios Kyrtzidis440ec2e2011-09-28 18:35:06 +00003816 if (AttrLoc.isValid())
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00003817 type = S.Context.getAttributedType(AttributedType::attr_objc_ownership,
John McCallf85e1932011-06-15 23:02:42 +00003818 origType, type);
3819
John McCall9f084a32011-07-06 00:26:06 +00003820 // Forbid __weak if the runtime doesn't support it.
John McCallf85e1932011-06-15 23:02:42 +00003821 if (lifetime == Qualifiers::OCL_Weak &&
John McCall0a7dd782012-08-21 02:47:43 +00003822 !S.getLangOpts().ObjCARCWeak && !NonObjCPointer) {
John McCallf85e1932011-06-15 23:02:42 +00003823
3824 // Actually, delay this until we know what we're parsing.
3825 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
3826 S.DelayedDiagnostics.add(
Argyrios Kyrtzidis440ec2e2011-09-28 18:35:06 +00003827 sema::DelayedDiagnostic::makeForbiddenType(
3828 S.getSourceManager().getExpansionLoc(AttrLoc),
John McCallf85e1932011-06-15 23:02:42 +00003829 diag::err_arc_weak_no_runtime, type, /*ignored*/ 0));
3830 } else {
Argyrios Kyrtzidis440ec2e2011-09-28 18:35:06 +00003831 S.Diag(AttrLoc, diag::err_arc_weak_no_runtime);
John McCallf85e1932011-06-15 23:02:42 +00003832 }
3833
3834 attr.setInvalid();
3835 return true;
3836 }
Chad Rosier91cbbbf2012-06-26 21:41:40 +00003837
3838 // Forbid __weak for class objects marked as
Fariborz Jahanian742352a2011-07-06 19:24:05 +00003839 // objc_arc_weak_reference_unavailable
3840 if (lifetime == Qualifiers::OCL_Weak) {
John McCallb2381b12013-03-01 07:58:16 +00003841 if (const ObjCObjectPointerType *ObjT =
3842 type->getAs<ObjCObjectPointerType>()) {
Richard Smith4e90bc32012-08-23 04:53:18 +00003843 if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) {
3844 if (Class->isArcWeakrefUnavailable()) {
3845 S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class);
3846 S.Diag(ObjT->getInterfaceDecl()->getLocation(),
3847 diag::note_class_declared);
3848 }
Fariborz Jahanian742352a2011-07-06 19:24:05 +00003849 }
3850 }
3851 }
Chad Rosier91cbbbf2012-06-26 21:41:40 +00003852
John McCallf85e1932011-06-15 23:02:42 +00003853 return true;
3854}
3855
John McCall711c52b2011-01-05 12:14:39 +00003856/// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type
3857/// attribute on the specified type. Returns true to indicate that
3858/// the attribute was handled, false to indicate that the type does
3859/// not permit the attribute.
3860static bool handleObjCGCTypeAttr(TypeProcessingState &state,
3861 AttributeList &attr,
3862 QualType &type) {
3863 Sema &S = state.getSema();
3864
3865 // Delay if this isn't some kind of pointer.
3866 if (!type->isPointerType() &&
3867 !type->isObjCObjectPointerType() &&
3868 !type->isBlockPointerType())
3869 return false;
3870
3871 if (type.getObjCGCAttr() != Qualifiers::GCNone) {
3872 S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc);
3873 attr.setInvalid();
3874 return true;
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00003875 }
Mike Stump1eb44332009-09-09 15:08:12 +00003876
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00003877 // Check the attribute arguments.
John McCall711c52b2011-01-05 12:14:39 +00003878 if (!attr.getParameterName()) {
3879 S.Diag(attr.getLoc(), diag::err_attribute_argument_n_not_string)
Fariborz Jahanianba372b82009-02-18 17:52:36 +00003880 << "objc_gc" << 1;
John McCall711c52b2011-01-05 12:14:39 +00003881 attr.setInvalid();
3882 return true;
Fariborz Jahanianba372b82009-02-18 17:52:36 +00003883 }
John McCall0953e762009-09-24 19:53:00 +00003884 Qualifiers::GC GCAttr;
John McCall711c52b2011-01-05 12:14:39 +00003885 if (attr.getNumArgs() != 0) {
3886 S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
3887 attr.setInvalid();
3888 return true;
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00003889 }
John McCall711c52b2011-01-05 12:14:39 +00003890 if (attr.getParameterName()->isStr("weak"))
John McCall0953e762009-09-24 19:53:00 +00003891 GCAttr = Qualifiers::Weak;
John McCall711c52b2011-01-05 12:14:39 +00003892 else if (attr.getParameterName()->isStr("strong"))
John McCall0953e762009-09-24 19:53:00 +00003893 GCAttr = Qualifiers::Strong;
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00003894 else {
John McCall711c52b2011-01-05 12:14:39 +00003895 S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported)
3896 << "objc_gc" << attr.getParameterName();
3897 attr.setInvalid();
3898 return true;
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00003899 }
Mike Stump1eb44332009-09-09 15:08:12 +00003900
John McCall14aa2172011-03-04 04:00:19 +00003901 QualType origType = type;
3902 type = S.Context.getObjCGCQualType(origType, GCAttr);
3903
3904 // Make an attributed type to preserve the source information.
3905 if (attr.getLoc().isValid())
3906 type = S.Context.getAttributedType(AttributedType::attr_objc_gc,
3907 origType, type);
3908
John McCall711c52b2011-01-05 12:14:39 +00003909 return true;
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00003910}
3911
John McCalle6a365d2010-12-19 02:44:49 +00003912namespace {
3913 /// A helper class to unwrap a type down to a function for the
3914 /// purposes of applying attributes there.
3915 ///
3916 /// Use:
3917 /// FunctionTypeUnwrapper unwrapped(SemaRef, T);
3918 /// if (unwrapped.isFunctionType()) {
3919 /// const FunctionType *fn = unwrapped.get();
3920 /// // change fn somehow
3921 /// T = unwrapped.wrap(fn);
3922 /// }
3923 struct FunctionTypeUnwrapper {
3924 enum WrapKind {
3925 Desugar,
3926 Parens,
3927 Pointer,
3928 BlockPointer,
3929 Reference,
3930 MemberPointer
3931 };
3932
3933 QualType Original;
3934 const FunctionType *Fn;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003935 SmallVector<unsigned char /*WrapKind*/, 8> Stack;
John McCalle6a365d2010-12-19 02:44:49 +00003936
3937 FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) {
3938 while (true) {
3939 const Type *Ty = T.getTypePtr();
3940 if (isa<FunctionType>(Ty)) {
3941 Fn = cast<FunctionType>(Ty);
3942 return;
3943 } else if (isa<ParenType>(Ty)) {
3944 T = cast<ParenType>(Ty)->getInnerType();
3945 Stack.push_back(Parens);
3946 } else if (isa<PointerType>(Ty)) {
3947 T = cast<PointerType>(Ty)->getPointeeType();
3948 Stack.push_back(Pointer);
3949 } else if (isa<BlockPointerType>(Ty)) {
3950 T = cast<BlockPointerType>(Ty)->getPointeeType();
3951 Stack.push_back(BlockPointer);
3952 } else if (isa<MemberPointerType>(Ty)) {
3953 T = cast<MemberPointerType>(Ty)->getPointeeType();
3954 Stack.push_back(MemberPointer);
3955 } else if (isa<ReferenceType>(Ty)) {
3956 T = cast<ReferenceType>(Ty)->getPointeeType();
3957 Stack.push_back(Reference);
3958 } else {
3959 const Type *DTy = Ty->getUnqualifiedDesugaredType();
3960 if (Ty == DTy) {
3961 Fn = 0;
3962 return;
3963 }
3964
3965 T = QualType(DTy, 0);
3966 Stack.push_back(Desugar);
3967 }
3968 }
3969 }
3970
3971 bool isFunctionType() const { return (Fn != 0); }
3972 const FunctionType *get() const { return Fn; }
3973
3974 QualType wrap(Sema &S, const FunctionType *New) {
3975 // If T wasn't modified from the unwrapped type, do nothing.
3976 if (New == get()) return Original;
3977
3978 Fn = New;
3979 return wrap(S.Context, Original, 0);
3980 }
3981
3982 private:
3983 QualType wrap(ASTContext &C, QualType Old, unsigned I) {
3984 if (I == Stack.size())
3985 return C.getQualifiedType(Fn, Old.getQualifiers());
3986
3987 // Build up the inner type, applying the qualifiers from the old
3988 // type to the new type.
3989 SplitQualType SplitOld = Old.split();
3990
3991 // As a special case, tail-recurse if there are no qualifiers.
John McCall200fa532012-02-08 00:46:36 +00003992 if (SplitOld.Quals.empty())
3993 return wrap(C, SplitOld.Ty, I);
3994 return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals);
John McCalle6a365d2010-12-19 02:44:49 +00003995 }
3996
3997 QualType wrap(ASTContext &C, const Type *Old, unsigned I) {
3998 if (I == Stack.size()) return QualType(Fn, 0);
3999
4000 switch (static_cast<WrapKind>(Stack[I++])) {
4001 case Desugar:
4002 // This is the point at which we potentially lose source
4003 // information.
4004 return wrap(C, Old->getUnqualifiedDesugaredType(), I);
4005
4006 case Parens: {
4007 QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I);
4008 return C.getParenType(New);
4009 }
4010
4011 case Pointer: {
4012 QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I);
4013 return C.getPointerType(New);
4014 }
4015
4016 case BlockPointer: {
4017 QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I);
4018 return C.getBlockPointerType(New);
4019 }
4020
4021 case MemberPointer: {
4022 const MemberPointerType *OldMPT = cast<MemberPointerType>(Old);
4023 QualType New = wrap(C, OldMPT->getPointeeType(), I);
4024 return C.getMemberPointerType(New, OldMPT->getClass());
4025 }
4026
4027 case Reference: {
4028 const ReferenceType *OldRef = cast<ReferenceType>(Old);
4029 QualType New = wrap(C, OldRef->getPointeeType(), I);
4030 if (isa<LValueReferenceType>(OldRef))
4031 return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue());
4032 else
4033 return C.getRValueReferenceType(New);
4034 }
4035 }
4036
4037 llvm_unreachable("unknown wrapping kind");
John McCalle6a365d2010-12-19 02:44:49 +00004038 }
4039 };
4040}
4041
John McCall711c52b2011-01-05 12:14:39 +00004042/// Process an individual function attribute. Returns true to
4043/// indicate that the attribute was handled, false if it wasn't.
4044static bool handleFunctionTypeAttr(TypeProcessingState &state,
4045 AttributeList &attr,
4046 QualType &type) {
4047 Sema &S = state.getSema();
John McCalle6a365d2010-12-19 02:44:49 +00004048
John McCall711c52b2011-01-05 12:14:39 +00004049 FunctionTypeUnwrapper unwrapped(S, type);
Mike Stump24556362009-07-25 21:26:53 +00004050
Sean Hunt8e083e72012-06-19 23:57:03 +00004051 if (attr.getKind() == AttributeList::AT_NoReturn) {
John McCall711c52b2011-01-05 12:14:39 +00004052 if (S.CheckNoReturnAttr(attr))
John McCall04a67a62010-02-05 21:31:56 +00004053 return true;
John McCalle6a365d2010-12-19 02:44:49 +00004054
John McCall711c52b2011-01-05 12:14:39 +00004055 // Delay if this is not a function type.
4056 if (!unwrapped.isFunctionType())
4057 return false;
4058
John McCall04a67a62010-02-05 21:31:56 +00004059 // Otherwise we can process right away.
John McCall711c52b2011-01-05 12:14:39 +00004060 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true);
4061 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
4062 return true;
John McCall04a67a62010-02-05 21:31:56 +00004063 }
Mike Stump24556362009-07-25 21:26:53 +00004064
John McCallf85e1932011-06-15 23:02:42 +00004065 // ns_returns_retained is not always a type attribute, but if we got
4066 // here, we're treating it as one right now.
Sean Hunt8e083e72012-06-19 23:57:03 +00004067 if (attr.getKind() == AttributeList::AT_NSReturnsRetained) {
David Blaikie4e4d0842012-03-11 07:00:24 +00004068 assert(S.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00004069 "ns_returns_retained treated as type attribute in non-ARC");
4070 if (attr.getNumArgs()) return true;
4071
4072 // Delay if this is not a function type.
4073 if (!unwrapped.isFunctionType())
4074 return false;
4075
4076 FunctionType::ExtInfo EI
4077 = unwrapped.get()->getExtInfo().withProducesResult(true);
4078 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
4079 return true;
4080 }
4081
Sean Hunt8e083e72012-06-19 23:57:03 +00004082 if (attr.getKind() == AttributeList::AT_Regparm) {
John McCall711c52b2011-01-05 12:14:39 +00004083 unsigned value;
4084 if (S.CheckRegparmAttr(attr, value))
Rafael Espindola425ef722010-03-30 22:15:11 +00004085 return true;
4086
John McCall711c52b2011-01-05 12:14:39 +00004087 // Delay if this is not a function type.
4088 if (!unwrapped.isFunctionType())
Rafael Espindola425ef722010-03-30 22:15:11 +00004089 return false;
4090
Argyrios Kyrtzidisce955662011-01-25 23:16:40 +00004091 // Diagnose regparm with fastcall.
4092 const FunctionType *fn = unwrapped.get();
4093 CallingConv CC = fn->getCallConv();
4094 if (CC == CC_X86FastCall) {
4095 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
4096 << FunctionType::getNameForCallConv(CC)
4097 << "regparm";
4098 attr.setInvalid();
4099 return true;
4100 }
4101
Chad Rosier91cbbbf2012-06-26 21:41:40 +00004102 FunctionType::ExtInfo EI =
John McCall711c52b2011-01-05 12:14:39 +00004103 unwrapped.get()->getExtInfo().withRegParm(value);
4104 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
4105 return true;
Rafael Espindola425ef722010-03-30 22:15:11 +00004106 }
4107
Aaron Ballman82bfa192012-10-02 14:26:08 +00004108 // Delay if the type didn't work out to a function.
4109 if (!unwrapped.isFunctionType()) return false;
4110
John McCall04a67a62010-02-05 21:31:56 +00004111 // Otherwise, a calling convention.
John McCall711c52b2011-01-05 12:14:39 +00004112 CallingConv CC;
4113 if (S.CheckCallingConvAttr(attr, CC))
4114 return true;
John McCallf82b4e82010-02-04 05:44:44 +00004115
John McCall711c52b2011-01-05 12:14:39 +00004116 const FunctionType *fn = unwrapped.get();
4117 CallingConv CCOld = fn->getCallConv();
Charles Davis064f7db2010-02-23 06:13:55 +00004118 if (S.Context.getCanonicalCallConv(CC) ==
Abramo Bagnarae215f722010-04-30 13:10:51 +00004119 S.Context.getCanonicalCallConv(CCOld)) {
Argyrios Kyrtzidisce955662011-01-25 23:16:40 +00004120 FunctionType::ExtInfo EI= unwrapped.get()->getExtInfo().withCallingConv(CC);
4121 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
John McCall711c52b2011-01-05 12:14:39 +00004122 return true;
Abramo Bagnarae215f722010-04-30 13:10:51 +00004123 }
John McCall04a67a62010-02-05 21:31:56 +00004124
Roman Divacky8e68f1c2011-08-05 16:37:22 +00004125 if (CCOld != (S.LangOpts.MRTD ? CC_X86StdCall : CC_Default)) {
John McCall04a67a62010-02-05 21:31:56 +00004126 // Should we diagnose reapplications of the same convention?
John McCall711c52b2011-01-05 12:14:39 +00004127 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
John McCall04a67a62010-02-05 21:31:56 +00004128 << FunctionType::getNameForCallConv(CC)
4129 << FunctionType::getNameForCallConv(CCOld);
John McCall711c52b2011-01-05 12:14:39 +00004130 attr.setInvalid();
4131 return true;
John McCall04a67a62010-02-05 21:31:56 +00004132 }
4133
4134 // Diagnose the use of X86 fastcall on varargs or unprototyped functions.
4135 if (CC == CC_X86FastCall) {
John McCall711c52b2011-01-05 12:14:39 +00004136 if (isa<FunctionNoProtoType>(fn)) {
4137 S.Diag(attr.getLoc(), diag::err_cconv_knr)
John McCall04a67a62010-02-05 21:31:56 +00004138 << FunctionType::getNameForCallConv(CC);
John McCall711c52b2011-01-05 12:14:39 +00004139 attr.setInvalid();
4140 return true;
John McCall04a67a62010-02-05 21:31:56 +00004141 }
4142
John McCall711c52b2011-01-05 12:14:39 +00004143 const FunctionProtoType *FnP = cast<FunctionProtoType>(fn);
John McCall04a67a62010-02-05 21:31:56 +00004144 if (FnP->isVariadic()) {
John McCall711c52b2011-01-05 12:14:39 +00004145 S.Diag(attr.getLoc(), diag::err_cconv_varargs)
John McCall04a67a62010-02-05 21:31:56 +00004146 << FunctionType::getNameForCallConv(CC);
John McCall711c52b2011-01-05 12:14:39 +00004147 attr.setInvalid();
4148 return true;
John McCall04a67a62010-02-05 21:31:56 +00004149 }
Argyrios Kyrtzidisce955662011-01-25 23:16:40 +00004150
4151 // Also diagnose fastcall with regparm.
Eli Friedmana49218e2011-04-09 08:18:08 +00004152 if (fn->getHasRegParm()) {
Argyrios Kyrtzidisce955662011-01-25 23:16:40 +00004153 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
4154 << "regparm"
4155 << FunctionType::getNameForCallConv(CC);
4156 attr.setInvalid();
4157 return true;
4158 }
John McCall04a67a62010-02-05 21:31:56 +00004159 }
4160
John McCall711c52b2011-01-05 12:14:39 +00004161 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withCallingConv(CC);
4162 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
4163 return true;
John McCallf82b4e82010-02-04 05:44:44 +00004164}
4165
Peter Collingbourne207f4d82011-03-18 22:38:29 +00004166/// Handle OpenCL image access qualifiers: read_only, write_only, read_write
4167static void HandleOpenCLImageAccessAttribute(QualType& CurType,
4168 const AttributeList &Attr,
4169 Sema &S) {
4170 // Check the attribute arguments.
4171 if (Attr.getNumArgs() != 1) {
4172 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
4173 Attr.setInvalid();
4174 return;
4175 }
4176 Expr *sizeExpr = static_cast<Expr *>(Attr.getArg(0));
4177 llvm::APSInt arg(32);
4178 if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() ||
4179 !sizeExpr->isIntegerConstantExpr(arg, S.Context)) {
4180 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
4181 << "opencl_image_access" << sizeExpr->getSourceRange();
4182 Attr.setInvalid();
4183 return;
4184 }
4185 unsigned iarg = static_cast<unsigned>(arg.getZExtValue());
4186 switch (iarg) {
4187 case CLIA_read_only:
4188 case CLIA_write_only:
4189 case CLIA_read_write:
4190 // Implemented in a separate patch
4191 break;
4192 default:
4193 // Implemented in a separate patch
4194 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
4195 << sizeExpr->getSourceRange();
4196 Attr.setInvalid();
4197 break;
4198 }
4199}
4200
John Thompson6e132aa2009-12-04 21:51:28 +00004201/// HandleVectorSizeAttribute - this attribute is only applicable to integral
4202/// and float scalars, although arrays, pointers, and function return values are
4203/// allowed in conjunction with this construct. Aggregates with this attribute
4204/// are invalid, even if they are of the same size as a corresponding scalar.
4205/// The raw attribute should contain precisely 1 argument, the vector size for
4206/// the variable, measured in bytes. If curType and rawAttr are well formed,
4207/// this routine will return a new vector type.
Chris Lattner788b0fd2010-06-23 06:00:24 +00004208static void HandleVectorSizeAttr(QualType& CurType, const AttributeList &Attr,
4209 Sema &S) {
Bob Wilson56affbc2010-11-16 00:32:16 +00004210 // Check the attribute arguments.
John Thompson6e132aa2009-12-04 21:51:28 +00004211 if (Attr.getNumArgs() != 1) {
4212 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
Abramo Bagnarae215f722010-04-30 13:10:51 +00004213 Attr.setInvalid();
John Thompson6e132aa2009-12-04 21:51:28 +00004214 return;
4215 }
4216 Expr *sizeExpr = static_cast<Expr *>(Attr.getArg(0));
4217 llvm::APSInt vecSize(32);
Douglas Gregorac06a0e2010-05-18 23:01:22 +00004218 if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() ||
4219 !sizeExpr->isIntegerConstantExpr(vecSize, S.Context)) {
John Thompson6e132aa2009-12-04 21:51:28 +00004220 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
4221 << "vector_size" << sizeExpr->getSourceRange();
Abramo Bagnarae215f722010-04-30 13:10:51 +00004222 Attr.setInvalid();
John Thompson6e132aa2009-12-04 21:51:28 +00004223 return;
4224 }
4225 // the base type must be integer or float, and can't already be a vector.
Douglas Gregorf6094622010-07-23 15:58:24 +00004226 if (!CurType->isIntegerType() && !CurType->isRealFloatingType()) {
John Thompson6e132aa2009-12-04 21:51:28 +00004227 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
Abramo Bagnarae215f722010-04-30 13:10:51 +00004228 Attr.setInvalid();
John Thompson6e132aa2009-12-04 21:51:28 +00004229 return;
4230 }
4231 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
4232 // vecSize is specified in bytes - convert to bits.
4233 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
4234
4235 // the vector size needs to be an integral multiple of the type size.
4236 if (vectorSize % typeSize) {
4237 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
4238 << sizeExpr->getSourceRange();
Abramo Bagnarae215f722010-04-30 13:10:51 +00004239 Attr.setInvalid();
John Thompson6e132aa2009-12-04 21:51:28 +00004240 return;
4241 }
4242 if (vectorSize == 0) {
4243 S.Diag(Attr.getLoc(), diag::err_attribute_zero_size)
4244 << sizeExpr->getSourceRange();
Abramo Bagnarae215f722010-04-30 13:10:51 +00004245 Attr.setInvalid();
John Thompson6e132aa2009-12-04 21:51:28 +00004246 return;
4247 }
4248
4249 // Success! Instantiate the vector type, the number of elements is > 0, and
4250 // not required to be a power of 2, unlike GCC.
Chris Lattner788b0fd2010-06-23 06:00:24 +00004251 CurType = S.Context.getVectorType(CurType, vectorSize/typeSize,
Bob Wilsone86d78c2010-11-10 21:56:12 +00004252 VectorType::GenericVector);
John Thompson6e132aa2009-12-04 21:51:28 +00004253}
4254
Douglas Gregor4ac01402011-06-15 16:02:29 +00004255/// \brief Process the OpenCL-like ext_vector_type attribute when it occurs on
4256/// a type.
Chad Rosier91cbbbf2012-06-26 21:41:40 +00004257static void HandleExtVectorTypeAttr(QualType &CurType,
4258 const AttributeList &Attr,
Douglas Gregor4ac01402011-06-15 16:02:29 +00004259 Sema &S) {
4260 Expr *sizeExpr;
Chad Rosier91cbbbf2012-06-26 21:41:40 +00004261
Douglas Gregor4ac01402011-06-15 16:02:29 +00004262 // Special case where the argument is a template id.
4263 if (Attr.getParameterName()) {
4264 CXXScopeSpec SS;
Abramo Bagnarae4b92762012-01-27 09:46:47 +00004265 SourceLocation TemplateKWLoc;
Douglas Gregor4ac01402011-06-15 16:02:29 +00004266 UnqualifiedId id;
4267 id.setIdentifier(Attr.getParameterName(), Attr.getLoc());
Abramo Bagnarae4b92762012-01-27 09:46:47 +00004268
4269 ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, TemplateKWLoc,
4270 id, false, false);
Douglas Gregor4ac01402011-06-15 16:02:29 +00004271 if (Size.isInvalid())
4272 return;
Chad Rosier91cbbbf2012-06-26 21:41:40 +00004273
Douglas Gregor4ac01402011-06-15 16:02:29 +00004274 sizeExpr = Size.get();
4275 } else {
4276 // check the attribute arguments.
4277 if (Attr.getNumArgs() != 1) {
4278 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
4279 return;
4280 }
4281 sizeExpr = Attr.getArg(0);
4282 }
Chad Rosier91cbbbf2012-06-26 21:41:40 +00004283
Douglas Gregor4ac01402011-06-15 16:02:29 +00004284 // Create the vector type.
4285 QualType T = S.BuildExtVectorType(CurType, sizeExpr, Attr.getLoc());
4286 if (!T.isNull())
4287 CurType = T;
4288}
4289
Bob Wilson4211bb62010-11-16 00:32:24 +00004290/// HandleNeonVectorTypeAttr - The "neon_vector_type" and
4291/// "neon_polyvector_type" attributes are used to create vector types that
4292/// are mangled according to ARM's ABI. Otherwise, these types are identical
4293/// to those created with the "vector_size" attribute. Unlike "vector_size"
4294/// the argument to these Neon attributes is the number of vector elements,
4295/// not the vector size in bytes. The vector width and element type must
4296/// match one of the standard Neon vector types.
4297static void HandleNeonVectorTypeAttr(QualType& CurType,
4298 const AttributeList &Attr, Sema &S,
4299 VectorType::VectorKind VecKind,
4300 const char *AttrName) {
4301 // Check the attribute arguments.
4302 if (Attr.getNumArgs() != 1) {
4303 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
4304 Attr.setInvalid();
4305 return;
4306 }
4307 // The number of elements must be an ICE.
4308 Expr *numEltsExpr = static_cast<Expr *>(Attr.getArg(0));
4309 llvm::APSInt numEltsInt(32);
4310 if (numEltsExpr->isTypeDependent() || numEltsExpr->isValueDependent() ||
4311 !numEltsExpr->isIntegerConstantExpr(numEltsInt, S.Context)) {
4312 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
4313 << AttrName << numEltsExpr->getSourceRange();
4314 Attr.setInvalid();
4315 return;
4316 }
4317 // Only certain element types are supported for Neon vectors.
4318 const BuiltinType* BTy = CurType->getAs<BuiltinType>();
4319 if (!BTy ||
4320 (VecKind == VectorType::NeonPolyVector &&
4321 BTy->getKind() != BuiltinType::SChar &&
4322 BTy->getKind() != BuiltinType::Short) ||
4323 (BTy->getKind() != BuiltinType::SChar &&
4324 BTy->getKind() != BuiltinType::UChar &&
4325 BTy->getKind() != BuiltinType::Short &&
4326 BTy->getKind() != BuiltinType::UShort &&
4327 BTy->getKind() != BuiltinType::Int &&
4328 BTy->getKind() != BuiltinType::UInt &&
4329 BTy->getKind() != BuiltinType::LongLong &&
4330 BTy->getKind() != BuiltinType::ULongLong &&
4331 BTy->getKind() != BuiltinType::Float)) {
4332 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) <<CurType;
4333 Attr.setInvalid();
4334 return;
4335 }
4336 // The total size of the vector must be 64 or 128 bits.
4337 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
4338 unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue());
4339 unsigned vecSize = typeSize * numElts;
4340 if (vecSize != 64 && vecSize != 128) {
4341 S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType;
4342 Attr.setInvalid();
4343 return;
4344 }
4345
4346 CurType = S.Context.getVectorType(CurType, numElts, VecKind);
4347}
4348
John McCall711c52b2011-01-05 12:14:39 +00004349static void processTypeAttrs(TypeProcessingState &state, QualType &type,
Richard Smithf7a05272013-01-14 07:53:01 +00004350 TypeAttrLocation TAL, AttributeList *attrs) {
Chris Lattner232e8822008-02-21 01:08:11 +00004351 // Scan through and apply attributes to this type where it makes sense. Some
4352 // attributes (such as __address_space__, __vector_size__, etc) apply to the
4353 // type, but others can be present in the type specifiers even though they
Chris Lattnerfca0ddd2008-06-26 06:27:57 +00004354 // apply to the decl. Here we apply type attributes and ignore the rest.
John McCall711c52b2011-01-05 12:14:39 +00004355
4356 AttributeList *next;
4357 do {
4358 AttributeList &attr = *attrs;
4359 next = attr.getNext();
4360
Abramo Bagnarae215f722010-04-30 13:10:51 +00004361 // Skip attributes that were marked to be invalid.
John McCall711c52b2011-01-05 12:14:39 +00004362 if (attr.isInvalid())
Abramo Bagnarae215f722010-04-30 13:10:51 +00004363 continue;
4364
Richard Smithcd8ab512013-01-17 01:30:42 +00004365 if (attr.isCXX11Attribute()) {
4366 // [[gnu::...]] attributes are treated as declaration attributes, so may
4367 // not appertain to a DeclaratorChunk, even if we handle them as type
4368 // attributes.
4369 if (attr.getScopeName() && attr.getScopeName()->isStr("gnu")) {
4370 if (TAL == TAL_DeclChunk) {
4371 state.getSema().Diag(attr.getLoc(),
4372 diag::warn_cxx11_gnu_attribute_on_type)
4373 << attr.getName();
4374 continue;
4375 }
4376 } else if (TAL != TAL_DeclChunk) {
4377 // Otherwise, only consider type processing for a C++11 attribute if
4378 // it's actually been applied to a type.
4379 continue;
4380 }
Richard Smithf7a05272013-01-14 07:53:01 +00004381 }
4382
Abramo Bagnarab1f1b262010-04-30 09:13:03 +00004383 // If this is an attribute we can handle, do so now,
4384 // otherwise, add it to the FnAttrs list for rechaining.
John McCall711c52b2011-01-05 12:14:39 +00004385 switch (attr.getKind()) {
Richard Smithcd8ab512013-01-17 01:30:42 +00004386 default:
4387 // A C++11 attribute on a declarator chunk must appertain to a type.
Richard Smithd03de6a2013-01-29 10:02:16 +00004388 if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk) {
Richard Smithcd8ab512013-01-17 01:30:42 +00004389 state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr)
Richard Smithd03de6a2013-01-29 10:02:16 +00004390 << attr.getName();
4391 attr.setUsedAsTypeAttr();
4392 }
Richard Smithcd8ab512013-01-17 01:30:42 +00004393 break;
4394
4395 case AttributeList::UnknownAttribute:
4396 if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk)
4397 state.getSema().Diag(attr.getLoc(),
4398 diag::warn_unknown_attribute_ignored)
4399 << attr.getName();
4400 break;
4401
4402 case AttributeList::IgnoredAttribute:
4403 break;
John McCall04a67a62010-02-05 21:31:56 +00004404
Sean Hunt8e083e72012-06-19 23:57:03 +00004405 case AttributeList::AT_MayAlias:
Chandler Carruth682eae22011-10-07 18:40:27 +00004406 // FIXME: This attribute needs to actually be handled, but if we ignore
4407 // it it breaks large amounts of Linux software.
4408 attr.setUsedAsTypeAttr();
4409 break;
Sean Hunt8e083e72012-06-19 23:57:03 +00004410 case AttributeList::AT_AddressSpace:
John McCall711c52b2011-01-05 12:14:39 +00004411 HandleAddressSpaceTypeAttribute(type, attr, state.getSema());
John McCalle82247a2011-10-01 05:17:03 +00004412 attr.setUsedAsTypeAttr();
Chris Lattnerc9b346d2008-06-29 00:50:08 +00004413 break;
John McCall711c52b2011-01-05 12:14:39 +00004414 OBJC_POINTER_TYPE_ATTRS_CASELIST:
4415 if (!handleObjCPointerTypeAttr(state, attr, type))
4416 distributeObjCPointerTypeAttr(state, attr, type);
John McCalle82247a2011-10-01 05:17:03 +00004417 attr.setUsedAsTypeAttr();
Mike Stump24556362009-07-25 21:26:53 +00004418 break;
Sean Hunt8e083e72012-06-19 23:57:03 +00004419 case AttributeList::AT_VectorSize:
John McCall711c52b2011-01-05 12:14:39 +00004420 HandleVectorSizeAttr(type, attr, state.getSema());
John McCalle82247a2011-10-01 05:17:03 +00004421 attr.setUsedAsTypeAttr();
John McCall04a67a62010-02-05 21:31:56 +00004422 break;
Sean Hunt8e083e72012-06-19 23:57:03 +00004423 case AttributeList::AT_ExtVectorType:
Richard Smitha4fa9002013-01-13 02:11:23 +00004424 HandleExtVectorTypeAttr(type, attr, state.getSema());
John McCalle82247a2011-10-01 05:17:03 +00004425 attr.setUsedAsTypeAttr();
Douglas Gregor4ac01402011-06-15 16:02:29 +00004426 break;
Sean Hunt8e083e72012-06-19 23:57:03 +00004427 case AttributeList::AT_NeonVectorType:
John McCall711c52b2011-01-05 12:14:39 +00004428 HandleNeonVectorTypeAttr(type, attr, state.getSema(),
4429 VectorType::NeonVector, "neon_vector_type");
John McCalle82247a2011-10-01 05:17:03 +00004430 attr.setUsedAsTypeAttr();
Bob Wilson4211bb62010-11-16 00:32:24 +00004431 break;
Sean Hunt8e083e72012-06-19 23:57:03 +00004432 case AttributeList::AT_NeonPolyVectorType:
John McCall711c52b2011-01-05 12:14:39 +00004433 HandleNeonVectorTypeAttr(type, attr, state.getSema(),
4434 VectorType::NeonPolyVector,
Bob Wilson4211bb62010-11-16 00:32:24 +00004435 "neon_polyvector_type");
John McCalle82247a2011-10-01 05:17:03 +00004436 attr.setUsedAsTypeAttr();
Bob Wilson4211bb62010-11-16 00:32:24 +00004437 break;
Sean Hunt8e083e72012-06-19 23:57:03 +00004438 case AttributeList::AT_OpenCLImageAccess:
Peter Collingbourne207f4d82011-03-18 22:38:29 +00004439 HandleOpenCLImageAccessAttribute(type, attr, state.getSema());
John McCalle82247a2011-10-01 05:17:03 +00004440 attr.setUsedAsTypeAttr();
Peter Collingbourne207f4d82011-03-18 22:38:29 +00004441 break;
4442
Richard Smithd03de6a2013-01-29 10:02:16 +00004443 case AttributeList::AT_Win64:
4444 case AttributeList::AT_Ptr32:
4445 case AttributeList::AT_Ptr64:
4446 // FIXME: Don't ignore these. We have partial handling for them as
4447 // declaration attributes in SemaDeclAttr.cpp; that should be moved here.
4448 attr.setUsedAsTypeAttr();
4449 break;
4450
Sean Hunt8e083e72012-06-19 23:57:03 +00004451 case AttributeList::AT_NSReturnsRetained:
David Blaikie4e4d0842012-03-11 07:00:24 +00004452 if (!state.getSema().getLangOpts().ObjCAutoRefCount)
Richard Smithcd8ab512013-01-17 01:30:42 +00004453 break;
John McCallf85e1932011-06-15 23:02:42 +00004454 // fallthrough into the function attrs
4455
John McCall711c52b2011-01-05 12:14:39 +00004456 FUNCTION_TYPE_ATTRS_CASELIST:
John McCalle82247a2011-10-01 05:17:03 +00004457 attr.setUsedAsTypeAttr();
4458
John McCall711c52b2011-01-05 12:14:39 +00004459 // Never process function type attributes as part of the
4460 // declaration-specifiers.
Richard Smithf7a05272013-01-14 07:53:01 +00004461 if (TAL == TAL_DeclSpec)
John McCall711c52b2011-01-05 12:14:39 +00004462 distributeFunctionTypeAttrFromDeclSpec(state, attr, type);
4463
4464 // Otherwise, handle the possible delays.
4465 else if (!handleFunctionTypeAttr(state, attr, type))
4466 distributeFunctionTypeAttr(state, attr, type);
John Thompson6e132aa2009-12-04 21:51:28 +00004467 break;
Chris Lattner232e8822008-02-21 01:08:11 +00004468 }
John McCall711c52b2011-01-05 12:14:39 +00004469 } while ((attrs = next));
Chris Lattner232e8822008-02-21 01:08:11 +00004470}
4471
Chandler Carruthe4d645c2011-05-27 01:33:31 +00004472/// \brief Ensure that the type of the given expression is complete.
4473///
4474/// This routine checks whether the expression \p E has a complete type. If the
4475/// expression refers to an instantiable construct, that instantiation is
4476/// performed as needed to complete its type. Furthermore
4477/// Sema::RequireCompleteType is called for the expression's type (or in the
4478/// case of a reference type, the referred-to type).
4479///
4480/// \param E The expression whose type is required to be complete.
Douglas Gregord10099e2012-05-04 16:32:21 +00004481/// \param Diagnoser The object that will emit a diagnostic if the type is
4482/// incomplete.
Chandler Carruthe4d645c2011-05-27 01:33:31 +00004483///
4484/// \returns \c true if the type of \p E is incomplete and diagnosed, \c false
4485/// otherwise.
Douglas Gregorf502d8e2012-05-04 16:48:41 +00004486bool Sema::RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser){
Chandler Carruthe4d645c2011-05-27 01:33:31 +00004487 QualType T = E->getType();
4488
4489 // Fast path the case where the type is already complete.
4490 if (!T->isIncompleteType())
4491 return false;
4492
4493 // Incomplete array types may be completed by the initializer attached to
4494 // their definitions. For static data members of class templates we need to
4495 // instantiate the definition to get this initializer and complete the type.
4496 if (T->isIncompleteArrayType()) {
4497 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4498 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
4499 if (Var->isStaticDataMember() &&
4500 Var->getInstantiatedFromStaticDataMember()) {
Chad Rosier91cbbbf2012-06-26 21:41:40 +00004501
Douglas Gregor36f255c2011-06-03 14:28:43 +00004502 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
4503 assert(MSInfo && "Missing member specialization information?");
4504 if (MSInfo->getTemplateSpecializationKind()
4505 != TSK_ExplicitSpecialization) {
4506 // If we don't already have a point of instantiation, this is it.
4507 if (MSInfo->getPointOfInstantiation().isInvalid()) {
4508 MSInfo->setPointOfInstantiation(E->getLocStart());
Chad Rosier91cbbbf2012-06-26 21:41:40 +00004509
4510 // This is a modification of an existing AST node. Notify
Douglas Gregor36f255c2011-06-03 14:28:43 +00004511 // listeners.
4512 if (ASTMutationListener *L = getASTMutationListener())
4513 L->StaticDataMemberInstantiated(Var);
4514 }
Chad Rosier91cbbbf2012-06-26 21:41:40 +00004515
Douglas Gregor36f255c2011-06-03 14:28:43 +00004516 InstantiateStaticDataMemberDefinition(E->getExprLoc(), Var);
Chad Rosier91cbbbf2012-06-26 21:41:40 +00004517
Douglas Gregor36f255c2011-06-03 14:28:43 +00004518 // Update the type to the newly instantiated definition's type both
4519 // here and within the expression.
4520 if (VarDecl *Def = Var->getDefinition()) {
4521 DRE->setDecl(Def);
4522 T = Def->getType();
4523 DRE->setType(T);
4524 E->setType(T);
4525 }
Douglas Gregorf15748a2011-06-03 03:35:07 +00004526 }
Chad Rosier91cbbbf2012-06-26 21:41:40 +00004527
Chandler Carruthe4d645c2011-05-27 01:33:31 +00004528 // We still go on to try to complete the type independently, as it
4529 // may also require instantiations or diagnostics if it remains
4530 // incomplete.
4531 }
4532 }
4533 }
4534 }
4535
4536 // FIXME: Are there other cases which require instantiating something other
4537 // than the type to complete the type of an expression?
4538
4539 // Look through reference types and complete the referred type.
4540 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
4541 T = Ref->getPointeeType();
4542
Douglas Gregord10099e2012-05-04 16:32:21 +00004543 return RequireCompleteType(E->getExprLoc(), T, Diagnoser);
4544}
4545
4546namespace {
Douglas Gregorf502d8e2012-05-04 16:48:41 +00004547 struct TypeDiagnoserDiag : Sema::TypeDiagnoser {
Douglas Gregord10099e2012-05-04 16:32:21 +00004548 unsigned DiagID;
Chad Rosier91cbbbf2012-06-26 21:41:40 +00004549
Douglas Gregorf502d8e2012-05-04 16:48:41 +00004550 TypeDiagnoserDiag(unsigned DiagID)
4551 : Sema::TypeDiagnoser(DiagID == 0), DiagID(DiagID) {}
Chad Rosier91cbbbf2012-06-26 21:41:40 +00004552
Douglas Gregord10099e2012-05-04 16:32:21 +00004553 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
4554 if (Suppressed) return;
4555 S.Diag(Loc, DiagID) << T;
4556 }
4557 };
4558}
4559
4560bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) {
Douglas Gregorf502d8e2012-05-04 16:48:41 +00004561 TypeDiagnoserDiag Diagnoser(DiagID);
Douglas Gregord10099e2012-05-04 16:32:21 +00004562 return RequireCompleteExprType(E, Diagnoser);
Chandler Carruthe4d645c2011-05-27 01:33:31 +00004563}
4564
Mike Stump1eb44332009-09-09 15:08:12 +00004565/// @brief Ensure that the type T is a complete type.
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004566///
4567/// This routine checks whether the type @p T is complete in any
4568/// context where a complete type is required. If @p T is a complete
Douglas Gregor86447ec2009-03-09 16:13:40 +00004569/// type, returns false. If @p T is a class template specialization,
4570/// this routine then attempts to perform class template
4571/// instantiation. If instantiation fails, or if @p T is incomplete
4572/// and cannot be completed, issues the diagnostic @p diag (giving it
4573/// the type @p T) and returns true.
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004574///
4575/// @param Loc The location in the source that the incomplete type
4576/// diagnostic should refer to.
4577///
4578/// @param T The type that this routine is examining for completeness.
4579///
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004580/// @returns @c true if @p T is incomplete and a diagnostic was emitted,
4581/// @c false otherwise.
Anders Carlsson91a0cc92009-08-26 22:33:56 +00004582bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
Douglas Gregorf502d8e2012-05-04 16:48:41 +00004583 TypeDiagnoser &Diagnoser) {
Douglas Gregor573d9c32009-10-21 23:19:44 +00004584 // FIXME: Add this assertion to make sure we always get instantiation points.
4585 // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
Douglas Gregor690dc7f2009-05-21 23:48:18 +00004586 // FIXME: Add this assertion to help us flush out problems with
4587 // checking for dependent types and type-dependent expressions.
4588 //
Mike Stump1eb44332009-09-09 15:08:12 +00004589 // assert(!T->isDependentType() &&
Douglas Gregor690dc7f2009-05-21 23:48:18 +00004590 // "Can't ask whether a dependent type is complete");
4591
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004592 // If we have a complete type, we're done.
Douglas Gregord07cc362012-01-02 17:18:37 +00004593 NamedDecl *Def = 0;
4594 if (!T->isIncompleteType(&Def)) {
4595 // If we know about the definition but it is not visible, complain.
Douglas Gregord10099e2012-05-04 16:32:21 +00004596 if (!Diagnoser.Suppressed && Def && !LookupResult::isVisible(Def)) {
Douglas Gregord07cc362012-01-02 17:18:37 +00004597 // Suppress this error outside of a SFINAE context if we've already
Chad Rosier91cbbbf2012-06-26 21:41:40 +00004598 // emitted the error once for this type. There's no usefulness in
Douglas Gregord07cc362012-01-02 17:18:37 +00004599 // repeating the diagnostic.
4600 // FIXME: Add a Fix-It that imports the corresponding module or includes
4601 // the header.
Douglas Gregorca2ab452013-01-12 01:29:50 +00004602 Module *Owner = Def->getOwningModule();
4603 Diag(Loc, diag::err_module_private_definition)
4604 << T << Owner->getFullModuleName();
4605 Diag(Def->getLocation(), diag::note_previous_definition);
4606
4607 if (!isSFINAEContext()) {
4608 // Recover by implicitly importing this module.
4609 createImplicitModuleImport(Loc, Owner);
Douglas Gregord07cc362012-01-02 17:18:37 +00004610 }
4611 }
Chad Rosier91cbbbf2012-06-26 21:41:40 +00004612
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004613 return false;
Douglas Gregord07cc362012-01-02 17:18:37 +00004614 }
Eli Friedman3c0eb162008-05-27 03:33:27 +00004615
Sean Callananbd791192011-12-16 00:20:31 +00004616 const TagType *Tag = T->getAs<TagType>();
4617 const ObjCInterfaceType *IFace = 0;
Chad Rosier91cbbbf2012-06-26 21:41:40 +00004618
Sean Callananbd791192011-12-16 00:20:31 +00004619 if (Tag) {
4620 // Avoid diagnosing invalid decls as incomplete.
4621 if (Tag->getDecl()->isInvalidDecl())
4622 return true;
4623
4624 // Give the external AST source a chance to complete the type.
4625 if (Tag->getDecl()->hasExternalLexicalStorage()) {
4626 Context.getExternalSource()->CompleteType(Tag->getDecl());
4627 if (!Tag->isIncompleteType())
4628 return false;
4629 }
4630 }
4631 else if ((IFace = T->getAs<ObjCInterfaceType>())) {
4632 // Avoid diagnosing invalid decls as incomplete.
4633 if (IFace->getDecl()->isInvalidDecl())
4634 return true;
Chad Rosier91cbbbf2012-06-26 21:41:40 +00004635
Sean Callananbd791192011-12-16 00:20:31 +00004636 // Give the external AST source a chance to complete the type.
4637 if (IFace->getDecl()->hasExternalLexicalStorage()) {
4638 Context.getExternalSource()->CompleteType(IFace->getDecl());
4639 if (!IFace->isIncompleteType())
4640 return false;
4641 }
4642 }
Chad Rosier91cbbbf2012-06-26 21:41:40 +00004643
Douglas Gregord475b8d2009-03-25 21:17:03 +00004644 // If we have a class template specialization or a class member of a
Sebastian Redl923d56d2009-11-05 15:52:31 +00004645 // class template specialization, or an array with known size of such,
4646 // try to instantiate it.
4647 QualType MaybeTemplate = T;
Douglas Gregore656b832012-04-23 16:42:52 +00004648 while (const ConstantArrayType *Array
4649 = Context.getAsConstantArrayType(MaybeTemplate))
Sebastian Redl923d56d2009-11-05 15:52:31 +00004650 MaybeTemplate = Array->getElementType();
4651 if (const RecordType *Record = MaybeTemplate->getAs<RecordType>()) {
Douglas Gregor2943aed2009-03-03 04:44:36 +00004652 if (ClassTemplateSpecializationDecl *ClassTemplateSpec
Douglas Gregord475b8d2009-03-25 21:17:03 +00004653 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
Douglas Gregor972e6ce2009-10-27 06:26:26 +00004654 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared)
4655 return InstantiateClassTemplateSpecialization(Loc, ClassTemplateSpec,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00004656 TSK_ImplicitInstantiation,
Douglas Gregord10099e2012-05-04 16:32:21 +00004657 /*Complain=*/!Diagnoser.Suppressed);
Mike Stump1eb44332009-09-09 15:08:12 +00004658 } else if (CXXRecordDecl *Rec
Douglas Gregord475b8d2009-03-25 21:17:03 +00004659 = dyn_cast<CXXRecordDecl>(Record->getDecl())) {
Richard Smith564f4c52012-03-22 03:35:28 +00004660 CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass();
4661 if (!Rec->isBeingDefined() && Pattern) {
4662 MemberSpecializationInfo *MSI = Rec->getMemberSpecializationInfo();
4663 assert(MSI && "Missing member specialization information?");
Douglas Gregor357bbd02009-08-28 20:50:45 +00004664 // This record was instantiated from a class within a template.
Richard Smith564f4c52012-03-22 03:35:28 +00004665 if (MSI->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregorf6b11852009-10-08 15:14:33 +00004666 return InstantiateClass(Loc, Rec, Pattern,
4667 getTemplateInstantiationArgs(Rec),
4668 TSK_ImplicitInstantiation,
Douglas Gregord10099e2012-05-04 16:32:21 +00004669 /*Complain=*/!Diagnoser.Suppressed);
Douglas Gregord475b8d2009-03-25 21:17:03 +00004670 }
4671 }
4672 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00004673
Douglas Gregord10099e2012-05-04 16:32:21 +00004674 if (Diagnoser.Suppressed)
Douglas Gregor5842ba92009-08-24 15:23:48 +00004675 return true;
Douglas Gregord10099e2012-05-04 16:32:21 +00004676
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004677 // We have an incomplete type. Produce a diagnostic.
Douglas Gregord10099e2012-05-04 16:32:21 +00004678 Diagnoser.diagnose(*this, Loc, T);
Chad Rosier91cbbbf2012-06-26 21:41:40 +00004679
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004680 // If the type was a forward declaration of a class/struct/union
Rafael Espindola01620702010-03-21 22:56:43 +00004681 // type, produce a note.
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004682 if (Tag && !Tag->getDecl()->isInvalidDecl())
Mike Stump1eb44332009-09-09 15:08:12 +00004683 Diag(Tag->getDecl()->getLocation(),
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004684 Tag->isBeingDefined() ? diag::note_type_being_defined
4685 : diag::note_forward_declaration)
Douglas Gregorb3029962011-11-14 22:10:01 +00004686 << QualType(Tag, 0);
Chad Rosier91cbbbf2012-06-26 21:41:40 +00004687
Douglas Gregorb3029962011-11-14 22:10:01 +00004688 // If the Objective-C class was a forward declaration, produce a note.
4689 if (IFace && !IFace->getDecl()->isInvalidDecl())
4690 Diag(IFace->getDecl()->getLocation(), diag::note_forward_class);
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004691
4692 return true;
4693}
Douglas Gregore6258932009-03-19 00:39:20 +00004694
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004695bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
Chad Rosier91cbbbf2012-06-26 21:41:40 +00004696 unsigned DiagID) {
Douglas Gregorf502d8e2012-05-04 16:48:41 +00004697 TypeDiagnoserDiag Diagnoser(DiagID);
Douglas Gregord10099e2012-05-04 16:32:21 +00004698 return RequireCompleteType(Loc, T, Diagnoser);
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004699}
4700
Joao Matos6666ed42012-08-31 18:45:21 +00004701/// \brief Get diagnostic %select index for tag kind for
4702/// literal type diagnostic message.
4703/// WARNING: Indexes apply to particular diagnostics only!
4704///
4705/// \returns diagnostic %select index.
Joao Matosf143ae92012-09-01 00:13:24 +00004706static unsigned getLiteralDiagFromTagKind(TagTypeKind Tag) {
Joao Matos6666ed42012-08-31 18:45:21 +00004707 switch (Tag) {
Joao Matosf143ae92012-09-01 00:13:24 +00004708 case TTK_Struct: return 0;
4709 case TTK_Interface: return 1;
4710 case TTK_Class: return 2;
4711 default: llvm_unreachable("Invalid tag kind for literal type diagnostic!");
Joao Matos6666ed42012-08-31 18:45:21 +00004712 }
Joao Matos6666ed42012-08-31 18:45:21 +00004713}
4714
Richard Smith9f569cc2011-10-01 02:31:28 +00004715/// @brief Ensure that the type T is a literal type.
4716///
4717/// This routine checks whether the type @p T is a literal type. If @p T is an
4718/// incomplete type, an attempt is made to complete it. If @p T is a literal
4719/// type, or @p AllowIncompleteType is true and @p T is an incomplete type,
4720/// returns false. Otherwise, this routine issues the diagnostic @p PD (giving
4721/// it the type @p T), along with notes explaining why the type is not a
4722/// literal type, and returns true.
4723///
4724/// @param Loc The location in the source that the non-literal type
4725/// diagnostic should refer to.
4726///
4727/// @param T The type that this routine is examining for literalness.
4728///
Douglas Gregorf502d8e2012-05-04 16:48:41 +00004729/// @param Diagnoser Emits a diagnostic if T is not a literal type.
Richard Smith9f569cc2011-10-01 02:31:28 +00004730///
Richard Smith9f569cc2011-10-01 02:31:28 +00004731/// @returns @c true if @p T is not a literal type and a diagnostic was emitted,
4732/// @c false otherwise.
4733bool Sema::RequireLiteralType(SourceLocation Loc, QualType T,
Douglas Gregorf502d8e2012-05-04 16:48:41 +00004734 TypeDiagnoser &Diagnoser) {
Richard Smith9f569cc2011-10-01 02:31:28 +00004735 assert(!T->isDependentType() && "type should not be dependent");
4736
Eli Friedmanee065392012-02-20 23:58:14 +00004737 QualType ElemType = Context.getBaseElementType(T);
4738 RequireCompleteType(Loc, ElemType, 0);
4739
Richard Smith86c3ae42012-02-13 03:54:03 +00004740 if (T->isLiteralType())
Richard Smith9f569cc2011-10-01 02:31:28 +00004741 return false;
4742
Douglas Gregorf502d8e2012-05-04 16:48:41 +00004743 if (Diagnoser.Suppressed)
Richard Smith9f569cc2011-10-01 02:31:28 +00004744 return true;
4745
Douglas Gregorf502d8e2012-05-04 16:48:41 +00004746 Diagnoser.diagnose(*this, Loc, T);
Richard Smith9f569cc2011-10-01 02:31:28 +00004747
4748 if (T->isVariableArrayType())
4749 return true;
4750
Eli Friedmanee065392012-02-20 23:58:14 +00004751 const RecordType *RT = ElemType->getAs<RecordType>();
Richard Smith9f569cc2011-10-01 02:31:28 +00004752 if (!RT)
4753 return true;
4754
4755 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4756
Richard Smithc799a6a2012-04-25 23:23:48 +00004757 // A partially-defined class type can't be a literal type, because a literal
4758 // class type must have a trivial destructor (which can't be checked until
4759 // the class definition is complete).
4760 if (!RD->isCompleteDefinition()) {
Douglas Gregord10099e2012-05-04 16:32:21 +00004761 RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T);
Eli Friedmanee065392012-02-20 23:58:14 +00004762 return true;
Richard Smithc799a6a2012-04-25 23:23:48 +00004763 }
Eli Friedmanee065392012-02-20 23:58:14 +00004764
Richard Smith9f569cc2011-10-01 02:31:28 +00004765 // If the class has virtual base classes, then it's not an aggregate, and
Richard Smith86c3ae42012-02-13 03:54:03 +00004766 // cannot have any constexpr constructors or a trivial default constructor,
4767 // so is non-literal. This is better to diagnose than the resulting absence
4768 // of constexpr constructors.
Richard Smith9f569cc2011-10-01 02:31:28 +00004769 if (RD->getNumVBases()) {
4770 Diag(RD->getLocation(), diag::note_non_literal_virtual_base)
Joao Matos6666ed42012-08-31 18:45:21 +00004771 << getLiteralDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
Richard Smith9f569cc2011-10-01 02:31:28 +00004772 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
4773 E = RD->vbases_end(); I != E; ++I)
Daniel Dunbar96a00142012-03-09 18:35:03 +00004774 Diag(I->getLocStart(),
Richard Smith9f569cc2011-10-01 02:31:28 +00004775 diag::note_constexpr_virtual_base_here) << I->getSourceRange();
Richard Smith86c3ae42012-02-13 03:54:03 +00004776 } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() &&
4777 !RD->hasTrivialDefaultConstructor()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00004778 Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD;
Richard Smith9f569cc2011-10-01 02:31:28 +00004779 } else if (RD->hasNonLiteralTypeFieldsOrBases()) {
4780 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4781 E = RD->bases_end(); I != E; ++I) {
4782 if (!I->getType()->isLiteralType()) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00004783 Diag(I->getLocStart(),
Richard Smith9f569cc2011-10-01 02:31:28 +00004784 diag::note_non_literal_base_class)
4785 << RD << I->getType() << I->getSourceRange();
4786 return true;
4787 }
4788 }
4789 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
4790 E = RD->field_end(); I != E; ++I) {
David Blaikie262bc182012-04-30 02:36:29 +00004791 if (!I->getType()->isLiteralType() ||
4792 I->getType().isVolatileQualified()) {
4793 Diag(I->getLocation(), diag::note_non_literal_field)
David Blaikie581deb32012-06-06 20:45:41 +00004794 << RD << *I << I->getType()
David Blaikie262bc182012-04-30 02:36:29 +00004795 << I->getType().isVolatileQualified();
Richard Smith9f569cc2011-10-01 02:31:28 +00004796 return true;
4797 }
4798 }
4799 } else if (!RD->hasTrivialDestructor()) {
4800 // All fields and bases are of literal types, so have trivial destructors.
4801 // If this class's destructor is non-trivial it must be user-declared.
4802 CXXDestructorDecl *Dtor = RD->getDestructor();
4803 assert(Dtor && "class has literal fields and bases but no dtor?");
4804 if (!Dtor)
4805 return true;
4806
4807 Diag(Dtor->getLocation(), Dtor->isUserProvided() ?
4808 diag::note_non_literal_user_provided_dtor :
4809 diag::note_non_literal_nontrivial_dtor) << RD;
Richard Smithac713512012-12-08 02:53:02 +00004810 if (!Dtor->isUserProvided())
4811 SpecialMemberIsTrivial(Dtor, CXXDestructor, /*Diagnose*/true);
Richard Smith9f569cc2011-10-01 02:31:28 +00004812 }
4813
4814 return true;
4815}
4816
Chad Rosier91cbbbf2012-06-26 21:41:40 +00004817bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) {
Douglas Gregorf502d8e2012-05-04 16:48:41 +00004818 TypeDiagnoserDiag Diagnoser(DiagID);
4819 return RequireLiteralType(Loc, T, Diagnoser);
4820}
4821
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004822/// \brief Retrieve a version of the type 'T' that is elaborated by Keyword
4823/// and qualified by the nested-name-specifier contained in SS.
4824QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword,
4825 const CXXScopeSpec &SS, QualType T) {
4826 if (T.isNull())
Douglas Gregore6258932009-03-19 00:39:20 +00004827 return T;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004828 NestedNameSpecifier *NNS;
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00004829 if (SS.isValid())
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004830 NNS = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4831 else {
4832 if (Keyword == ETK_None)
4833 return T;
4834 NNS = 0;
4835 }
4836 return Context.getElaboratedType(Keyword, NNS, T);
Douglas Gregore6258932009-03-19 00:39:20 +00004837}
Anders Carlssonaf017e62009-06-29 22:58:55 +00004838
John McCall2a984ca2010-10-12 00:20:44 +00004839QualType Sema::BuildTypeofExprType(Expr *E, SourceLocation Loc) {
John McCallfb8721c2011-04-10 19:13:55 +00004840 ExprResult ER = CheckPlaceholderExpr(E);
John McCall2a984ca2010-10-12 00:20:44 +00004841 if (ER.isInvalid()) return QualType();
4842 E = ER.take();
4843
Fariborz Jahanian2b1d51b2010-10-05 23:24:00 +00004844 if (!E->isTypeDependent()) {
4845 QualType T = E->getType();
Fariborz Jahanianaca7f7b2010-10-06 00:23:25 +00004846 if (const TagType *TT = T->getAs<TagType>())
4847 DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc());
Fariborz Jahanian2b1d51b2010-10-05 23:24:00 +00004848 }
Anders Carlssonaf017e62009-06-29 22:58:55 +00004849 return Context.getTypeOfExprType(E);
4850}
4851
Douglas Gregorf8af9822012-02-12 18:42:33 +00004852/// getDecltypeForExpr - Given an expr, will return the decltype for
4853/// that expression, according to the rules in C++11
4854/// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18.
4855static QualType getDecltypeForExpr(Sema &S, Expr *E) {
4856 if (E->isTypeDependent())
4857 return S.Context.DependentTy;
4858
Douglas Gregor6d9ef302012-02-12 18:57:57 +00004859 // C++11 [dcl.type.simple]p4:
4860 // The type denoted by decltype(e) is defined as follows:
4861 //
4862 // - if e is an unparenthesized id-expression or an unparenthesized class
Chad Rosier91cbbbf2012-06-26 21:41:40 +00004863 // member access (5.2.5), decltype(e) is the type of the entity named
4864 // by e. If there is no such entity, or if e names a set of overloaded
Douglas Gregor6d9ef302012-02-12 18:57:57 +00004865 // functions, the program is ill-formed;
Douglas Gregor84dd82e2012-09-13 23:40:46 +00004866 //
4867 // We apply the same rules for Objective-C ivar and property references.
Douglas Gregorf8af9822012-02-12 18:42:33 +00004868 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
4869 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
4870 return VD->getType();
Douglas Gregor84dd82e2012-09-13 23:40:46 +00004871 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
Douglas Gregorf8af9822012-02-12 18:42:33 +00004872 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
4873 return FD->getType();
Douglas Gregor84dd82e2012-09-13 23:40:46 +00004874 } else if (const ObjCIvarRefExpr *IR = dyn_cast<ObjCIvarRefExpr>(E)) {
4875 return IR->getDecl()->getType();
4876 } else if (const ObjCPropertyRefExpr *PR = dyn_cast<ObjCPropertyRefExpr>(E)) {
4877 if (PR->isExplicitProperty())
4878 return PR->getExplicitProperty()->getType();
Douglas Gregorf8af9822012-02-12 18:42:33 +00004879 }
Douglas Gregor84dd82e2012-09-13 23:40:46 +00004880
Douglas Gregorf8af9822012-02-12 18:42:33 +00004881 // C++11 [expr.lambda.prim]p18:
4882 // Every occurrence of decltype((x)) where x is a possibly
4883 // parenthesized id-expression that names an entity of automatic
4884 // storage duration is treated as if x were transformed into an
4885 // access to a corresponding data member of the closure type that
4886 // would have been declared if x were an odr-use of the denoted
4887 // entity.
4888 using namespace sema;
4889 if (S.getCurLambda()) {
4890 if (isa<ParenExpr>(E)) {
4891 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4892 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
Douglas Gregor68932842012-02-18 05:51:20 +00004893 QualType T = S.getCapturedDeclRefType(Var, DRE->getLocation());
4894 if (!T.isNull())
4895 return S.Context.getLValueReferenceType(T);
Douglas Gregorf8af9822012-02-12 18:42:33 +00004896 }
4897 }
4898 }
4899 }
4900
Douglas Gregor6d9ef302012-02-12 18:57:57 +00004901
4902 // C++11 [dcl.type.simple]p4:
4903 // [...]
Douglas Gregorf8af9822012-02-12 18:42:33 +00004904 QualType T = E->getType();
Douglas Gregor6d9ef302012-02-12 18:57:57 +00004905 switch (E->getValueKind()) {
Chad Rosier91cbbbf2012-06-26 21:41:40 +00004906 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
Douglas Gregor6d9ef302012-02-12 18:57:57 +00004907 // type of e;
4908 case VK_XValue: T = S.Context.getRValueReferenceType(T); break;
Chad Rosier91cbbbf2012-06-26 21:41:40 +00004909 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
Douglas Gregor6d9ef302012-02-12 18:57:57 +00004910 // type of e;
4911 case VK_LValue: T = S.Context.getLValueReferenceType(T); break;
4912 // - otherwise, decltype(e) is the type of e.
4913 case VK_RValue: break;
4914 }
Chad Rosier91cbbbf2012-06-26 21:41:40 +00004915
Douglas Gregorf8af9822012-02-12 18:42:33 +00004916 return T;
4917}
4918
John McCall2a984ca2010-10-12 00:20:44 +00004919QualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc) {
John McCallfb8721c2011-04-10 19:13:55 +00004920 ExprResult ER = CheckPlaceholderExpr(E);
John McCall2a984ca2010-10-12 00:20:44 +00004921 if (ER.isInvalid()) return QualType();
4922 E = ER.take();
Chad Rosier91cbbbf2012-06-26 21:41:40 +00004923
Douglas Gregorf8af9822012-02-12 18:42:33 +00004924 return Context.getDecltypeType(E, getDecltypeForExpr(*this, E));
Anders Carlssonaf017e62009-06-29 22:58:55 +00004925}
Sean Huntca63c202011-05-24 22:41:36 +00004926
4927QualType Sema::BuildUnaryTransformType(QualType BaseType,
4928 UnaryTransformType::UTTKind UKind,
4929 SourceLocation Loc) {
4930 switch (UKind) {
4931 case UnaryTransformType::EnumUnderlyingType:
4932 if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) {
4933 Diag(Loc, diag::err_only_enums_have_underlying_types);
4934 return QualType();
4935 } else {
4936 QualType Underlying = BaseType;
4937 if (!BaseType->isDependentType()) {
4938 EnumDecl *ED = BaseType->getAs<EnumType>()->getDecl();
4939 assert(ED && "EnumType has no EnumDecl");
4940 DiagnoseUseOfDecl(ED, Loc);
4941 Underlying = ED->getIntegerType();
4942 }
4943 assert(!Underlying.isNull());
4944 return Context.getUnaryTransformType(BaseType, Underlying,
4945 UnaryTransformType::EnumUnderlyingType);
4946 }
4947 }
4948 llvm_unreachable("unknown unary transform type");
4949}
Eli Friedmanb001de72011-10-06 23:00:33 +00004950
4951QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) {
4952 if (!T->isDependentType()) {
Richard Smith83271182012-02-11 18:03:45 +00004953 // FIXME: It isn't entirely clear whether incomplete atomic types
4954 // are allowed or not; for simplicity, ban them for the moment.
Douglas Gregord10099e2012-05-04 16:32:21 +00004955 if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0))
Richard Smith83271182012-02-11 18:03:45 +00004956 return QualType();
4957
Eli Friedmanb001de72011-10-06 23:00:33 +00004958 int DisallowedKind = -1;
Richard Smith83271182012-02-11 18:03:45 +00004959 if (T->isArrayType())
Eli Friedmanb001de72011-10-06 23:00:33 +00004960 DisallowedKind = 1;
4961 else if (T->isFunctionType())
4962 DisallowedKind = 2;
4963 else if (T->isReferenceType())
4964 DisallowedKind = 3;
4965 else if (T->isAtomicType())
4966 DisallowedKind = 4;
4967 else if (T.hasQualifiers())
4968 DisallowedKind = 5;
4969 else if (!T.isTriviallyCopyableType(Context))
4970 // Some other non-trivially-copyable type (probably a C++ class)
4971 DisallowedKind = 6;
4972
4973 if (DisallowedKind != -1) {
4974 Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T;
4975 return QualType();
4976 }
4977
4978 // FIXME: Do we need any handling for ARC here?
4979 }
4980
4981 // Build the pointer type.
4982 return Context.getAtomicType(T);
4983}