blob: d8ac7636e213b2e303b308aefe7a1785fc636884 [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
Douglas Gregorf8af9822012-02-12 18:42:33 +000014#include "clang/Sema/ScopeInfo.h"
John McCall2d887082010-08-25 22:03:47 +000015#include "clang/Sema/SemaInternal.h"
John McCall7cd088e2010-08-24 07:21:54 +000016#include "clang/Sema/Template.h"
Peter Collingbourne207f4d82011-03-18 22:38:29 +000017#include "clang/Basic/OpenCL.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000018#include "clang/AST/ASTContext.h"
Douglas Gregor36f255c2011-06-03 14:28:43 +000019#include "clang/AST/ASTMutationListener.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000020#include "clang/AST/CXXInheritance.h"
Steve Naroff980e5082007-10-01 19:00:59 +000021#include "clang/AST/DeclObjC.h"
Douglas Gregor2943aed2009-03-03 04:44:36 +000022#include "clang/AST/DeclTemplate.h"
Argyrios Kyrtzidis4adab7f2009-08-19 01:28:06 +000023#include "clang/AST/TypeLoc.h"
John McCall51bd8032009-10-18 01:05:36 +000024#include "clang/AST/TypeLocVisitor.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000025#include "clang/AST/Expr.h"
Anders Carlsson91a0cc92009-08-26 22:33:56 +000026#include "clang/Basic/PartialDiagnostic.h"
Charles Davisd18f9f92010-08-16 04:01:50 +000027#include "clang/Basic/TargetInfo.h"
John McCall2792fa52011-03-08 04:17:03 +000028#include "clang/Lex/Preprocessor.h"
John McCall19510852010-08-20 18:27:03 +000029#include "clang/Sema/DeclSpec.h"
John McCallf85e1932011-06-15 23:02:42 +000030#include "clang/Sema/DelayedDiagnostic.h"
Douglas Gregord07cc362012-01-02 17:18:37 +000031#include "clang/Sema/Lookup.h"
Sebastian Redl4994d2d2009-07-04 11:39:00 +000032#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor87c12c42009-11-04 16:49:01 +000033#include "llvm/Support/ErrorHandling.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000034using namespace clang;
35
Chris Lattner5db2bb12009-10-25 18:21:37 +000036/// isOmittedBlockReturnType - Return true if this declarator is missing a
37/// return type because this is a omitted return type on a block literal.
Sebastian Redl8ce35b02009-10-25 21:45:37 +000038static bool isOmittedBlockReturnType(const Declarator &D) {
Chris Lattner5db2bb12009-10-25 18:21:37 +000039 if (D.getContext() != Declarator::BlockLiteralContext ||
Sebastian Redl8ce35b02009-10-25 21:45:37 +000040 D.getDeclSpec().hasTypeSpecifier())
Chris Lattner5db2bb12009-10-25 18:21:37 +000041 return false;
42
43 if (D.getNumTypeObjects() == 0)
Chris Lattnera64ef0a2009-10-25 22:09:09 +000044 return true; // ^{ ... }
Chris Lattner5db2bb12009-10-25 18:21:37 +000045
46 if (D.getNumTypeObjects() == 1 &&
47 D.getTypeObject(0).Kind == DeclaratorChunk::Function)
Chris Lattnera64ef0a2009-10-25 22:09:09 +000048 return true; // ^(int X, float Y) { ... }
Chris Lattner5db2bb12009-10-25 18:21:37 +000049
50 return false;
51}
52
John McCall2792fa52011-03-08 04:17:03 +000053/// diagnoseBadTypeAttribute - Diagnoses a type attribute which
54/// doesn't apply to the given type.
55static void diagnoseBadTypeAttribute(Sema &S, const AttributeList &attr,
56 QualType type) {
Chandler Carruth108f7562011-07-26 05:40:03 +000057 bool useExpansionLoc = false;
John McCall2792fa52011-03-08 04:17:03 +000058
59 unsigned diagID = 0;
60 switch (attr.getKind()) {
61 case AttributeList::AT_objc_gc:
62 diagID = diag::warn_pointer_attribute_wrong_type;
Chandler Carruth108f7562011-07-26 05:40:03 +000063 useExpansionLoc = true;
John McCall2792fa52011-03-08 04:17:03 +000064 break;
65
Argyrios Kyrtzidis05d48762011-07-01 22:23:09 +000066 case AttributeList::AT_objc_ownership:
67 diagID = diag::warn_objc_object_attribute_wrong_type;
Chandler Carruth108f7562011-07-26 05:40:03 +000068 useExpansionLoc = true;
Argyrios Kyrtzidis05d48762011-07-01 22:23:09 +000069 break;
70
John McCall2792fa52011-03-08 04:17:03 +000071 default:
72 // Assume everything else was a function attribute.
73 diagID = diag::warn_function_attribute_wrong_type;
74 break;
75 }
76
77 SourceLocation loc = attr.getLoc();
Chris Lattner5f9e2722011-07-23 10:55:15 +000078 StringRef name = attr.getName()->getName();
John McCall2792fa52011-03-08 04:17:03 +000079
80 // The GC attributes are usually written with macros; special-case them.
Chandler Carruth108f7562011-07-26 05:40:03 +000081 if (useExpansionLoc && loc.isMacroID() && attr.getParameterName()) {
John McCall834e3f62011-03-08 07:59:04 +000082 if (attr.getParameterName()->isStr("strong")) {
83 if (S.findMacroSpelling(loc, "__strong")) name = "__strong";
84 } else if (attr.getParameterName()->isStr("weak")) {
85 if (S.findMacroSpelling(loc, "__weak")) name = "__weak";
John McCall2792fa52011-03-08 04:17:03 +000086 }
87 }
88
89 S.Diag(loc, diagID) << name << type;
90}
91
John McCall711c52b2011-01-05 12:14:39 +000092// objc_gc applies to Objective-C pointers or, otherwise, to the
93// smallest available pointer type (i.e. 'void*' in 'void**').
94#define OBJC_POINTER_TYPE_ATTRS_CASELIST \
John McCallf85e1932011-06-15 23:02:42 +000095 case AttributeList::AT_objc_gc: \
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +000096 case AttributeList::AT_objc_ownership
John McCall04a67a62010-02-05 21:31:56 +000097
John McCall711c52b2011-01-05 12:14:39 +000098// Function type attributes.
99#define FUNCTION_TYPE_ATTRS_CASELIST \
100 case AttributeList::AT_noreturn: \
101 case AttributeList::AT_cdecl: \
102 case AttributeList::AT_fastcall: \
103 case AttributeList::AT_stdcall: \
104 case AttributeList::AT_thiscall: \
105 case AttributeList::AT_pascal: \
Anton Korobeynikov414d8962011-04-14 20:06:49 +0000106 case AttributeList::AT_regparm: \
107 case AttributeList::AT_pcs \
John McCall04a67a62010-02-05 21:31:56 +0000108
John McCall711c52b2011-01-05 12:14:39 +0000109namespace {
110 /// An object which stores processing state for the entire
111 /// GetTypeForDeclarator process.
112 class TypeProcessingState {
113 Sema &sema;
114
115 /// The declarator being processed.
116 Declarator &declarator;
117
118 /// The index of the declarator chunk we're currently processing.
119 /// May be the total number of valid chunks, indicating the
120 /// DeclSpec.
121 unsigned chunkIndex;
122
123 /// Whether there are non-trivial modifications to the decl spec.
124 bool trivial;
125
John McCall7ea21932011-03-26 01:39:56 +0000126 /// Whether we saved the attributes in the decl spec.
127 bool hasSavedAttrs;
128
John McCall711c52b2011-01-05 12:14:39 +0000129 /// The original set of attributes on the DeclSpec.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000130 SmallVector<AttributeList*, 2> savedAttrs;
John McCall711c52b2011-01-05 12:14:39 +0000131
132 /// A list of attributes to diagnose the uselessness of when the
133 /// processing is complete.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000134 SmallVector<AttributeList*, 2> ignoredTypeAttrs;
John McCall711c52b2011-01-05 12:14:39 +0000135
136 public:
137 TypeProcessingState(Sema &sema, Declarator &declarator)
138 : sema(sema), declarator(declarator),
139 chunkIndex(declarator.getNumTypeObjects()),
John McCall7ea21932011-03-26 01:39:56 +0000140 trivial(true), hasSavedAttrs(false) {}
John McCall711c52b2011-01-05 12:14:39 +0000141
142 Sema &getSema() const {
143 return sema;
Abramo Bagnarae215f722010-04-30 13:10:51 +0000144 }
John McCall711c52b2011-01-05 12:14:39 +0000145
146 Declarator &getDeclarator() const {
147 return declarator;
148 }
149
150 unsigned getCurrentChunkIndex() const {
151 return chunkIndex;
152 }
153
154 void setCurrentChunkIndex(unsigned idx) {
155 assert(idx <= declarator.getNumTypeObjects());
156 chunkIndex = idx;
157 }
158
159 AttributeList *&getCurrentAttrListRef() const {
160 assert(chunkIndex <= declarator.getNumTypeObjects());
161 if (chunkIndex == declarator.getNumTypeObjects())
162 return getMutableDeclSpec().getAttributes().getListRef();
163 return declarator.getTypeObject(chunkIndex).getAttrListRef();
164 }
165
166 /// Save the current set of attributes on the DeclSpec.
167 void saveDeclSpecAttrs() {
168 // Don't try to save them multiple times.
John McCall7ea21932011-03-26 01:39:56 +0000169 if (hasSavedAttrs) return;
John McCall711c52b2011-01-05 12:14:39 +0000170
171 DeclSpec &spec = getMutableDeclSpec();
172 for (AttributeList *attr = spec.getAttributes().getList(); attr;
173 attr = attr->getNext())
174 savedAttrs.push_back(attr);
175 trivial &= savedAttrs.empty();
John McCall7ea21932011-03-26 01:39:56 +0000176 hasSavedAttrs = true;
John McCall711c52b2011-01-05 12:14:39 +0000177 }
178
179 /// Record that we had nowhere to put the given type attribute.
180 /// We will diagnose such attributes later.
181 void addIgnoredTypeAttr(AttributeList &attr) {
182 ignoredTypeAttrs.push_back(&attr);
183 }
184
185 /// Diagnose all the ignored type attributes, given that the
186 /// declarator worked out to the given type.
187 void diagnoseIgnoredTypeAttrs(QualType type) const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000188 for (SmallVectorImpl<AttributeList*>::const_iterator
John McCall711c52b2011-01-05 12:14:39 +0000189 i = ignoredTypeAttrs.begin(), e = ignoredTypeAttrs.end();
John McCall2792fa52011-03-08 04:17:03 +0000190 i != e; ++i)
191 diagnoseBadTypeAttribute(getSema(), **i, type);
John McCall711c52b2011-01-05 12:14:39 +0000192 }
193
194 ~TypeProcessingState() {
195 if (trivial) return;
196
197 restoreDeclSpecAttrs();
198 }
199
200 private:
201 DeclSpec &getMutableDeclSpec() const {
202 return const_cast<DeclSpec&>(declarator.getDeclSpec());
203 }
204
205 void restoreDeclSpecAttrs() {
John McCall7ea21932011-03-26 01:39:56 +0000206 assert(hasSavedAttrs);
207
208 if (savedAttrs.empty()) {
209 getMutableDeclSpec().getAttributes().set(0);
210 return;
211 }
212
John McCall711c52b2011-01-05 12:14:39 +0000213 getMutableDeclSpec().getAttributes().set(savedAttrs[0]);
214 for (unsigned i = 0, e = savedAttrs.size() - 1; i != e; ++i)
215 savedAttrs[i]->setNext(savedAttrs[i+1]);
216 savedAttrs.back()->setNext(0);
217 }
218 };
219
220 /// Basically std::pair except that we really want to avoid an
221 /// implicit operator= for safety concerns. It's also a minor
222 /// link-time optimization for this to be a private type.
223 struct AttrAndList {
224 /// The attribute.
225 AttributeList &first;
226
227 /// The head of the list the attribute is currently in.
228 AttributeList *&second;
229
230 AttrAndList(AttributeList &attr, AttributeList *&head)
231 : first(attr), second(head) {}
232 };
John McCall04a67a62010-02-05 21:31:56 +0000233}
234
John McCall711c52b2011-01-05 12:14:39 +0000235namespace llvm {
236 template <> struct isPodLike<AttrAndList> {
237 static const bool value = true;
238 };
239}
240
241static void spliceAttrIntoList(AttributeList &attr, AttributeList *&head) {
242 attr.setNext(head);
243 head = &attr;
244}
245
246static void spliceAttrOutOfList(AttributeList &attr, AttributeList *&head) {
247 if (head == &attr) {
248 head = attr.getNext();
249 return;
John McCall04a67a62010-02-05 21:31:56 +0000250 }
John McCall711c52b2011-01-05 12:14:39 +0000251
252 AttributeList *cur = head;
253 while (true) {
254 assert(cur && cur->getNext() && "ran out of attrs?");
255 if (cur->getNext() == &attr) {
256 cur->setNext(attr.getNext());
257 return;
258 }
259 cur = cur->getNext();
260 }
261}
262
263static void moveAttrFromListToList(AttributeList &attr,
264 AttributeList *&fromList,
265 AttributeList *&toList) {
266 spliceAttrOutOfList(attr, fromList);
267 spliceAttrIntoList(attr, toList);
268}
269
270static void processTypeAttrs(TypeProcessingState &state,
271 QualType &type, bool isDeclSpec,
272 AttributeList *attrs);
273
274static bool handleFunctionTypeAttr(TypeProcessingState &state,
275 AttributeList &attr,
276 QualType &type);
277
278static bool handleObjCGCTypeAttr(TypeProcessingState &state,
279 AttributeList &attr, QualType &type);
280
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +0000281static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
John McCallf85e1932011-06-15 23:02:42 +0000282 AttributeList &attr, QualType &type);
283
John McCall711c52b2011-01-05 12:14:39 +0000284static bool handleObjCPointerTypeAttr(TypeProcessingState &state,
285 AttributeList &attr, QualType &type) {
John McCallf85e1932011-06-15 23:02:42 +0000286 if (attr.getKind() == AttributeList::AT_objc_gc)
287 return handleObjCGCTypeAttr(state, attr, type);
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +0000288 assert(attr.getKind() == AttributeList::AT_objc_ownership);
289 return handleObjCOwnershipTypeAttr(state, attr, type);
John McCall711c52b2011-01-05 12:14:39 +0000290}
291
292/// Given that an objc_gc attribute was written somewhere on a
293/// declaration *other* than on the declarator itself (for which, use
294/// distributeObjCPointerTypeAttrFromDeclarator), and given that it
295/// didn't apply in whatever position it was written in, try to move
296/// it to a more appropriate position.
297static void distributeObjCPointerTypeAttr(TypeProcessingState &state,
298 AttributeList &attr,
299 QualType type) {
300 Declarator &declarator = state.getDeclarator();
301 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
302 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
303 switch (chunk.Kind) {
304 case DeclaratorChunk::Pointer:
305 case DeclaratorChunk::BlockPointer:
306 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
307 chunk.getAttrListRef());
308 return;
309
310 case DeclaratorChunk::Paren:
311 case DeclaratorChunk::Array:
312 continue;
313
314 // Don't walk through these.
315 case DeclaratorChunk::Reference:
316 case DeclaratorChunk::Function:
317 case DeclaratorChunk::MemberPointer:
318 goto error;
319 }
320 }
321 error:
John McCall2792fa52011-03-08 04:17:03 +0000322
323 diagnoseBadTypeAttribute(state.getSema(), attr, type);
John McCall711c52b2011-01-05 12:14:39 +0000324}
325
326/// Distribute an objc_gc type attribute that was written on the
327/// declarator.
328static void
329distributeObjCPointerTypeAttrFromDeclarator(TypeProcessingState &state,
330 AttributeList &attr,
331 QualType &declSpecType) {
332 Declarator &declarator = state.getDeclarator();
333
334 // objc_gc goes on the innermost pointer to something that's not a
335 // pointer.
336 unsigned innermost = -1U;
337 bool considerDeclSpec = true;
338 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
339 DeclaratorChunk &chunk = declarator.getTypeObject(i);
340 switch (chunk.Kind) {
341 case DeclaratorChunk::Pointer:
342 case DeclaratorChunk::BlockPointer:
343 innermost = i;
John McCallae278a32011-01-12 00:34:59 +0000344 continue;
John McCall711c52b2011-01-05 12:14:39 +0000345
346 case DeclaratorChunk::Reference:
347 case DeclaratorChunk::MemberPointer:
348 case DeclaratorChunk::Paren:
349 case DeclaratorChunk::Array:
350 continue;
351
352 case DeclaratorChunk::Function:
353 considerDeclSpec = false;
354 goto done;
355 }
356 }
357 done:
358
359 // That might actually be the decl spec if we weren't blocked by
360 // anything in the declarator.
361 if (considerDeclSpec) {
John McCall7ea21932011-03-26 01:39:56 +0000362 if (handleObjCPointerTypeAttr(state, attr, declSpecType)) {
363 // Splice the attribute into the decl spec. Prevents the
364 // attribute from being applied multiple times and gives
365 // the source-location-filler something to work with.
366 state.saveDeclSpecAttrs();
367 moveAttrFromListToList(attr, declarator.getAttrListRef(),
368 declarator.getMutableDeclSpec().getAttributes().getListRef());
John McCall711c52b2011-01-05 12:14:39 +0000369 return;
John McCall7ea21932011-03-26 01:39:56 +0000370 }
John McCall711c52b2011-01-05 12:14:39 +0000371 }
372
373 // Otherwise, if we found an appropriate chunk, splice the attribute
374 // into it.
375 if (innermost != -1U) {
376 moveAttrFromListToList(attr, declarator.getAttrListRef(),
377 declarator.getTypeObject(innermost).getAttrListRef());
378 return;
379 }
380
381 // Otherwise, diagnose when we're done building the type.
382 spliceAttrOutOfList(attr, declarator.getAttrListRef());
383 state.addIgnoredTypeAttr(attr);
384}
385
386/// A function type attribute was written somewhere in a declaration
387/// *other* than on the declarator itself or in the decl spec. Given
388/// that it didn't apply in whatever position it was written in, try
389/// to move it to a more appropriate position.
390static void distributeFunctionTypeAttr(TypeProcessingState &state,
391 AttributeList &attr,
392 QualType type) {
393 Declarator &declarator = state.getDeclarator();
394
395 // Try to push the attribute from the return type of a function to
396 // the function itself.
397 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
398 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
399 switch (chunk.Kind) {
400 case DeclaratorChunk::Function:
401 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
402 chunk.getAttrListRef());
403 return;
404
405 case DeclaratorChunk::Paren:
406 case DeclaratorChunk::Pointer:
407 case DeclaratorChunk::BlockPointer:
408 case DeclaratorChunk::Array:
409 case DeclaratorChunk::Reference:
410 case DeclaratorChunk::MemberPointer:
411 continue;
412 }
413 }
414
John McCall2792fa52011-03-08 04:17:03 +0000415 diagnoseBadTypeAttribute(state.getSema(), attr, type);
John McCall711c52b2011-01-05 12:14:39 +0000416}
417
418/// Try to distribute a function type attribute to the innermost
419/// function chunk or type. Returns true if the attribute was
420/// distributed, false if no location was found.
421static bool
422distributeFunctionTypeAttrToInnermost(TypeProcessingState &state,
423 AttributeList &attr,
424 AttributeList *&attrList,
425 QualType &declSpecType) {
426 Declarator &declarator = state.getDeclarator();
427
428 // Put it on the innermost function chunk, if there is one.
429 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
430 DeclaratorChunk &chunk = declarator.getTypeObject(i);
431 if (chunk.Kind != DeclaratorChunk::Function) continue;
432
433 moveAttrFromListToList(attr, attrList, chunk.getAttrListRef());
434 return true;
435 }
436
John McCallf85e1932011-06-15 23:02:42 +0000437 if (handleFunctionTypeAttr(state, attr, declSpecType)) {
438 spliceAttrOutOfList(attr, attrList);
439 return true;
440 }
441
442 return false;
John McCall711c52b2011-01-05 12:14:39 +0000443}
444
445/// A function type attribute was written in the decl spec. Try to
446/// apply it somewhere.
447static void
448distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state,
449 AttributeList &attr,
450 QualType &declSpecType) {
451 state.saveDeclSpecAttrs();
452
453 // Try to distribute to the innermost.
454 if (distributeFunctionTypeAttrToInnermost(state, attr,
455 state.getCurrentAttrListRef(),
456 declSpecType))
457 return;
458
459 // If that failed, diagnose the bad attribute when the declarator is
460 // fully built.
461 state.addIgnoredTypeAttr(attr);
462}
463
464/// A function type attribute was written on the declarator. Try to
465/// apply it somewhere.
466static void
467distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state,
468 AttributeList &attr,
469 QualType &declSpecType) {
470 Declarator &declarator = state.getDeclarator();
471
472 // Try to distribute to the innermost.
473 if (distributeFunctionTypeAttrToInnermost(state, attr,
474 declarator.getAttrListRef(),
475 declSpecType))
476 return;
477
478 // If that failed, diagnose the bad attribute when the declarator is
479 // fully built.
480 spliceAttrOutOfList(attr, declarator.getAttrListRef());
481 state.addIgnoredTypeAttr(attr);
482}
483
484/// \brief Given that there are attributes written on the declarator
485/// itself, try to distribute any type attributes to the appropriate
486/// declarator chunk.
487///
488/// These are attributes like the following:
489/// int f ATTR;
490/// int (f ATTR)();
491/// but not necessarily this:
492/// int f() ATTR;
493static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state,
494 QualType &declSpecType) {
495 // Collect all the type attributes from the declarator itself.
496 assert(state.getDeclarator().getAttributes() && "declarator has no attrs!");
497 AttributeList *attr = state.getDeclarator().getAttributes();
498 AttributeList *next;
499 do {
500 next = attr->getNext();
501
502 switch (attr->getKind()) {
503 OBJC_POINTER_TYPE_ATTRS_CASELIST:
504 distributeObjCPointerTypeAttrFromDeclarator(state, *attr, declSpecType);
505 break;
506
John McCallf85e1932011-06-15 23:02:42 +0000507 case AttributeList::AT_ns_returns_retained:
David Blaikie4e4d0842012-03-11 07:00:24 +0000508 if (!state.getSema().getLangOpts().ObjCAutoRefCount)
John McCallf85e1932011-06-15 23:02:42 +0000509 break;
510 // fallthrough
511
John McCall711c52b2011-01-05 12:14:39 +0000512 FUNCTION_TYPE_ATTRS_CASELIST:
513 distributeFunctionTypeAttrFromDeclarator(state, *attr, declSpecType);
514 break;
515
516 default:
517 break;
518 }
519 } while ((attr = next));
520}
521
522/// Add a synthetic '()' to a block-literal declarator if it is
523/// required, given the return type.
524static void maybeSynthesizeBlockSignature(TypeProcessingState &state,
525 QualType declSpecType) {
526 Declarator &declarator = state.getDeclarator();
527
528 // First, check whether the declarator would produce a function,
529 // i.e. whether the innermost semantic chunk is a function.
530 if (declarator.isFunctionDeclarator()) {
531 // If so, make that declarator a prototyped declarator.
532 declarator.getFunctionTypeInfo().hasPrototype = true;
533 return;
534 }
535
John McCallda263792011-02-08 01:59:10 +0000536 // If there are any type objects, the type as written won't name a
537 // function, regardless of the decl spec type. This is because a
538 // block signature declarator is always an abstract-declarator, and
539 // abstract-declarators can't just be parentheses chunks. Therefore
540 // we need to build a function chunk unless there are no type
541 // objects and the decl spec type is a function.
John McCall711c52b2011-01-05 12:14:39 +0000542 if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType())
543 return;
544
John McCallda263792011-02-08 01:59:10 +0000545 // Note that there *are* cases with invalid declarators where
546 // declarators consist solely of parentheses. In general, these
547 // occur only in failed efforts to make function declarators, so
548 // faking up the function chunk is still the right thing to do.
John McCall711c52b2011-01-05 12:14:39 +0000549
550 // Otherwise, we need to fake up a function declarator.
Daniel Dunbar96a00142012-03-09 18:35:03 +0000551 SourceLocation loc = declarator.getLocStart();
John McCall711c52b2011-01-05 12:14:39 +0000552
553 // ...and *prepend* it to the declarator.
554 declarator.AddInnermostTypeInfo(DeclaratorChunk::getFunction(
John McCall711c52b2011-01-05 12:14:39 +0000555 /*proto*/ true,
556 /*variadic*/ false, SourceLocation(),
557 /*args*/ 0, 0,
558 /*type quals*/ 0,
Douglas Gregor83f51722011-01-26 03:43:54 +0000559 /*ref-qualifier*/true, SourceLocation(),
Douglas Gregor43f51032011-10-19 06:04:55 +0000560 /*const qualifier*/SourceLocation(),
561 /*volatile qualifier*/SourceLocation(),
Douglas Gregor90ebed02011-07-13 21:47:47 +0000562 /*mutable qualifier*/SourceLocation(),
Sebastian Redl6e5d3192011-03-05 22:42:13 +0000563 /*EH*/ EST_None, SourceLocation(), 0, 0, 0, 0,
John McCall711c52b2011-01-05 12:14:39 +0000564 /*parens*/ loc, loc,
565 declarator));
566
567 // For consistency, make sure the state still has us as processing
568 // the decl spec.
569 assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1);
570 state.setCurrentChunkIndex(declarator.getNumTypeObjects());
John McCall04a67a62010-02-05 21:31:56 +0000571}
572
Douglas Gregor930d8b52009-01-30 22:09:00 +0000573/// \brief Convert the specified declspec to the appropriate type
574/// object.
Chris Lattner5db2bb12009-10-25 18:21:37 +0000575/// \param D the declarator containing the declaration specifier.
Chris Lattner5153ee62009-04-25 08:47:54 +0000576/// \returns The type described by the declaration specifiers. This function
577/// never returns null.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +0000578static QualType ConvertDeclSpecToType(TypeProcessingState &state) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000579 // FIXME: Should move the logic from DeclSpec::Finish to here for validity
580 // checking.
John McCall711c52b2011-01-05 12:14:39 +0000581
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +0000582 Sema &S = state.getSema();
John McCall711c52b2011-01-05 12:14:39 +0000583 Declarator &declarator = state.getDeclarator();
584 const DeclSpec &DS = declarator.getDeclSpec();
585 SourceLocation DeclLoc = declarator.getIdentifierLoc();
Chris Lattner5db2bb12009-10-25 18:21:37 +0000586 if (DeclLoc.isInvalid())
Daniel Dunbar96a00142012-03-09 18:35:03 +0000587 DeclLoc = DS.getLocStart();
Chris Lattner1564e392009-10-25 18:07:27 +0000588
John McCall711c52b2011-01-05 12:14:39 +0000589 ASTContext &Context = S.Context;
Mike Stump1eb44332009-09-09 15:08:12 +0000590
Chris Lattner5db2bb12009-10-25 18:21:37 +0000591 QualType Result;
Reid Spencer5f016e22007-07-11 17:01:13 +0000592 switch (DS.getTypeSpecType()) {
Chris Lattner96b77fc2008-04-02 06:50:17 +0000593 case DeclSpec::TST_void:
594 Result = Context.VoidTy;
595 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000596 case DeclSpec::TST_char:
597 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
Chris Lattnerfab5b452008-02-20 23:53:49 +0000598 Result = Context.CharTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000599 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed)
Chris Lattnerfab5b452008-02-20 23:53:49 +0000600 Result = Context.SignedCharTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000601 else {
602 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
603 "Unknown TSS value");
Chris Lattnerfab5b452008-02-20 23:53:49 +0000604 Result = Context.UnsignedCharTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000605 }
Chris Lattner958858e2008-02-20 21:40:32 +0000606 break;
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000607 case DeclSpec::TST_wchar:
608 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
609 Result = Context.WCharTy;
610 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) {
John McCall711c52b2011-01-05 12:14:39 +0000611 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000612 << DS.getSpecifierName(DS.getTypeSpecType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000613 Result = Context.getSignedWCharType();
614 } else {
615 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
616 "Unknown TSS value");
John McCall711c52b2011-01-05 12:14:39 +0000617 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000618 << DS.getSpecifierName(DS.getTypeSpecType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000619 Result = Context.getUnsignedWCharType();
620 }
621 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000622 case DeclSpec::TST_char16:
623 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
624 "Unknown TSS value");
625 Result = Context.Char16Ty;
626 break;
627 case DeclSpec::TST_char32:
628 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
629 "Unknown TSS value");
630 Result = Context.Char32Ty;
631 break;
Chris Lattnerd658b562008-04-05 06:32:51 +0000632 case DeclSpec::TST_unspecified:
Chris Lattner62f5f7f2008-07-26 00:46:50 +0000633 // "<proto1,proto2>" is an objc qualified ID with a missing id.
Chris Lattner097e9162008-10-20 02:01:50 +0000634 if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) {
John McCallc12c5bb2010-05-15 11:32:37 +0000635 Result = Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
636 (ObjCProtocolDecl**)PQ,
637 DS.getNumProtocolQualifiers());
638 Result = Context.getObjCObjectPointerType(Result);
Chris Lattner62f5f7f2008-07-26 00:46:50 +0000639 break;
640 }
Chris Lattner5db2bb12009-10-25 18:21:37 +0000641
642 // If this is a missing declspec in a block literal return context, then it
643 // is inferred from the return statements inside the block.
Eli Friedmanf88c4002012-01-04 04:41:38 +0000644 // The declspec is always missing in a lambda expr context; it is either
645 // specified with a trailing return type or inferred.
646 if (declarator.getContext() == Declarator::LambdaExprContext ||
647 isOmittedBlockReturnType(declarator)) {
Chris Lattner5db2bb12009-10-25 18:21:37 +0000648 Result = Context.DependentTy;
649 break;
650 }
Mike Stump1eb44332009-09-09 15:08:12 +0000651
Chris Lattnerd658b562008-04-05 06:32:51 +0000652 // Unspecified typespec defaults to int in C90. However, the C90 grammar
653 // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
654 // type-qualifier, or storage-class-specifier. If not, emit an extwarn.
655 // Note that the one exception to this is function definitions, which are
656 // allowed to be completely missing a declspec. This is handled in the
657 // parser already though by it pretending to have seen an 'int' in this
658 // case.
David Blaikie4e4d0842012-03-11 07:00:24 +0000659 if (S.getLangOpts().ImplicitInt) {
Chris Lattner35d276f2009-02-27 18:53:28 +0000660 // In C89 mode, we only warn if there is a completely missing declspec
661 // when one is not allowed.
Chris Lattner3f84ad22009-04-22 05:27:59 +0000662 if (DS.isEmpty()) {
John McCall711c52b2011-01-05 12:14:39 +0000663 S.Diag(DeclLoc, diag::ext_missing_declspec)
Chris Lattner3f84ad22009-04-22 05:27:59 +0000664 << DS.getSourceRange()
Daniel Dunbar96a00142012-03-09 18:35:03 +0000665 << FixItHint::CreateInsertion(DS.getLocStart(), "int");
Chris Lattner3f84ad22009-04-22 05:27:59 +0000666 }
Douglas Gregor4310f4e2009-02-16 22:38:20 +0000667 } else if (!DS.hasTypeSpecifier()) {
Chris Lattnerd658b562008-04-05 06:32:51 +0000668 // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says:
669 // "At least one type specifier shall be given in the declaration
670 // specifiers in each declaration, and in the specifier-qualifier list in
671 // each struct declaration and type name."
Douglas Gregor4310f4e2009-02-16 22:38:20 +0000672 // FIXME: Does Microsoft really have the implicit int extension in C++?
David Blaikie4e4d0842012-03-11 07:00:24 +0000673 if (S.getLangOpts().CPlusPlus &&
674 !S.getLangOpts().MicrosoftExt) {
John McCall711c52b2011-01-05 12:14:39 +0000675 S.Diag(DeclLoc, diag::err_missing_type_specifier)
Chris Lattner3f84ad22009-04-22 05:27:59 +0000676 << DS.getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000677
Chris Lattnerb78d8332009-06-26 04:45:06 +0000678 // When this occurs in C++ code, often something is very broken with the
679 // value being declared, poison it as invalid so we don't get chains of
680 // errors.
John McCall711c52b2011-01-05 12:14:39 +0000681 declarator.setInvalidType(true);
Chris Lattnerb78d8332009-06-26 04:45:06 +0000682 } else {
John McCall711c52b2011-01-05 12:14:39 +0000683 S.Diag(DeclLoc, diag::ext_missing_type_specifier)
Chris Lattner3f84ad22009-04-22 05:27:59 +0000684 << DS.getSourceRange();
Chris Lattnerb78d8332009-06-26 04:45:06 +0000685 }
Chris Lattnerd658b562008-04-05 06:32:51 +0000686 }
Mike Stump1eb44332009-09-09 15:08:12 +0000687
688 // FALL THROUGH.
Chris Lattner3cbc38b2007-08-21 17:02:28 +0000689 case DeclSpec::TST_int: {
Reid Spencer5f016e22007-07-11 17:01:13 +0000690 if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) {
691 switch (DS.getTypeSpecWidth()) {
Chris Lattnerfab5b452008-02-20 23:53:49 +0000692 case DeclSpec::TSW_unspecified: Result = Context.IntTy; break;
693 case DeclSpec::TSW_short: Result = Context.ShortTy; break;
694 case DeclSpec::TSW_long: Result = Context.LongTy; break;
Chris Lattner311157f2009-10-25 18:25:04 +0000695 case DeclSpec::TSW_longlong:
696 Result = Context.LongLongTy;
697
698 // long long is a C99 feature.
David Blaikie4e4d0842012-03-11 07:00:24 +0000699 if (!S.getLangOpts().C99)
Richard Smithebaf0e62011-10-18 20:49:44 +0000700 S.Diag(DS.getTypeSpecWidthLoc(),
David Blaikie4e4d0842012-03-11 07:00:24 +0000701 S.getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +0000702 diag::warn_cxx98_compat_longlong : diag::ext_longlong);
Chris Lattner311157f2009-10-25 18:25:04 +0000703 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000704 }
705 } else {
706 switch (DS.getTypeSpecWidth()) {
Chris Lattnerfab5b452008-02-20 23:53:49 +0000707 case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break;
708 case DeclSpec::TSW_short: Result = Context.UnsignedShortTy; break;
709 case DeclSpec::TSW_long: Result = Context.UnsignedLongTy; break;
Chris Lattner311157f2009-10-25 18:25:04 +0000710 case DeclSpec::TSW_longlong:
711 Result = Context.UnsignedLongLongTy;
712
713 // long long is a C99 feature.
David Blaikie4e4d0842012-03-11 07:00:24 +0000714 if (!S.getLangOpts().C99)
Richard Smithebaf0e62011-10-18 20:49:44 +0000715 S.Diag(DS.getTypeSpecWidthLoc(),
David Blaikie4e4d0842012-03-11 07:00:24 +0000716 S.getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +0000717 diag::warn_cxx98_compat_longlong : diag::ext_longlong);
Chris Lattner311157f2009-10-25 18:25:04 +0000718 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000719 }
720 }
Chris Lattner958858e2008-02-20 21:40:32 +0000721 break;
Chris Lattner3cbc38b2007-08-21 17:02:28 +0000722 }
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000723 case DeclSpec::TST_half: Result = Context.HalfTy; break;
Chris Lattnerfab5b452008-02-20 23:53:49 +0000724 case DeclSpec::TST_float: Result = Context.FloatTy; break;
Chris Lattner958858e2008-02-20 21:40:32 +0000725 case DeclSpec::TST_double:
726 if (DS.getTypeSpecWidth() == DeclSpec::TSW_long)
Chris Lattnerfab5b452008-02-20 23:53:49 +0000727 Result = Context.LongDoubleTy;
Chris Lattner958858e2008-02-20 21:40:32 +0000728 else
Chris Lattnerfab5b452008-02-20 23:53:49 +0000729 Result = Context.DoubleTy;
Peter Collingbourne39d3e7a2011-02-15 19:46:23 +0000730
David Blaikie4e4d0842012-03-11 07:00:24 +0000731 if (S.getLangOpts().OpenCL && !S.getOpenCLOptions().cl_khr_fp64) {
Peter Collingbourne39d3e7a2011-02-15 19:46:23 +0000732 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_double_requires_fp64);
733 declarator.setInvalidType(true);
734 }
Chris Lattner958858e2008-02-20 21:40:32 +0000735 break;
Chris Lattnerfab5b452008-02-20 23:53:49 +0000736 case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool
Reid Spencer5f016e22007-07-11 17:01:13 +0000737 case DeclSpec::TST_decimal32: // _Decimal32
738 case DeclSpec::TST_decimal64: // _Decimal64
739 case DeclSpec::TST_decimal128: // _Decimal128
John McCall711c52b2011-01-05 12:14:39 +0000740 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
Chris Lattner8f12f652009-05-13 05:02:08 +0000741 Result = Context.IntTy;
John McCall711c52b2011-01-05 12:14:39 +0000742 declarator.setInvalidType(true);
Chris Lattner8f12f652009-05-13 05:02:08 +0000743 break;
Chris Lattner99dc9142008-04-13 18:59:07 +0000744 case DeclSpec::TST_class:
Reid Spencer5f016e22007-07-11 17:01:13 +0000745 case DeclSpec::TST_enum:
746 case DeclSpec::TST_union:
747 case DeclSpec::TST_struct: {
John McCallb3d87482010-08-24 05:47:05 +0000748 TypeDecl *D = dyn_cast_or_null<TypeDecl>(DS.getRepAsDecl());
John McCall6e247262009-10-10 05:48:19 +0000749 if (!D) {
750 // This can happen in C++ with ambiguous lookups.
751 Result = Context.IntTy;
John McCall711c52b2011-01-05 12:14:39 +0000752 declarator.setInvalidType(true);
John McCall6e247262009-10-10 05:48:19 +0000753 break;
754 }
755
Chris Lattnera64ef0a2009-10-25 22:09:09 +0000756 // If the type is deprecated or unavailable, diagnose it.
Abramo Bagnara0daaf322011-03-16 20:16:18 +0000757 S.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeNameLoc());
Chris Lattnera64ef0a2009-10-25 22:09:09 +0000758
Reid Spencer5f016e22007-07-11 17:01:13 +0000759 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
Chris Lattnera64ef0a2009-10-25 22:09:09 +0000760 DS.getTypeSpecSign() == 0 && "No qualifiers on tag names!");
761
Reid Spencer5f016e22007-07-11 17:01:13 +0000762 // TypeQuals handled by caller.
Chris Lattnera64ef0a2009-10-25 22:09:09 +0000763 Result = Context.getTypeDeclType(D);
John McCall2191b202009-09-05 06:31:47 +0000764
Abramo Bagnara0daaf322011-03-16 20:16:18 +0000765 // In both C and C++, make an ElaboratedType.
766 ElaboratedTypeKeyword Keyword
767 = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType());
768 Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result);
Chris Lattner958858e2008-02-20 21:40:32 +0000769 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000770 }
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000771 case DeclSpec::TST_typename: {
Reid Spencer5f016e22007-07-11 17:01:13 +0000772 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
773 DS.getTypeSpecSign() == 0 &&
774 "Can't handle qualifiers on typedef names yet!");
John McCall711c52b2011-01-05 12:14:39 +0000775 Result = S.GetTypeFromParser(DS.getRepAsType());
John McCall27940d22010-07-30 05:17:22 +0000776 if (Result.isNull())
John McCall711c52b2011-01-05 12:14:39 +0000777 declarator.setInvalidType(true);
John McCall27940d22010-07-30 05:17:22 +0000778 else if (DeclSpec::ProtocolQualifierListTy PQ
779 = DS.getProtocolQualifiers()) {
John McCallc12c5bb2010-05-15 11:32:37 +0000780 if (const ObjCObjectType *ObjT = Result->getAs<ObjCObjectType>()) {
781 // Silently drop any existing protocol qualifiers.
782 // TODO: determine whether that's the right thing to do.
783 if (ObjT->getNumProtocols())
784 Result = ObjT->getBaseType();
785
786 if (DS.getNumProtocolQualifiers())
787 Result = Context.getObjCObjectType(Result,
788 (ObjCProtocolDecl**) PQ,
789 DS.getNumProtocolQualifiers());
790 } else if (Result->isObjCIdType()) {
Chris Lattnerae4da612008-07-26 01:53:50 +0000791 // id<protocol-list>
John McCallc12c5bb2010-05-15 11:32:37 +0000792 Result = Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
793 (ObjCProtocolDecl**) PQ,
794 DS.getNumProtocolQualifiers());
795 Result = Context.getObjCObjectPointerType(Result);
796 } else if (Result->isObjCClassType()) {
Steve Naroff4262a072009-02-23 18:53:24 +0000797 // Class<protocol-list>
John McCallc12c5bb2010-05-15 11:32:37 +0000798 Result = Context.getObjCObjectType(Context.ObjCBuiltinClassTy,
799 (ObjCProtocolDecl**) PQ,
800 DS.getNumProtocolQualifiers());
801 Result = Context.getObjCObjectPointerType(Result);
Chris Lattner3f84ad22009-04-22 05:27:59 +0000802 } else {
John McCall711c52b2011-01-05 12:14:39 +0000803 S.Diag(DeclLoc, diag::err_invalid_protocol_qualifiers)
Chris Lattner3f84ad22009-04-22 05:27:59 +0000804 << DS.getSourceRange();
John McCall711c52b2011-01-05 12:14:39 +0000805 declarator.setInvalidType(true);
Chris Lattner3f84ad22009-04-22 05:27:59 +0000806 }
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000807 }
Mike Stump1eb44332009-09-09 15:08:12 +0000808
Reid Spencer5f016e22007-07-11 17:01:13 +0000809 // TypeQuals handled by caller.
Chris Lattner958858e2008-02-20 21:40:32 +0000810 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000811 }
Chris Lattner958858e2008-02-20 21:40:32 +0000812 case DeclSpec::TST_typeofType:
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000813 // FIXME: Preserve type source info.
John McCall711c52b2011-01-05 12:14:39 +0000814 Result = S.GetTypeFromParser(DS.getRepAsType());
Chris Lattner958858e2008-02-20 21:40:32 +0000815 assert(!Result.isNull() && "Didn't get a type for typeof?");
Fariborz Jahanian730e1752010-10-06 17:00:02 +0000816 if (!Result->isDependentType())
817 if (const TagType *TT = Result->getAs<TagType>())
John McCall711c52b2011-01-05 12:14:39 +0000818 S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc());
Steve Naroffd1861fd2007-07-31 12:34:36 +0000819 // TypeQuals handled by caller.
Chris Lattnerfab5b452008-02-20 23:53:49 +0000820 Result = Context.getTypeOfType(Result);
Chris Lattner958858e2008-02-20 21:40:32 +0000821 break;
Steve Naroffd1861fd2007-07-31 12:34:36 +0000822 case DeclSpec::TST_typeofExpr: {
John McCallb3d87482010-08-24 05:47:05 +0000823 Expr *E = DS.getRepAsExpr();
Steve Naroffd1861fd2007-07-31 12:34:36 +0000824 assert(E && "Didn't get an expression for typeof?");
825 // TypeQuals handled by caller.
John McCall711c52b2011-01-05 12:14:39 +0000826 Result = S.BuildTypeofExprType(E, DS.getTypeSpecTypeLoc());
Douglas Gregor4b52e252009-12-21 23:17:24 +0000827 if (Result.isNull()) {
828 Result = Context.IntTy;
John McCall711c52b2011-01-05 12:14:39 +0000829 declarator.setInvalidType(true);
Douglas Gregor4b52e252009-12-21 23:17:24 +0000830 }
Chris Lattner958858e2008-02-20 21:40:32 +0000831 break;
Steve Naroffd1861fd2007-07-31 12:34:36 +0000832 }
Anders Carlsson6fd634f2009-06-24 17:47:40 +0000833 case DeclSpec::TST_decltype: {
John McCallb3d87482010-08-24 05:47:05 +0000834 Expr *E = DS.getRepAsExpr();
Anders Carlsson6fd634f2009-06-24 17:47:40 +0000835 assert(E && "Didn't get an expression for decltype?");
836 // TypeQuals handled by caller.
John McCall711c52b2011-01-05 12:14:39 +0000837 Result = S.BuildDecltypeType(E, DS.getTypeSpecTypeLoc());
Anders Carlssonaf017e62009-06-29 22:58:55 +0000838 if (Result.isNull()) {
839 Result = Context.IntTy;
John McCall711c52b2011-01-05 12:14:39 +0000840 declarator.setInvalidType(true);
Anders Carlssonaf017e62009-06-29 22:58:55 +0000841 }
Anders Carlsson6fd634f2009-06-24 17:47:40 +0000842 break;
843 }
Sean Huntca63c202011-05-24 22:41:36 +0000844 case DeclSpec::TST_underlyingType:
Sean Huntdb5d44b2011-05-19 05:37:45 +0000845 Result = S.GetTypeFromParser(DS.getRepAsType());
846 assert(!Result.isNull() && "Didn't get a type for __underlying_type?");
Sean Huntca63c202011-05-24 22:41:36 +0000847 Result = S.BuildUnaryTransformType(Result,
848 UnaryTransformType::EnumUnderlyingType,
849 DS.getTypeSpecTypeLoc());
850 if (Result.isNull()) {
851 Result = Context.IntTy;
852 declarator.setInvalidType(true);
Sean Huntdb5d44b2011-05-19 05:37:45 +0000853 }
854 break;
855
Anders Carlssone89d1592009-06-26 18:41:36 +0000856 case DeclSpec::TST_auto: {
857 // TypeQuals handled by caller.
Richard Smith34b41d92011-02-20 03:19:35 +0000858 Result = Context.getAutoType(QualType());
Anders Carlssone89d1592009-06-26 18:41:36 +0000859 break;
860 }
Mike Stump1eb44332009-09-09 15:08:12 +0000861
John McCalla5fc4722011-04-09 22:50:59 +0000862 case DeclSpec::TST_unknown_anytype:
863 Result = Context.UnknownAnyTy;
864 break;
865
Eli Friedmanb001de72011-10-06 23:00:33 +0000866 case DeclSpec::TST_atomic:
867 Result = S.GetTypeFromParser(DS.getRepAsType());
868 assert(!Result.isNull() && "Didn't get a type for _Atomic?");
869 Result = S.BuildAtomicType(Result, DS.getTypeSpecTypeLoc());
870 if (Result.isNull()) {
871 Result = Context.IntTy;
872 declarator.setInvalidType(true);
873 }
874 break;
875
Douglas Gregor809070a2009-02-18 17:45:20 +0000876 case DeclSpec::TST_error:
Chris Lattner5153ee62009-04-25 08:47:54 +0000877 Result = Context.IntTy;
John McCall711c52b2011-01-05 12:14:39 +0000878 declarator.setInvalidType(true);
Chris Lattner5153ee62009-04-25 08:47:54 +0000879 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000880 }
Mike Stump1eb44332009-09-09 15:08:12 +0000881
Chris Lattner958858e2008-02-20 21:40:32 +0000882 // Handle complex types.
Douglas Gregorf244cd72009-02-14 21:06:05 +0000883 if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000884 if (S.getLangOpts().Freestanding)
John McCall711c52b2011-01-05 12:14:39 +0000885 S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
Chris Lattnerfab5b452008-02-20 23:53:49 +0000886 Result = Context.getComplexType(Result);
John Thompson82287d12010-02-05 00:12:22 +0000887 } else if (DS.isTypeAltiVecVector()) {
888 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result));
889 assert(typeSize > 0 && "type size for vector must be greater than 0 bits");
Bob Wilsone86d78c2010-11-10 21:56:12 +0000890 VectorType::VectorKind VecKind = VectorType::AltiVecVector;
Chris Lattner788b0fd2010-06-23 06:00:24 +0000891 if (DS.isTypeAltiVecPixel())
Bob Wilsone86d78c2010-11-10 21:56:12 +0000892 VecKind = VectorType::AltiVecPixel;
Chris Lattner788b0fd2010-06-23 06:00:24 +0000893 else if (DS.isTypeAltiVecBool())
Bob Wilsone86d78c2010-11-10 21:56:12 +0000894 VecKind = VectorType::AltiVecBool;
895 Result = Context.getVectorType(Result, 128/typeSize, VecKind);
Douglas Gregorf244cd72009-02-14 21:06:05 +0000896 }
Mike Stump1eb44332009-09-09 15:08:12 +0000897
Argyrios Kyrtzidis47423bd2010-09-23 09:40:31 +0000898 // FIXME: Imaginary.
899 if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary)
John McCall711c52b2011-01-05 12:14:39 +0000900 S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported);
Mike Stump1eb44332009-09-09 15:08:12 +0000901
John McCall711c52b2011-01-05 12:14:39 +0000902 // Before we process any type attributes, synthesize a block literal
903 // function declarator if necessary.
904 if (declarator.getContext() == Declarator::BlockLiteralContext)
905 maybeSynthesizeBlockSignature(state, Result);
906
907 // Apply any type attributes from the decl spec. This may cause the
908 // list of type attributes to be temporarily saved while the type
909 // attributes are pushed around.
910 if (AttributeList *attrs = DS.getAttributes().getList())
911 processTypeAttrs(state, Result, true, attrs);
Mike Stump1eb44332009-09-09 15:08:12 +0000912
Chris Lattner96b77fc2008-04-02 06:50:17 +0000913 // Apply const/volatile/restrict qualifiers to T.
914 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
915
916 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
917 // or incomplete types shall not be restrict-qualified." C++ also allows
918 // restrict-qualified references.
John McCall0953e762009-09-24 19:53:00 +0000919 if (TypeQuals & DeclSpec::TQ_restrict) {
Fariborz Jahanian2b5ff1a2009-12-07 18:08:58 +0000920 if (Result->isAnyPointerType() || Result->isReferenceType()) {
921 QualType EltTy;
922 if (Result->isObjCObjectPointerType())
923 EltTy = Result;
924 else
925 EltTy = Result->isPointerType() ?
926 Result->getAs<PointerType>()->getPointeeType() :
927 Result->getAs<ReferenceType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +0000928
Douglas Gregorbad0e652009-03-24 20:32:41 +0000929 // If we have a pointer or reference, the pointee must have an object
Chris Lattnerbdcd6372008-04-02 17:35:06 +0000930 // incomplete type.
931 if (!EltTy->isIncompleteOrObjectType()) {
John McCall711c52b2011-01-05 12:14:39 +0000932 S.Diag(DS.getRestrictSpecLoc(),
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000933 diag::err_typecheck_invalid_restrict_invalid_pointee)
Chris Lattnerd1625842008-11-24 06:25:27 +0000934 << EltTy << DS.getSourceRange();
John McCall0953e762009-09-24 19:53:00 +0000935 TypeQuals &= ~DeclSpec::TQ_restrict; // Remove the restrict qualifier.
Chris Lattnerbdcd6372008-04-02 17:35:06 +0000936 }
937 } else {
John McCall711c52b2011-01-05 12:14:39 +0000938 S.Diag(DS.getRestrictSpecLoc(),
939 diag::err_typecheck_invalid_restrict_not_pointer)
Chris Lattnerd1625842008-11-24 06:25:27 +0000940 << Result << DS.getSourceRange();
John McCall0953e762009-09-24 19:53:00 +0000941 TypeQuals &= ~DeclSpec::TQ_restrict; // Remove the restrict qualifier.
Chris Lattner96b77fc2008-04-02 06:50:17 +0000942 }
Chris Lattner96b77fc2008-04-02 06:50:17 +0000943 }
Mike Stump1eb44332009-09-09 15:08:12 +0000944
Chris Lattner96b77fc2008-04-02 06:50:17 +0000945 // Warn about CV qualifiers on functions: C99 6.7.3p8: "If the specification
946 // of a function type includes any type qualifiers, the behavior is
947 // undefined."
948 if (Result->isFunctionType() && TypeQuals) {
949 // Get some location to point at, either the C or V location.
950 SourceLocation Loc;
John McCall0953e762009-09-24 19:53:00 +0000951 if (TypeQuals & DeclSpec::TQ_const)
Chris Lattner96b77fc2008-04-02 06:50:17 +0000952 Loc = DS.getConstSpecLoc();
John McCall0953e762009-09-24 19:53:00 +0000953 else if (TypeQuals & DeclSpec::TQ_volatile)
Chris Lattner96b77fc2008-04-02 06:50:17 +0000954 Loc = DS.getVolatileSpecLoc();
John McCall0953e762009-09-24 19:53:00 +0000955 else {
956 assert((TypeQuals & DeclSpec::TQ_restrict) &&
957 "Has CVR quals but not C, V, or R?");
958 Loc = DS.getRestrictSpecLoc();
Chris Lattner96b77fc2008-04-02 06:50:17 +0000959 }
John McCall711c52b2011-01-05 12:14:39 +0000960 S.Diag(Loc, diag::warn_typecheck_function_qualifiers)
Chris Lattnerd1625842008-11-24 06:25:27 +0000961 << Result << DS.getSourceRange();
Chris Lattner96b77fc2008-04-02 06:50:17 +0000962 }
Mike Stump1eb44332009-09-09 15:08:12 +0000963
Douglas Gregorf1f9b4e2008-11-03 15:51:28 +0000964 // C++ [dcl.ref]p1:
965 // Cv-qualified references are ill-formed except when the
966 // cv-qualifiers are introduced through the use of a typedef
967 // (7.1.3) or of a template type argument (14.3), in which
968 // case the cv-qualifiers are ignored.
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000969 // FIXME: Shouldn't we be checking SCS_typedef here?
970 if (DS.getTypeSpecType() == DeclSpec::TST_typename &&
Douglas Gregorf1f9b4e2008-11-03 15:51:28 +0000971 TypeQuals && Result->isReferenceType()) {
John McCall0953e762009-09-24 19:53:00 +0000972 TypeQuals &= ~DeclSpec::TQ_const;
973 TypeQuals &= ~DeclSpec::TQ_volatile;
Mike Stump1eb44332009-09-09 15:08:12 +0000974 }
975
John McCall0953e762009-09-24 19:53:00 +0000976 Qualifiers Quals = Qualifiers::fromCVRMask(TypeQuals);
977 Result = Context.getQualifiedType(Result, Quals);
Chris Lattner96b77fc2008-04-02 06:50:17 +0000978 }
John McCall0953e762009-09-24 19:53:00 +0000979
Chris Lattnerf1d705c2008-02-21 01:07:18 +0000980 return Result;
981}
982
Douglas Gregorcd281c32009-02-28 00:25:32 +0000983static std::string getPrintableNameForEntity(DeclarationName Entity) {
984 if (Entity)
985 return Entity.getAsString();
Mike Stump1eb44332009-09-09 15:08:12 +0000986
Douglas Gregorcd281c32009-02-28 00:25:32 +0000987 return "type name";
988}
989
John McCall28654742010-06-05 06:41:15 +0000990QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
991 Qualifiers Qs) {
992 // Enforce C99 6.7.3p2: "Types other than pointer types derived from
993 // object or incomplete types shall not be restrict-qualified."
994 if (Qs.hasRestrict()) {
995 unsigned DiagID = 0;
996 QualType ProblemTy;
997
998 const Type *Ty = T->getCanonicalTypeInternal().getTypePtr();
999 if (const ReferenceType *RTy = dyn_cast<ReferenceType>(Ty)) {
1000 if (!RTy->getPointeeType()->isIncompleteOrObjectType()) {
1001 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1002 ProblemTy = T->getAs<ReferenceType>()->getPointeeType();
1003 }
1004 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
1005 if (!PTy->getPointeeType()->isIncompleteOrObjectType()) {
1006 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1007 ProblemTy = T->getAs<PointerType>()->getPointeeType();
1008 }
1009 } else if (const MemberPointerType *PTy = dyn_cast<MemberPointerType>(Ty)) {
1010 if (!PTy->getPointeeType()->isIncompleteOrObjectType()) {
1011 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1012 ProblemTy = T->getAs<PointerType>()->getPointeeType();
1013 }
1014 } else if (!Ty->isDependentType()) {
1015 // FIXME: this deserves a proper diagnostic
1016 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1017 ProblemTy = T;
1018 }
1019
1020 if (DiagID) {
1021 Diag(Loc, DiagID) << ProblemTy;
1022 Qs.removeRestrict();
1023 }
1024 }
1025
1026 return Context.getQualifiedType(T, Qs);
1027}
1028
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001029/// \brief Build a paren type including \p T.
1030QualType Sema::BuildParenType(QualType T) {
1031 return Context.getParenType(T);
1032}
1033
John McCallf85e1932011-06-15 23:02:42 +00001034/// Given that we're building a pointer or reference to the given
1035static QualType inferARCLifetimeForPointee(Sema &S, QualType type,
1036 SourceLocation loc,
1037 bool isReference) {
1038 // Bail out if retention is unrequired or already specified.
1039 if (!type->isObjCLifetimeType() ||
1040 type.getObjCLifetime() != Qualifiers::OCL_None)
1041 return type;
1042
1043 Qualifiers::ObjCLifetime implicitLifetime = Qualifiers::OCL_None;
1044
1045 // If the object type is const-qualified, we can safely use
1046 // __unsafe_unretained. This is safe (because there are no read
1047 // barriers), and it'll be safe to coerce anything but __weak* to
1048 // the resulting type.
1049 if (type.isConstQualified()) {
1050 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1051
1052 // Otherwise, check whether the static type does not require
1053 // retaining. This currently only triggers for Class (possibly
1054 // protocol-qualifed, and arrays thereof).
1055 } else if (type->isObjCARCImplicitlyUnretainedType()) {
1056 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1057
Eli Friedmanef331b72012-01-20 01:26:23 +00001058 // If we are in an unevaluated context, like sizeof, skip adding a
1059 // qualification.
Eli Friedman78a54242012-01-21 04:44:06 +00001060 } else if (S.ExprEvalContexts.back().Context == Sema::Unevaluated) {
Eli Friedmanef331b72012-01-20 01:26:23 +00001061 return type;
Argyrios Kyrtzidis5b76f372011-09-20 23:49:22 +00001062
John McCalle8c904f2012-01-26 20:04:03 +00001063 // If that failed, give an error and recover using __strong. __strong
1064 // is the option most likely to prevent spurious second-order diagnostics,
1065 // like when binding a reference to a field.
John McCallf85e1932011-06-15 23:02:42 +00001066 } else {
1067 // These types can show up in private ivars in system headers, so
1068 // we need this to not be an error in those cases. Instead we
1069 // want to delay.
1070 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
Eli Friedmanef331b72012-01-20 01:26:23 +00001071 S.DelayedDiagnostics.add(
1072 sema::DelayedDiagnostic::makeForbiddenType(loc,
1073 diag::err_arc_indirect_no_ownership, type, isReference));
John McCallf85e1932011-06-15 23:02:42 +00001074 } else {
Eli Friedmanef331b72012-01-20 01:26:23 +00001075 S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference;
John McCallf85e1932011-06-15 23:02:42 +00001076 }
John McCalle8c904f2012-01-26 20:04:03 +00001077 implicitLifetime = Qualifiers::OCL_Strong;
John McCallf85e1932011-06-15 23:02:42 +00001078 }
1079 assert(implicitLifetime && "didn't infer any lifetime!");
1080
1081 Qualifiers qs;
1082 qs.addObjCLifetime(implicitLifetime);
1083 return S.Context.getQualifiedType(type, qs);
1084}
1085
Douglas Gregorcd281c32009-02-28 00:25:32 +00001086/// \brief Build a pointer type.
1087///
1088/// \param T The type to which we'll be building a pointer.
1089///
Douglas Gregorcd281c32009-02-28 00:25:32 +00001090/// \param Loc The location of the entity whose type involves this
1091/// pointer type or, if there is no such entity, the location of the
1092/// type that will have pointer type.
1093///
1094/// \param Entity The name of the entity that involves the pointer
1095/// type, if known.
1096///
1097/// \returns A suitable pointer type, if there are no
1098/// errors. Otherwise, returns a NULL type.
John McCall28654742010-06-05 06:41:15 +00001099QualType Sema::BuildPointerType(QualType T,
Douglas Gregorcd281c32009-02-28 00:25:32 +00001100 SourceLocation Loc, DeclarationName Entity) {
1101 if (T->isReferenceType()) {
1102 // C++ 8.3.2p4: There shall be no ... pointers to references ...
1103 Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
John McCallac406052009-10-30 00:37:20 +00001104 << getPrintableNameForEntity(Entity) << T;
Douglas Gregorcd281c32009-02-28 00:25:32 +00001105 return QualType();
1106 }
1107
John McCallc12c5bb2010-05-15 11:32:37 +00001108 assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType");
Douglas Gregor92e986e2010-04-22 16:44:27 +00001109
John McCallf85e1932011-06-15 23:02:42 +00001110 // In ARC, it is forbidden to build pointers to unqualified pointers.
David Blaikie4e4d0842012-03-11 07:00:24 +00001111 if (getLangOpts().ObjCAutoRefCount)
John McCallf85e1932011-06-15 23:02:42 +00001112 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false);
1113
Douglas Gregorcd281c32009-02-28 00:25:32 +00001114 // Build the pointer type.
John McCall28654742010-06-05 06:41:15 +00001115 return Context.getPointerType(T);
Douglas Gregorcd281c32009-02-28 00:25:32 +00001116}
1117
1118/// \brief Build a reference type.
1119///
1120/// \param T The type to which we'll be building a reference.
1121///
Douglas Gregorcd281c32009-02-28 00:25:32 +00001122/// \param Loc The location of the entity whose type involves this
1123/// reference type or, if there is no such entity, the location of the
1124/// type that will have reference type.
1125///
1126/// \param Entity The name of the entity that involves the reference
1127/// type, if known.
1128///
1129/// \returns A suitable reference type, if there are no
1130/// errors. Otherwise, returns a NULL type.
John McCall54e14c42009-10-22 22:37:11 +00001131QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue,
John McCall28654742010-06-05 06:41:15 +00001132 SourceLocation Loc,
John McCall54e14c42009-10-22 22:37:11 +00001133 DeclarationName Entity) {
Douglas Gregor9625e442011-05-21 22:16:50 +00001134 assert(Context.getCanonicalType(T) != Context.OverloadTy &&
1135 "Unresolved overloaded function type");
1136
Douglas Gregor69d83162011-01-20 16:08:06 +00001137 // C++0x [dcl.ref]p6:
1138 // If a typedef (7.1.3), a type template-parameter (14.3.1), or a
1139 // decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a
1140 // type T, an attempt to create the type "lvalue reference to cv TR" creates
1141 // the type "lvalue reference to T", while an attempt to create the type
1142 // "rvalue reference to cv TR" creates the type TR.
John McCall54e14c42009-10-22 22:37:11 +00001143 bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
1144
John McCall54e14c42009-10-22 22:37:11 +00001145 // C++ [dcl.ref]p4: There shall be no references to references.
1146 //
1147 // According to C++ DR 106, references to references are only
1148 // diagnosed when they are written directly (e.g., "int & &"),
1149 // but not when they happen via a typedef:
1150 //
1151 // typedef int& intref;
1152 // typedef intref& intref2;
1153 //
1154 // Parser::ParseDeclaratorInternal diagnoses the case where
1155 // references are written directly; here, we handle the
Douglas Gregor69d83162011-01-20 16:08:06 +00001156 // collapsing of references-to-references as described in C++0x.
1157 // DR 106 and 540 introduce reference-collapsing into C++98/03.
Douglas Gregorcd281c32009-02-28 00:25:32 +00001158
1159 // C++ [dcl.ref]p1:
Eli Friedman33a31382009-08-05 19:21:58 +00001160 // A declarator that specifies the type "reference to cv void"
Douglas Gregorcd281c32009-02-28 00:25:32 +00001161 // is ill-formed.
1162 if (T->isVoidType()) {
1163 Diag(Loc, diag::err_reference_to_void);
1164 return QualType();
1165 }
1166
John McCallf85e1932011-06-15 23:02:42 +00001167 // In ARC, it is forbidden to build references to unqualified pointers.
David Blaikie4e4d0842012-03-11 07:00:24 +00001168 if (getLangOpts().ObjCAutoRefCount)
John McCallf85e1932011-06-15 23:02:42 +00001169 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true);
1170
Douglas Gregorcd281c32009-02-28 00:25:32 +00001171 // Handle restrict on references.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001172 if (LValueRef)
John McCall28654742010-06-05 06:41:15 +00001173 return Context.getLValueReferenceType(T, SpelledAsLValue);
1174 return Context.getRValueReferenceType(T);
Douglas Gregorcd281c32009-02-28 00:25:32 +00001175}
1176
Chris Lattnere1eed382011-06-14 06:38:10 +00001177/// Check whether the specified array size makes the array type a VLA. If so,
1178/// return true, if not, return the size of the array in SizeVal.
Richard Smith282e7e62012-02-04 09:53:13 +00001179static bool isArraySizeVLA(Sema &S, Expr *ArraySize, llvm::APSInt &SizeVal) {
1180 // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode
1181 // (like gnu99, but not c99) accept any evaluatable value as an extension.
1182 return S.VerifyIntegerConstantExpression(
1183 ArraySize, &SizeVal, S.PDiag(), S.LangOpts.GNUMode,
1184 S.PDiag(diag::ext_vla_folded_to_constant)).isInvalid();
Chris Lattnere1eed382011-06-14 06:38:10 +00001185}
1186
1187
Douglas Gregorcd281c32009-02-28 00:25:32 +00001188/// \brief Build an array type.
1189///
1190/// \param T The type of each element in the array.
1191///
1192/// \param ASM C99 array size modifier (e.g., '*', 'static').
Mike Stump1eb44332009-09-09 15:08:12 +00001193///
1194/// \param ArraySize Expression describing the size of the array.
Douglas Gregorcd281c32009-02-28 00:25:32 +00001195///
Douglas Gregorcd281c32009-02-28 00:25:32 +00001196/// \param Loc The location of the entity whose type involves this
1197/// array type or, if there is no such entity, the location of the
1198/// type that will have array type.
1199///
1200/// \param Entity The name of the entity that involves the array
1201/// type, if known.
1202///
1203/// \returns A suitable array type, if there are no errors. Otherwise,
1204/// returns a NULL type.
1205QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1206 Expr *ArraySize, unsigned Quals,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001207 SourceRange Brackets, DeclarationName Entity) {
John McCall0953e762009-09-24 19:53:00 +00001208
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001209 SourceLocation Loc = Brackets.getBegin();
David Blaikie4e4d0842012-03-11 07:00:24 +00001210 if (getLangOpts().CPlusPlus) {
Douglas Gregor138bb232010-04-27 19:38:14 +00001211 // C++ [dcl.array]p1:
1212 // T is called the array element type; this type shall not be a reference
1213 // type, the (possibly cv-qualified) type void, a function type or an
1214 // abstract class type.
1215 //
1216 // Note: function types are handled in the common path with C.
1217 if (T->isReferenceType()) {
1218 Diag(Loc, diag::err_illegal_decl_array_of_references)
1219 << getPrintableNameForEntity(Entity) << T;
1220 return QualType();
1221 }
1222
Sebastian Redl923d56d2009-11-05 15:52:31 +00001223 if (T->isVoidType()) {
1224 Diag(Loc, diag::err_illegal_decl_array_incomplete_type) << T;
1225 return QualType();
1226 }
Douglas Gregor138bb232010-04-27 19:38:14 +00001227
1228 if (RequireNonAbstractType(Brackets.getBegin(), T,
1229 diag::err_array_of_abstract_type))
1230 return QualType();
1231
Sebastian Redl923d56d2009-11-05 15:52:31 +00001232 } else {
Douglas Gregor138bb232010-04-27 19:38:14 +00001233 // C99 6.7.5.2p1: If the element type is an incomplete or function type,
1234 // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
Sebastian Redl923d56d2009-11-05 15:52:31 +00001235 if (RequireCompleteType(Loc, T,
1236 diag::err_illegal_decl_array_incomplete_type))
1237 return QualType();
1238 }
Douglas Gregorcd281c32009-02-28 00:25:32 +00001239
1240 if (T->isFunctionType()) {
1241 Diag(Loc, diag::err_illegal_decl_array_of_functions)
John McCallac406052009-10-30 00:37:20 +00001242 << getPrintableNameForEntity(Entity) << T;
Douglas Gregorcd281c32009-02-28 00:25:32 +00001243 return QualType();
1244 }
Mike Stump1eb44332009-09-09 15:08:12 +00001245
Richard Smith34b41d92011-02-20 03:19:35 +00001246 if (T->getContainedAutoType()) {
1247 Diag(Loc, diag::err_illegal_decl_array_of_auto)
1248 << getPrintableNameForEntity(Entity) << T;
Anders Carlssone7cf07d2009-06-26 19:33:28 +00001249 return QualType();
1250 }
Mike Stump1eb44332009-09-09 15:08:12 +00001251
Ted Kremenek6217b802009-07-29 21:53:49 +00001252 if (const RecordType *EltTy = T->getAs<RecordType>()) {
Douglas Gregorcd281c32009-02-28 00:25:32 +00001253 // If the element type is a struct or union that contains a variadic
1254 // array, accept it as a GNU extension: C99 6.7.2.1p2.
1255 if (EltTy->getDecl()->hasFlexibleArrayMember())
1256 Diag(Loc, diag::ext_flexible_array_in_array) << T;
John McCallc12c5bb2010-05-15 11:32:37 +00001257 } else if (T->isObjCObjectType()) {
Chris Lattnerc7c11b12009-04-27 01:55:56 +00001258 Diag(Loc, diag::err_objc_array_of_interfaces) << T;
1259 return QualType();
Douglas Gregorcd281c32009-02-28 00:25:32 +00001260 }
Mike Stump1eb44332009-09-09 15:08:12 +00001261
John McCall806054d2012-01-11 00:14:46 +00001262 // Do placeholder conversions on the array size expression.
1263 if (ArraySize && ArraySize->hasPlaceholderType()) {
1264 ExprResult Result = CheckPlaceholderExpr(ArraySize);
1265 if (Result.isInvalid()) return QualType();
1266 ArraySize = Result.take();
1267 }
1268
John McCall5e3c67b2010-12-15 04:42:30 +00001269 // Do lvalue-to-rvalue conversions on the array size expression.
John Wiegley429bb272011-04-08 18:41:53 +00001270 if (ArraySize && !ArraySize->isRValue()) {
1271 ExprResult Result = DefaultLvalueConversion(ArraySize);
1272 if (Result.isInvalid())
1273 return QualType();
1274
1275 ArraySize = Result.take();
1276 }
John McCall5e3c67b2010-12-15 04:42:30 +00001277
Douglas Gregorcd281c32009-02-28 00:25:32 +00001278 // C99 6.7.5.2p1: The size expression shall have integer type.
Richard Smith282e7e62012-02-04 09:53:13 +00001279 // C++11 allows contextual conversions to such types.
David Blaikie4e4d0842012-03-11 07:00:24 +00001280 if (!getLangOpts().CPlusPlus0x &&
Richard Smith282e7e62012-02-04 09:53:13 +00001281 ArraySize && !ArraySize->isTypeDependent() &&
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001282 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
Douglas Gregorcd281c32009-02-28 00:25:32 +00001283 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
1284 << ArraySize->getType() << ArraySize->getSourceRange();
Douglas Gregorcd281c32009-02-28 00:25:32 +00001285 return QualType();
1286 }
Richard Smith282e7e62012-02-04 09:53:13 +00001287
Douglas Gregor2767ce22010-08-18 00:39:00 +00001288 llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType()));
Douglas Gregorcd281c32009-02-28 00:25:32 +00001289 if (!ArraySize) {
Eli Friedmanf91f5c82009-04-26 21:57:51 +00001290 if (ASM == ArrayType::Star)
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001291 T = Context.getVariableArrayType(T, 0, ASM, Quals, Brackets);
Eli Friedmanf91f5c82009-04-26 21:57:51 +00001292 else
1293 T = Context.getIncompleteArrayType(T, ASM, Quals);
Douglas Gregorac06a0e2010-05-18 23:01:22 +00001294 } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) {
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001295 T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets);
Richard Smith282e7e62012-02-04 09:53:13 +00001296 } else if ((!T->isDependentType() && !T->isIncompleteType() &&
1297 !T->isConstantSizeType()) ||
1298 isArraySizeVLA(*this, ArraySize, ConstVal)) {
1299 // Even in C++11, don't allow contextual conversions in the array bound
1300 // of a VLA.
David Blaikie4e4d0842012-03-11 07:00:24 +00001301 if (getLangOpts().CPlusPlus0x &&
Richard Smith282e7e62012-02-04 09:53:13 +00001302 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
1303 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
1304 << ArraySize->getType() << ArraySize->getSourceRange();
1305 return QualType();
1306 }
1307
Chris Lattnere1eed382011-06-14 06:38:10 +00001308 // C99: an array with an element type that has a non-constant-size is a VLA.
Chris Lattnere1eed382011-06-14 06:38:10 +00001309 // C99: an array with a non-ICE size is a VLA. We accept any expression
1310 // that we can fold to a non-zero positive value as an extension.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001311 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
Douglas Gregorcd281c32009-02-28 00:25:32 +00001312 } else {
1313 // C99 6.7.5.2p1: If the expression is a constant expression, it shall
1314 // have a value greater than zero.
Sebastian Redl923d56d2009-11-05 15:52:31 +00001315 if (ConstVal.isSigned() && ConstVal.isNegative()) {
Chandler Carruthb2b5cc02011-01-04 04:44:35 +00001316 if (Entity)
1317 Diag(ArraySize->getLocStart(), diag::err_decl_negative_array_size)
1318 << getPrintableNameForEntity(Entity) << ArraySize->getSourceRange();
1319 else
1320 Diag(ArraySize->getLocStart(), diag::err_typecheck_negative_array_size)
1321 << ArraySize->getSourceRange();
Sebastian Redl923d56d2009-11-05 15:52:31 +00001322 return QualType();
1323 }
1324 if (ConstVal == 0) {
Douglas Gregor02024a92010-03-28 02:42:43 +00001325 // GCC accepts zero sized static arrays. We allow them when
1326 // we're not in a SFINAE context.
1327 Diag(ArraySize->getLocStart(),
1328 isSFINAEContext()? diag::err_typecheck_zero_array_size
1329 : diag::ext_typecheck_zero_array_size)
Sebastian Redl923d56d2009-11-05 15:52:31 +00001330 << ArraySize->getSourceRange();
Peter Collingbourne20cdbeb2011-10-16 21:17:32 +00001331
1332 if (ASM == ArrayType::Static) {
1333 Diag(ArraySize->getLocStart(),
1334 diag::warn_typecheck_zero_static_array_size)
1335 << ArraySize->getSourceRange();
1336 ASM = ArrayType::Normal;
1337 }
Douglas Gregor2767ce22010-08-18 00:39:00 +00001338 } else if (!T->isDependentType() && !T->isVariablyModifiedType() &&
1339 !T->isIncompleteType()) {
1340 // Is the array too large?
1341 unsigned ActiveSizeBits
1342 = ConstantArrayType::getNumAddressingBits(Context, T, ConstVal);
1343 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
1344 Diag(ArraySize->getLocStart(), diag::err_array_too_large)
1345 << ConstVal.toString(10)
1346 << ArraySize->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001347 }
Douglas Gregor2767ce22010-08-18 00:39:00 +00001348
John McCall46a617a2009-10-16 00:14:28 +00001349 T = Context.getConstantArrayType(T, ConstVal, ASM, Quals);
Douglas Gregorcd281c32009-02-28 00:25:32 +00001350 }
David Chisnallaf407762010-01-11 23:08:08 +00001351 // If this is not C99, extwarn about VLA's and C99 array size modifiers.
David Blaikie4e4d0842012-03-11 07:00:24 +00001352 if (!getLangOpts().C99) {
Douglas Gregor0fddb972010-05-22 16:17:30 +00001353 if (T->isVariableArrayType()) {
1354 // Prohibit the use of non-POD types in VLAs.
John McCallf85e1932011-06-15 23:02:42 +00001355 QualType BaseT = Context.getBaseElementType(T);
Douglas Gregor204ce172010-05-24 20:42:30 +00001356 if (!T->isDependentType() &&
John McCallf85e1932011-06-15 23:02:42 +00001357 !BaseT.isPODType(Context) &&
1358 !BaseT->isObjCLifetimeType()) {
Douglas Gregor0fddb972010-05-22 16:17:30 +00001359 Diag(Loc, diag::err_vla_non_pod)
John McCallf85e1932011-06-15 23:02:42 +00001360 << BaseT;
Douglas Gregor0fddb972010-05-22 16:17:30 +00001361 return QualType();
1362 }
Douglas Gregora481ec42010-05-23 19:57:01 +00001363 // Prohibit the use of VLAs during template argument deduction.
1364 else if (isSFINAEContext()) {
1365 Diag(Loc, diag::err_vla_in_sfinae);
1366 return QualType();
1367 }
Douglas Gregor0fddb972010-05-22 16:17:30 +00001368 // Just extwarn about VLAs.
1369 else
1370 Diag(Loc, diag::ext_vla);
1371 } else if (ASM != ArrayType::Normal || Quals != 0)
Richard Smithd7c56e12011-12-29 21:57:33 +00001372 Diag(Loc,
David Blaikie4e4d0842012-03-11 07:00:24 +00001373 getLangOpts().CPlusPlus? diag::err_c99_array_usage_cxx
Richard Smithd7c56e12011-12-29 21:57:33 +00001374 : diag::ext_c99_array_usage) << ASM;
Douglas Gregorcd281c32009-02-28 00:25:32 +00001375 }
1376
1377 return T;
1378}
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001379
1380/// \brief Build an ext-vector type.
1381///
1382/// Run the required checks for the extended vector type.
John McCall9ae2f072010-08-23 23:25:46 +00001383QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize,
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001384 SourceLocation AttrLoc) {
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001385 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1386 // in conjunction with complex types (pointers, arrays, functions, etc.).
Mike Stump1eb44332009-09-09 15:08:12 +00001387 if (!T->isDependentType() &&
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001388 !T->isIntegerType() && !T->isRealFloatingType()) {
1389 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
1390 return QualType();
1391 }
1392
John McCall9ae2f072010-08-23 23:25:46 +00001393 if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) {
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001394 llvm::APSInt vecSize(32);
John McCall9ae2f072010-08-23 23:25:46 +00001395 if (!ArraySize->isIntegerConstantExpr(vecSize, Context)) {
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001396 Diag(AttrLoc, diag::err_attribute_argument_not_int)
John McCall9ae2f072010-08-23 23:25:46 +00001397 << "ext_vector_type" << ArraySize->getSourceRange();
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001398 return QualType();
1399 }
Mike Stump1eb44332009-09-09 15:08:12 +00001400
1401 // unlike gcc's vector_size attribute, the size is specified as the
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001402 // number of elements, not the number of bytes.
Mike Stump1eb44332009-09-09 15:08:12 +00001403 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
1404
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001405 if (vectorSize == 0) {
1406 Diag(AttrLoc, diag::err_attribute_zero_size)
John McCall9ae2f072010-08-23 23:25:46 +00001407 << ArraySize->getSourceRange();
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001408 return QualType();
1409 }
Mike Stump1eb44332009-09-09 15:08:12 +00001410
Douglas Gregor4ac01402011-06-15 16:02:29 +00001411 return Context.getExtVectorType(T, vectorSize);
Mike Stump1eb44332009-09-09 15:08:12 +00001412 }
1413
John McCall9ae2f072010-08-23 23:25:46 +00001414 return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc);
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001415}
Mike Stump1eb44332009-09-09 15:08:12 +00001416
Douglas Gregor724651c2009-02-28 01:04:19 +00001417/// \brief Build a function type.
1418///
1419/// This routine checks the function type according to C++ rules and
1420/// under the assumption that the result type and parameter types have
1421/// just been instantiated from a template. It therefore duplicates
Douglas Gregor2943aed2009-03-03 04:44:36 +00001422/// some of the behavior of GetTypeForDeclarator, but in a much
Douglas Gregor724651c2009-02-28 01:04:19 +00001423/// simpler form that is only suitable for this narrow use case.
1424///
1425/// \param T The return type of the function.
1426///
1427/// \param ParamTypes The parameter types of the function. This array
1428/// will be modified to account for adjustments to the types of the
1429/// function parameters.
1430///
1431/// \param NumParamTypes The number of parameter types in ParamTypes.
1432///
1433/// \param Variadic Whether this is a variadic function type.
1434///
Richard Smitheefb3d52012-02-10 09:58:53 +00001435/// \param HasTrailingReturn Whether this function has a trailing return type.
1436///
Douglas Gregor724651c2009-02-28 01:04:19 +00001437/// \param Quals The cvr-qualifiers to be applied to the function type.
1438///
1439/// \param Loc The location of the entity whose type involves this
1440/// function type or, if there is no such entity, the location of the
1441/// type that will have function type.
1442///
1443/// \param Entity The name of the entity that involves the function
1444/// type, if known.
1445///
1446/// \returns A suitable function type, if there are no
1447/// errors. Otherwise, returns a NULL type.
1448QualType Sema::BuildFunctionType(QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00001449 QualType *ParamTypes,
Douglas Gregor724651c2009-02-28 01:04:19 +00001450 unsigned NumParamTypes,
Richard Smitheefb3d52012-02-10 09:58:53 +00001451 bool Variadic, bool HasTrailingReturn,
1452 unsigned Quals,
Douglas Gregorc938c162011-01-26 05:01:58 +00001453 RefQualifierKind RefQualifier,
Eli Friedmanfa869542010-08-05 02:54:05 +00001454 SourceLocation Loc, DeclarationName Entity,
John McCalle23cf432010-12-14 08:05:40 +00001455 FunctionType::ExtInfo Info) {
Douglas Gregor724651c2009-02-28 01:04:19 +00001456 if (T->isArrayType() || T->isFunctionType()) {
Douglas Gregor58408bc2010-01-11 18:46:21 +00001457 Diag(Loc, diag::err_func_returning_array_function)
1458 << T->isFunctionType() << T;
Douglas Gregor724651c2009-02-28 01:04:19 +00001459 return QualType();
1460 }
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001461
1462 // Functions cannot return half FP.
1463 if (T->isHalfType()) {
1464 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 <<
1465 FixItHint::CreateInsertion(Loc, "*");
1466 return QualType();
1467 }
1468
Douglas Gregor724651c2009-02-28 01:04:19 +00001469 bool Invalid = false;
1470 for (unsigned Idx = 0; Idx < NumParamTypes; ++Idx) {
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001471 // FIXME: Loc is too inprecise here, should use proper locations for args.
Douglas Gregor79e6bd32011-07-12 04:42:08 +00001472 QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001473 if (ParamType->isVoidType()) {
Douglas Gregor724651c2009-02-28 01:04:19 +00001474 Diag(Loc, diag::err_param_with_void_type);
1475 Invalid = true;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001476 } else if (ParamType->isHalfType()) {
1477 // Disallow half FP arguments.
1478 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 <<
1479 FixItHint::CreateInsertion(Loc, "*");
1480 Invalid = true;
Douglas Gregor724651c2009-02-28 01:04:19 +00001481 }
Douglas Gregorcd281c32009-02-28 00:25:32 +00001482
John McCall54e14c42009-10-22 22:37:11 +00001483 ParamTypes[Idx] = ParamType;
Douglas Gregor724651c2009-02-28 01:04:19 +00001484 }
1485
1486 if (Invalid)
1487 return QualType();
1488
John McCalle23cf432010-12-14 08:05:40 +00001489 FunctionProtoType::ExtProtoInfo EPI;
1490 EPI.Variadic = Variadic;
Richard Smitheefb3d52012-02-10 09:58:53 +00001491 EPI.HasTrailingReturn = HasTrailingReturn;
John McCalle23cf432010-12-14 08:05:40 +00001492 EPI.TypeQuals = Quals;
Douglas Gregorc938c162011-01-26 05:01:58 +00001493 EPI.RefQualifier = RefQualifier;
John McCalle23cf432010-12-14 08:05:40 +00001494 EPI.ExtInfo = Info;
1495
1496 return Context.getFunctionType(T, ParamTypes, NumParamTypes, EPI);
Douglas Gregor724651c2009-02-28 01:04:19 +00001497}
Mike Stump1eb44332009-09-09 15:08:12 +00001498
Douglas Gregor949bf692009-06-09 22:17:39 +00001499/// \brief Build a member pointer type \c T Class::*.
1500///
1501/// \param T the type to which the member pointer refers.
1502/// \param Class the class type into which the member pointer points.
Douglas Gregor949bf692009-06-09 22:17:39 +00001503/// \param Loc the location where this type begins
1504/// \param Entity the name of the entity that will have this member pointer type
1505///
1506/// \returns a member pointer type, if successful, or a NULL type if there was
1507/// an error.
Mike Stump1eb44332009-09-09 15:08:12 +00001508QualType Sema::BuildMemberPointerType(QualType T, QualType Class,
John McCall28654742010-06-05 06:41:15 +00001509 SourceLocation Loc,
Douglas Gregor949bf692009-06-09 22:17:39 +00001510 DeclarationName Entity) {
1511 // Verify that we're not building a pointer to pointer to function with
1512 // exception specification.
1513 if (CheckDistantExceptionSpec(T)) {
1514 Diag(Loc, diag::err_distant_exception_spec);
1515
1516 // FIXME: If we're doing this as part of template instantiation,
1517 // we should return immediately.
1518
1519 // Build the type anyway, but use the canonical type so that the
1520 // exception specifiers are stripped off.
1521 T = Context.getCanonicalType(T);
1522 }
1523
Sebastian Redl73780122010-06-09 21:19:43 +00001524 // C++ 8.3.3p3: A pointer to member shall not point to ... a member
Douglas Gregor949bf692009-06-09 22:17:39 +00001525 // with reference type, or "cv void."
1526 if (T->isReferenceType()) {
Anders Carlsson8d4655d2009-06-30 00:06:57 +00001527 Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
John McCallac406052009-10-30 00:37:20 +00001528 << (Entity? Entity.getAsString() : "type name") << T;
Douglas Gregor949bf692009-06-09 22:17:39 +00001529 return QualType();
1530 }
1531
1532 if (T->isVoidType()) {
1533 Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
1534 << (Entity? Entity.getAsString() : "type name");
1535 return QualType();
1536 }
1537
Douglas Gregor949bf692009-06-09 22:17:39 +00001538 if (!Class->isDependentType() && !Class->isRecordType()) {
1539 Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
1540 return QualType();
1541 }
1542
Charles Davisd18f9f92010-08-16 04:01:50 +00001543 // In the Microsoft ABI, the class is allowed to be an incomplete
1544 // type. In such cases, the compiler makes a worst-case assumption.
1545 // We make no such assumption right now, so emit an error if the
1546 // class isn't a complete type.
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001547 if (Context.getTargetInfo().getCXXABI() == CXXABI_Microsoft &&
Charles Davisd18f9f92010-08-16 04:01:50 +00001548 RequireCompleteType(Loc, Class, diag::err_incomplete_type))
1549 return QualType();
1550
John McCall28654742010-06-05 06:41:15 +00001551 return Context.getMemberPointerType(T, Class.getTypePtr());
Douglas Gregor949bf692009-06-09 22:17:39 +00001552}
Mike Stump1eb44332009-09-09 15:08:12 +00001553
Anders Carlsson9a917e42009-06-12 22:56:54 +00001554/// \brief Build a block pointer type.
1555///
1556/// \param T The type to which we'll be building a block pointer.
1557///
John McCall0953e762009-09-24 19:53:00 +00001558/// \param CVR The cvr-qualifiers to be applied to the block pointer type.
Anders Carlsson9a917e42009-06-12 22:56:54 +00001559///
1560/// \param Loc The location of the entity whose type involves this
1561/// block pointer type or, if there is no such entity, the location of the
1562/// type that will have block pointer type.
1563///
1564/// \param Entity The name of the entity that involves the block pointer
1565/// type, if known.
1566///
1567/// \returns A suitable block pointer type, if there are no
1568/// errors. Otherwise, returns a NULL type.
John McCall28654742010-06-05 06:41:15 +00001569QualType Sema::BuildBlockPointerType(QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00001570 SourceLocation Loc,
Anders Carlsson9a917e42009-06-12 22:56:54 +00001571 DeclarationName Entity) {
John McCall0953e762009-09-24 19:53:00 +00001572 if (!T->isFunctionType()) {
Anders Carlsson9a917e42009-06-12 22:56:54 +00001573 Diag(Loc, diag::err_nonfunction_block_type);
1574 return QualType();
1575 }
Mike Stump1eb44332009-09-09 15:08:12 +00001576
John McCall28654742010-06-05 06:41:15 +00001577 return Context.getBlockPointerType(T);
Anders Carlsson9a917e42009-06-12 22:56:54 +00001578}
1579
John McCallb3d87482010-08-24 05:47:05 +00001580QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) {
1581 QualType QT = Ty.get();
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001582 if (QT.isNull()) {
John McCalla93c9342009-12-07 02:54:59 +00001583 if (TInfo) *TInfo = 0;
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001584 return QualType();
1585 }
1586
John McCalla93c9342009-12-07 02:54:59 +00001587 TypeSourceInfo *DI = 0;
John McCallf4c73712011-01-19 06:33:43 +00001588 if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001589 QT = LIT->getType();
John McCalla93c9342009-12-07 02:54:59 +00001590 DI = LIT->getTypeSourceInfo();
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001591 }
Mike Stump1eb44332009-09-09 15:08:12 +00001592
John McCalla93c9342009-12-07 02:54:59 +00001593 if (TInfo) *TInfo = DI;
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001594 return QT;
1595}
1596
Argyrios Kyrtzidisa8349f52011-07-01 22:23:05 +00001597static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
1598 Qualifiers::ObjCLifetime ownership,
1599 unsigned chunkIndex);
1600
John McCallf85e1932011-06-15 23:02:42 +00001601/// Given that this is the declaration of a parameter under ARC,
1602/// attempt to infer attributes and such for pointer-to-whatever
1603/// types.
1604static void inferARCWriteback(TypeProcessingState &state,
1605 QualType &declSpecType) {
1606 Sema &S = state.getSema();
1607 Declarator &declarator = state.getDeclarator();
1608
1609 // TODO: should we care about decl qualifiers?
1610
1611 // Check whether the declarator has the expected form. We walk
1612 // from the inside out in order to make the block logic work.
1613 unsigned outermostPointerIndex = 0;
1614 bool isBlockPointer = false;
1615 unsigned numPointers = 0;
1616 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
1617 unsigned chunkIndex = i;
1618 DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex);
1619 switch (chunk.Kind) {
1620 case DeclaratorChunk::Paren:
1621 // Ignore parens.
1622 break;
1623
1624 case DeclaratorChunk::Reference:
1625 case DeclaratorChunk::Pointer:
1626 // Count the number of pointers. Treat references
1627 // interchangeably as pointers; if they're mis-ordered, normal
1628 // type building will discover that.
1629 outermostPointerIndex = chunkIndex;
1630 numPointers++;
1631 break;
1632
1633 case DeclaratorChunk::BlockPointer:
1634 // If we have a pointer to block pointer, that's an acceptable
1635 // indirect reference; anything else is not an application of
1636 // the rules.
1637 if (numPointers != 1) return;
1638 numPointers++;
1639 outermostPointerIndex = chunkIndex;
1640 isBlockPointer = true;
1641
1642 // We don't care about pointer structure in return values here.
1643 goto done;
1644
1645 case DeclaratorChunk::Array: // suppress if written (id[])?
1646 case DeclaratorChunk::Function:
1647 case DeclaratorChunk::MemberPointer:
1648 return;
1649 }
1650 }
1651 done:
1652
1653 // If we have *one* pointer, then we want to throw the qualifier on
1654 // the declaration-specifiers, which means that it needs to be a
1655 // retainable object type.
1656 if (numPointers == 1) {
1657 // If it's not a retainable object type, the rule doesn't apply.
1658 if (!declSpecType->isObjCRetainableType()) return;
1659
1660 // If it already has lifetime, don't do anything.
1661 if (declSpecType.getObjCLifetime()) return;
1662
1663 // Otherwise, modify the type in-place.
1664 Qualifiers qs;
1665
1666 if (declSpecType->isObjCARCImplicitlyUnretainedType())
1667 qs.addObjCLifetime(Qualifiers::OCL_ExplicitNone);
1668 else
1669 qs.addObjCLifetime(Qualifiers::OCL_Autoreleasing);
1670 declSpecType = S.Context.getQualifiedType(declSpecType, qs);
1671
1672 // If we have *two* pointers, then we want to throw the qualifier on
1673 // the outermost pointer.
1674 } else if (numPointers == 2) {
1675 // If we don't have a block pointer, we need to check whether the
1676 // declaration-specifiers gave us something that will turn into a
1677 // retainable object pointer after we slap the first pointer on it.
1678 if (!isBlockPointer && !declSpecType->isObjCObjectType())
1679 return;
1680
1681 // Look for an explicit lifetime attribute there.
1682 DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex);
Argyrios Kyrtzidis1c73dcb2011-07-01 22:23:03 +00001683 if (chunk.Kind != DeclaratorChunk::Pointer &&
1684 chunk.Kind != DeclaratorChunk::BlockPointer)
1685 return;
John McCallf85e1932011-06-15 23:02:42 +00001686 for (const AttributeList *attr = chunk.getAttrs(); attr;
1687 attr = attr->getNext())
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00001688 if (attr->getKind() == AttributeList::AT_objc_ownership)
John McCallf85e1932011-06-15 23:02:42 +00001689 return;
1690
Argyrios Kyrtzidisa8349f52011-07-01 22:23:05 +00001691 transferARCOwnershipToDeclaratorChunk(state, Qualifiers::OCL_Autoreleasing,
1692 outermostPointerIndex);
John McCallf85e1932011-06-15 23:02:42 +00001693
1694 // Any other number of pointers/references does not trigger the rule.
1695 } else return;
1696
1697 // TODO: mark whether we did this inference?
1698}
1699
Chandler Carruthd067c072011-02-23 18:51:59 +00001700static void DiagnoseIgnoredQualifiers(unsigned Quals,
1701 SourceLocation ConstQualLoc,
1702 SourceLocation VolatileQualLoc,
1703 SourceLocation RestrictQualLoc,
1704 Sema& S) {
1705 std::string QualStr;
1706 unsigned NumQuals = 0;
1707 SourceLocation Loc;
1708
1709 FixItHint ConstFixIt;
1710 FixItHint VolatileFixIt;
1711 FixItHint RestrictFixIt;
1712
Hans Wennborga08fcb82011-06-03 17:37:26 +00001713 const SourceManager &SM = S.getSourceManager();
1714
Chandler Carruthd067c072011-02-23 18:51:59 +00001715 // FIXME: The locations here are set kind of arbitrarily. It'd be nicer to
1716 // find a range and grow it to encompass all the qualifiers, regardless of
1717 // the order in which they textually appear.
1718 if (Quals & Qualifiers::Const) {
1719 ConstFixIt = FixItHint::CreateRemoval(ConstQualLoc);
Chandler Carruthd067c072011-02-23 18:51:59 +00001720 QualStr = "const";
Hans Wennborga08fcb82011-06-03 17:37:26 +00001721 ++NumQuals;
1722 if (!Loc.isValid() || SM.isBeforeInTranslationUnit(ConstQualLoc, Loc))
1723 Loc = ConstQualLoc;
Chandler Carruthd067c072011-02-23 18:51:59 +00001724 }
1725 if (Quals & Qualifiers::Volatile) {
1726 VolatileFixIt = FixItHint::CreateRemoval(VolatileQualLoc);
Hans Wennborga08fcb82011-06-03 17:37:26 +00001727 QualStr += (NumQuals == 0 ? "volatile" : " volatile");
Chandler Carruthd067c072011-02-23 18:51:59 +00001728 ++NumQuals;
Hans Wennborga08fcb82011-06-03 17:37:26 +00001729 if (!Loc.isValid() || SM.isBeforeInTranslationUnit(VolatileQualLoc, Loc))
1730 Loc = VolatileQualLoc;
Chandler Carruthd067c072011-02-23 18:51:59 +00001731 }
1732 if (Quals & Qualifiers::Restrict) {
1733 RestrictFixIt = FixItHint::CreateRemoval(RestrictQualLoc);
Hans Wennborga08fcb82011-06-03 17:37:26 +00001734 QualStr += (NumQuals == 0 ? "restrict" : " restrict");
Chandler Carruthd067c072011-02-23 18:51:59 +00001735 ++NumQuals;
Hans Wennborga08fcb82011-06-03 17:37:26 +00001736 if (!Loc.isValid() || SM.isBeforeInTranslationUnit(RestrictQualLoc, Loc))
1737 Loc = RestrictQualLoc;
Chandler Carruthd067c072011-02-23 18:51:59 +00001738 }
1739
1740 assert(NumQuals > 0 && "No known qualifiers?");
1741
1742 S.Diag(Loc, diag::warn_qual_return_type)
Hans Wennborga08fcb82011-06-03 17:37:26 +00001743 << QualStr << NumQuals << ConstFixIt << VolatileFixIt << RestrictFixIt;
Chandler Carruthd067c072011-02-23 18:51:59 +00001744}
1745
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001746static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state,
1747 TypeSourceInfo *&ReturnTypeInfo) {
1748 Sema &SemaRef = state.getSema();
1749 Declarator &D = state.getDeclarator();
Douglas Gregor930d8b52009-01-30 22:09:00 +00001750 QualType T;
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001751 ReturnTypeInfo = 0;
1752
1753 // The TagDecl owned by the DeclSpec.
Argyrios Kyrtzidisd3880f82011-06-28 03:01:18 +00001754 TagDecl *OwnedTagDecl = 0;
John McCall711c52b2011-01-05 12:14:39 +00001755
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001756 switch (D.getName().getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001757 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001758 case UnqualifiedId::IK_OperatorFunctionId:
Sebastian Redl8999fe12011-03-14 18:08:30 +00001759 case UnqualifiedId::IK_Identifier:
Sean Hunt0486d742009-11-28 04:44:28 +00001760 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001761 case UnqualifiedId::IK_TemplateId:
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001762 T = ConvertDeclSpecToType(state);
Chris Lattner5db2bb12009-10-25 18:21:37 +00001763
Douglas Gregor591bd3c2010-02-08 22:07:33 +00001764 if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) {
Argyrios Kyrtzidisd3880f82011-06-28 03:01:18 +00001765 OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
Abramo Bagnara15987972011-03-08 22:33:38 +00001766 // Owned declaration is embedded in declarator.
Argyrios Kyrtzidisd3880f82011-06-28 03:01:18 +00001767 OwnedTagDecl->setEmbeddedInDeclarator(true);
Douglas Gregor591bd3c2010-02-08 22:07:33 +00001768 }
Douglas Gregor930d8b52009-01-30 22:09:00 +00001769 break;
1770
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001771 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00001772 case UnqualifiedId::IK_ConstructorTemplateId:
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001773 case UnqualifiedId::IK_DestructorName:
Douglas Gregor930d8b52009-01-30 22:09:00 +00001774 // Constructors and destructors don't have return types. Use
Douglas Gregor48026d22010-01-11 18:40:55 +00001775 // "void" instead.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001776 T = SemaRef.Context.VoidTy;
Douglas Gregor930d8b52009-01-30 22:09:00 +00001777 break;
Douglas Gregor48026d22010-01-11 18:40:55 +00001778
1779 case UnqualifiedId::IK_ConversionFunctionId:
1780 // The result type of a conversion function is the type that it
1781 // converts to.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001782 T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId,
1783 &ReturnTypeInfo);
Douglas Gregor48026d22010-01-11 18:40:55 +00001784 break;
Douglas Gregor930d8b52009-01-30 22:09:00 +00001785 }
Douglas Gregordab60ad2010-10-01 18:44:50 +00001786
John McCall711c52b2011-01-05 12:14:39 +00001787 if (D.getAttributes())
1788 distributeTypeAttrsFromDeclarator(state, T);
1789
Richard Smithd37b3602012-02-10 11:05:11 +00001790 // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context.
1791 // In C++11, a function declarator using 'auto' must have a trailing return
Richard Smith8110f042011-02-22 01:22:29 +00001792 // type (this is checked later) and we can skip this. In other languages
1793 // using auto, we need to check regardless.
Richard Smith34b41d92011-02-20 03:19:35 +00001794 if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto &&
David Blaikie4e4d0842012-03-11 07:00:24 +00001795 (!SemaRef.getLangOpts().CPlusPlus0x || !D.isFunctionDeclarator())) {
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001796 int Error = -1;
Mike Stump1eb44332009-09-09 15:08:12 +00001797
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001798 switch (D.getContext()) {
1799 case Declarator::KNRTypeListContext:
David Blaikieb219cfc2011-09-23 05:06:16 +00001800 llvm_unreachable("K&R type lists aren't allowed in C++");
Eli Friedmanf88c4002012-01-04 04:41:38 +00001801 case Declarator::LambdaExprContext:
1802 llvm_unreachable("Can't specify a type specifier in lambda grammar");
John McCallcdda47f2011-10-01 09:56:14 +00001803 case Declarator::ObjCParameterContext:
1804 case Declarator::ObjCResultContext:
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001805 case Declarator::PrototypeContext:
1806 Error = 0; // Function prototype
1807 break;
1808 case Declarator::MemberContext:
Richard Smith7a614d82011-06-11 17:19:42 +00001809 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)
1810 break;
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001811 switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) {
David Blaikieeb2d1f12011-09-23 20:26:49 +00001812 case TTK_Enum: llvm_unreachable("unhandled tag kind");
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001813 case TTK_Struct: Error = 1; /* Struct member */ break;
1814 case TTK_Union: Error = 2; /* Union member */ break;
1815 case TTK_Class: Error = 3; /* Class member */ break;
Mike Stump1eb44332009-09-09 15:08:12 +00001816 }
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001817 break;
1818 case Declarator::CXXCatchContext:
Argyrios Kyrtzidis17b63992011-07-01 22:22:40 +00001819 case Declarator::ObjCCatchContext:
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001820 Error = 4; // Exception declaration
1821 break;
1822 case Declarator::TemplateParamContext:
1823 Error = 5; // Template parameter
1824 break;
1825 case Declarator::BlockLiteralContext:
Richard Smith34b41d92011-02-20 03:19:35 +00001826 Error = 6; // Block literal
1827 break;
1828 case Declarator::TemplateTypeArgContext:
1829 Error = 7; // Template type argument
1830 break;
Richard Smith162e1c12011-04-15 14:24:37 +00001831 case Declarator::AliasDeclContext:
Richard Smith3e4c6c42011-05-05 21:57:07 +00001832 case Declarator::AliasTemplateContext:
Richard Smith162e1c12011-04-15 14:24:37 +00001833 Error = 9; // Type alias
1834 break;
Richard Smith7796eb52012-03-12 08:56:40 +00001835 case Declarator::TrailingReturnContext:
1836 Error = 10; // Function return type
1837 break;
Richard Smith34b41d92011-02-20 03:19:35 +00001838 case Declarator::TypeNameContext:
Argyrios Kyrtzidis0b8c98f2011-06-28 03:01:23 +00001839 Error = 11; // Generic
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001840 break;
1841 case Declarator::FileContext:
1842 case Declarator::BlockContext:
1843 case Declarator::ForContext:
1844 case Declarator::ConditionContext:
Argyrios Kyrtzidis0b8c98f2011-06-28 03:01:23 +00001845 case Declarator::CXXNewContext:
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001846 break;
1847 }
1848
Richard Smithddc83f92011-02-21 23:18:00 +00001849 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
1850 Error = 8;
1851
Richard Smith8110f042011-02-22 01:22:29 +00001852 // In Objective-C it is an error to use 'auto' on a function declarator.
1853 if (D.isFunctionDeclarator())
Richard Smith162e1c12011-04-15 14:24:37 +00001854 Error = 10;
Richard Smith8110f042011-02-22 01:22:29 +00001855
Richard Smithd37b3602012-02-10 11:05:11 +00001856 // C++11 [dcl.spec.auto]p2: 'auto' is always fine if the declarator
Richard Smithe7397c62011-02-22 00:36:53 +00001857 // contains a trailing return type. That is only legal at the outermost
1858 // level. Check all declarator chunks (outermost first) anyway, to give
1859 // better diagnostics.
David Blaikie4e4d0842012-03-11 07:00:24 +00001860 if (SemaRef.getLangOpts().CPlusPlus0x && Error != -1) {
Richard Smithe7397c62011-02-22 00:36:53 +00001861 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
1862 unsigned chunkIndex = e - i - 1;
1863 state.setCurrentChunkIndex(chunkIndex);
1864 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
1865 if (DeclType.Kind == DeclaratorChunk::Function) {
1866 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
1867 if (FTI.TrailingReturnType) {
1868 Error = -1;
1869 break;
1870 }
1871 }
1872 }
1873 }
1874
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001875 if (Error != -1) {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001876 SemaRef.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
1877 diag::err_auto_not_allowed)
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001878 << Error;
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001879 T = SemaRef.Context.IntTy;
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001880 D.setInvalidType(true);
Richard Smith0aa86c02011-10-15 05:42:01 +00001881 } else
1882 SemaRef.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
1883 diag::warn_cxx98_compat_auto_type_specifier);
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001884 }
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001885
David Blaikie4e4d0842012-03-11 07:00:24 +00001886 if (SemaRef.getLangOpts().CPlusPlus &&
John McCall5e1cdac2011-10-07 06:10:15 +00001887 OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001888 // Check the contexts where C++ forbids the declaration of a new class
1889 // or enumeration in a type-specifier-seq.
1890 switch (D.getContext()) {
Richard Smith7796eb52012-03-12 08:56:40 +00001891 case Declarator::TrailingReturnContext:
1892 // Class and enumeration definitions are syntactically not allowed in
1893 // trailing return types.
1894 llvm_unreachable("parser should not have allowed this");
1895 break;
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001896 case Declarator::FileContext:
1897 case Declarator::MemberContext:
1898 case Declarator::BlockContext:
1899 case Declarator::ForContext:
1900 case Declarator::BlockLiteralContext:
Eli Friedmanf88c4002012-01-04 04:41:38 +00001901 case Declarator::LambdaExprContext:
Richard Smithd37b3602012-02-10 11:05:11 +00001902 // C++11 [dcl.type]p3:
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001903 // A type-specifier-seq shall not define a class or enumeration unless
1904 // it appears in the type-id of an alias-declaration (7.1.3) that is not
1905 // the declaration of a template-declaration.
1906 case Declarator::AliasDeclContext:
1907 break;
1908 case Declarator::AliasTemplateContext:
1909 SemaRef.Diag(OwnedTagDecl->getLocation(),
1910 diag::err_type_defined_in_alias_template)
1911 << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
1912 break;
1913 case Declarator::TypeNameContext:
1914 case Declarator::TemplateParamContext:
1915 case Declarator::CXXNewContext:
1916 case Declarator::CXXCatchContext:
1917 case Declarator::ObjCCatchContext:
1918 case Declarator::TemplateTypeArgContext:
1919 SemaRef.Diag(OwnedTagDecl->getLocation(),
1920 diag::err_type_defined_in_type_specifier)
1921 << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
1922 break;
1923 case Declarator::PrototypeContext:
John McCallcdda47f2011-10-01 09:56:14 +00001924 case Declarator::ObjCParameterContext:
1925 case Declarator::ObjCResultContext:
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001926 case Declarator::KNRTypeListContext:
1927 // C++ [dcl.fct]p6:
1928 // Types shall not be defined in return or parameter types.
1929 SemaRef.Diag(OwnedTagDecl->getLocation(),
1930 diag::err_type_defined_in_param_type)
1931 << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
1932 break;
1933 case Declarator::ConditionContext:
1934 // C++ 6.4p2:
1935 // The type-specifier-seq shall not contain typedef and shall not declare
1936 // a new class or enumeration.
1937 SemaRef.Diag(OwnedTagDecl->getLocation(),
1938 diag::err_type_defined_in_condition);
1939 break;
1940 }
1941 }
1942
1943 return T;
1944}
1945
Benjamin Kramera08c2fb2012-02-24 22:19:42 +00001946static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){
Richard Smithd37b3602012-02-10 11:05:11 +00001947 std::string Quals =
1948 Qualifiers::fromCVRMask(FnTy->getTypeQuals()).getAsString();
1949
1950 switch (FnTy->getRefQualifier()) {
1951 case RQ_None:
1952 break;
1953
1954 case RQ_LValue:
1955 if (!Quals.empty())
1956 Quals += ' ';
1957 Quals += '&';
1958 break;
1959
1960 case RQ_RValue:
1961 if (!Quals.empty())
1962 Quals += ' ';
1963 Quals += "&&";
1964 break;
1965 }
1966
1967 return Quals;
1968}
1969
1970/// Check that the function type T, which has a cv-qualifier or a ref-qualifier,
1971/// can be contained within the declarator chunk DeclType, and produce an
1972/// appropriate diagnostic if not.
1973static void checkQualifiedFunction(Sema &S, QualType T,
1974 DeclaratorChunk &DeclType) {
1975 // C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6: a function type with a
1976 // cv-qualifier or a ref-qualifier can only appear at the topmost level
1977 // of a type.
1978 int DiagKind = -1;
1979 switch (DeclType.Kind) {
1980 case DeclaratorChunk::Paren:
1981 case DeclaratorChunk::MemberPointer:
1982 // These cases are permitted.
1983 return;
1984 case DeclaratorChunk::Array:
1985 case DeclaratorChunk::Function:
1986 // These cases don't allow function types at all; no need to diagnose the
1987 // qualifiers separately.
1988 return;
1989 case DeclaratorChunk::BlockPointer:
1990 DiagKind = 0;
1991 break;
1992 case DeclaratorChunk::Pointer:
1993 DiagKind = 1;
1994 break;
1995 case DeclaratorChunk::Reference:
1996 DiagKind = 2;
1997 break;
1998 }
1999
2000 assert(DiagKind != -1);
2001 S.Diag(DeclType.Loc, diag::err_compound_qualified_function_type)
2002 << DiagKind << isa<FunctionType>(T.IgnoreParens()) << T
2003 << getFunctionQualifiersAsString(T->castAs<FunctionProtoType>());
2004}
2005
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002006static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
2007 QualType declSpecType,
2008 TypeSourceInfo *TInfo) {
2009
2010 QualType T = declSpecType;
2011 Declarator &D = state.getDeclarator();
2012 Sema &S = state.getSema();
2013 ASTContext &Context = S.Context;
David Blaikie4e4d0842012-03-11 07:00:24 +00002014 const LangOptions &LangOpts = S.getLangOpts();
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002015
2016 bool ImplicitlyNoexcept = false;
2017 if (D.getName().getKind() == UnqualifiedId::IK_OperatorFunctionId &&
2018 LangOpts.CPlusPlus0x) {
2019 OverloadedOperatorKind OO = D.getName().OperatorFunctionId.Operator;
2020 /// In C++0x, deallocation functions (normal and array operator delete)
2021 /// are implicitly noexcept.
2022 if (OO == OO_Delete || OO == OO_Array_Delete)
2023 ImplicitlyNoexcept = true;
2024 }
Richard Smith34b41d92011-02-20 03:19:35 +00002025
Douglas Gregorcd281c32009-02-28 00:25:32 +00002026 // The name we're declaring, if any.
2027 DeclarationName Name;
2028 if (D.getIdentifier())
2029 Name = D.getIdentifier();
Mike Stump1eb44332009-09-09 15:08:12 +00002030
Richard Smith162e1c12011-04-15 14:24:37 +00002031 // Does this declaration declare a typedef-name?
2032 bool IsTypedefName =
2033 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef ||
Richard Smith3e4c6c42011-05-05 21:57:07 +00002034 D.getContext() == Declarator::AliasDeclContext ||
2035 D.getContext() == Declarator::AliasTemplateContext;
Richard Smith162e1c12011-04-15 14:24:37 +00002036
Richard Smithd37b3602012-02-10 11:05:11 +00002037 // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
2038 bool IsQualifiedFunction = T->isFunctionProtoType() &&
2039 (T->castAs<FunctionProtoType>()->getTypeQuals() != 0 ||
2040 T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None);
2041
Mike Stump98eb8a72009-02-04 22:31:32 +00002042 // Walk the DeclTypeInfo, building the recursive type as we go.
2043 // DeclTypeInfos are ordered from the identifier out, which is
2044 // opposite of what we want :).
Sebastian Redl8ce35b02009-10-25 21:45:37 +00002045 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
John McCall711c52b2011-01-05 12:14:39 +00002046 unsigned chunkIndex = e - i - 1;
2047 state.setCurrentChunkIndex(chunkIndex);
2048 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
Richard Smithd37b3602012-02-10 11:05:11 +00002049 if (IsQualifiedFunction) {
2050 checkQualifiedFunction(S, T, DeclType);
2051 IsQualifiedFunction = DeclType.Kind == DeclaratorChunk::Paren;
2052 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002053 switch (DeclType.Kind) {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002054 case DeclaratorChunk::Paren:
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002055 T = S.BuildParenType(T);
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002056 break;
Steve Naroff5618bd42008-08-27 16:04:49 +00002057 case DeclaratorChunk::BlockPointer:
Chris Lattner9af55002009-03-27 04:18:06 +00002058 // If blocks are disabled, emit an error.
2059 if (!LangOpts.Blocks)
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002060 S.Diag(DeclType.Loc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +00002061
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002062 T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name);
John McCall28654742010-06-05 06:41:15 +00002063 if (DeclType.Cls.TypeQuals)
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002064 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals);
Steve Naroff5618bd42008-08-27 16:04:49 +00002065 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002066 case DeclaratorChunk::Pointer:
Sebastian Redl6a7330c2009-05-29 15:01:05 +00002067 // Verify that we're not building a pointer to pointer to function with
2068 // exception specification.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002069 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
2070 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
Sebastian Redl6a7330c2009-05-29 15:01:05 +00002071 D.setInvalidType(true);
2072 // Build the type anyway.
2073 }
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002074 if (LangOpts.ObjC1 && T->getAs<ObjCObjectType>()) {
John McCallc12c5bb2010-05-15 11:32:37 +00002075 T = Context.getObjCObjectPointerType(T);
John McCall28654742010-06-05 06:41:15 +00002076 if (DeclType.Ptr.TypeQuals)
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002077 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
Steve Naroff14108da2009-07-10 23:34:53 +00002078 break;
2079 }
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002080 T = S.BuildPointerType(T, DeclType.Loc, Name);
John McCall28654742010-06-05 06:41:15 +00002081 if (DeclType.Ptr.TypeQuals)
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002082 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
John McCall711c52b2011-01-05 12:14:39 +00002083
Reid Spencer5f016e22007-07-11 17:01:13 +00002084 break;
John McCall0953e762009-09-24 19:53:00 +00002085 case DeclaratorChunk::Reference: {
Sebastian Redl6a7330c2009-05-29 15:01:05 +00002086 // Verify that we're not building a reference to pointer to function with
2087 // exception specification.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002088 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
2089 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
Sebastian Redl6a7330c2009-05-29 15:01:05 +00002090 D.setInvalidType(true);
2091 // Build the type anyway.
2092 }
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002093 T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name);
John McCall28654742010-06-05 06:41:15 +00002094
2095 Qualifiers Quals;
2096 if (DeclType.Ref.HasRestrict)
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002097 T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict);
Reid Spencer5f016e22007-07-11 17:01:13 +00002098 break;
John McCall0953e762009-09-24 19:53:00 +00002099 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002100 case DeclaratorChunk::Array: {
Sebastian Redl6a7330c2009-05-29 15:01:05 +00002101 // Verify that we're not building an array of pointers to function with
2102 // exception specification.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002103 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
2104 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
Sebastian Redl6a7330c2009-05-29 15:01:05 +00002105 D.setInvalidType(true);
2106 // Build the type anyway.
2107 }
Chris Lattnerfd89bc82008-04-02 01:05:10 +00002108 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
Chris Lattner94f81fd2007-08-28 16:54:00 +00002109 Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
Reid Spencer5f016e22007-07-11 17:01:13 +00002110 ArrayType::ArraySizeModifier ASM;
2111 if (ATI.isStar)
2112 ASM = ArrayType::Star;
2113 else if (ATI.hasStatic)
2114 ASM = ArrayType::Static;
2115 else
2116 ASM = ArrayType::Normal;
John McCallc05a94b2011-03-23 23:43:04 +00002117 if (ASM == ArrayType::Star && !D.isPrototypeContext()) {
Eli Friedmanf91f5c82009-04-26 21:57:51 +00002118 // FIXME: This check isn't quite right: it allows star in prototypes
2119 // for function definitions, and disallows some edge cases detailed
2120 // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002121 S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
Eli Friedmanf91f5c82009-04-26 21:57:51 +00002122 ASM = ArrayType::Normal;
2123 D.setInvalidType(true);
2124 }
Eli Friedman8ac2c662011-11-11 02:00:42 +00002125 T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals,
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002126 SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
Reid Spencer5f016e22007-07-11 17:01:13 +00002127 break;
2128 }
Sebastian Redlf30208a2009-01-24 21:16:55 +00002129 case DeclaratorChunk::Function: {
Reid Spencer5f016e22007-07-11 17:01:13 +00002130 // If the function declarator has a prototype (i.e. it is not () and
2131 // does not have a K&R-style identifier list), then the arguments are part
2132 // of the type, otherwise the argument list is ().
2133 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
Richard Smithd37b3602012-02-10 11:05:11 +00002134 IsQualifiedFunction = FTI.TypeQuals || FTI.hasRefQualifier();
Sebastian Redl3cc97262009-05-31 11:47:27 +00002135
Richard Smithe7397c62011-02-22 00:36:53 +00002136 // Check for auto functions and trailing return type and adjust the
2137 // return type accordingly.
2138 if (!D.isInvalidType()) {
2139 // trailing-return-type is only required if we're declaring a function,
2140 // and not, for instance, a pointer to a function.
2141 if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto &&
2142 !FTI.TrailingReturnType && chunkIndex == 0) {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002143 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
Richard Smithe7397c62011-02-22 00:36:53 +00002144 diag::err_auto_missing_trailing_return);
2145 T = Context.IntTy;
2146 D.setInvalidType(true);
2147 } else if (FTI.TrailingReturnType) {
2148 // T must be exactly 'auto' at this point. See CWG issue 681.
2149 if (isa<ParenType>(T)) {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002150 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
Richard Smithe7397c62011-02-22 00:36:53 +00002151 diag::err_trailing_return_in_parens)
2152 << T << D.getDeclSpec().getSourceRange();
2153 D.setInvalidType(true);
Eli Friedmanf88c4002012-01-04 04:41:38 +00002154 } else if (D.getContext() != Declarator::LambdaExprContext &&
2155 (T.hasQualifiers() || !isa<AutoType>(T))) {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002156 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
Richard Smithe7397c62011-02-22 00:36:53 +00002157 diag::err_trailing_return_without_auto)
2158 << T << D.getDeclSpec().getSourceRange();
2159 D.setInvalidType(true);
2160 }
2161
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002162 T = S.GetTypeFromParser(
Richard Smithe7397c62011-02-22 00:36:53 +00002163 ParsedType::getFromOpaquePtr(FTI.TrailingReturnType),
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002164 &TInfo);
Richard Smithe7397c62011-02-22 00:36:53 +00002165 }
2166 }
2167
Chris Lattnercd881292007-12-19 05:31:29 +00002168 // C99 6.7.5.3p1: The return type may not be a function or array type.
Douglas Gregor58408bc2010-01-11 18:46:21 +00002169 // For conversion functions, we'll diagnose this particular error later.
Douglas Gregor48026d22010-01-11 18:40:55 +00002170 if ((T->isArrayType() || T->isFunctionType()) &&
2171 (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId)) {
Argyrios Kyrtzidis98650442011-01-25 23:16:33 +00002172 unsigned diagID = diag::err_func_returning_array_function;
Argyrios Kyrtzidisa4356ad2011-01-26 01:26:44 +00002173 // Last processing chunk in block context means this function chunk
2174 // represents the block.
2175 if (chunkIndex == 0 &&
2176 D.getContext() == Declarator::BlockLiteralContext)
Argyrios Kyrtzidis98650442011-01-25 23:16:33 +00002177 diagID = diag::err_block_returning_array_function;
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002178 S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T;
Chris Lattnercd881292007-12-19 05:31:29 +00002179 T = Context.IntTy;
2180 D.setInvalidType(true);
2181 }
Sebastian Redl465226e2009-05-27 22:11:52 +00002182
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00002183 // Do not allow returning half FP value.
2184 // FIXME: This really should be in BuildFunctionType.
2185 if (T->isHalfType()) {
2186 S.Diag(D.getIdentifierLoc(),
2187 diag::err_parameters_retval_cannot_have_fp16_type) << 1
2188 << FixItHint::CreateInsertion(D.getIdentifierLoc(), "*");
2189 D.setInvalidType(true);
2190 }
2191
Douglas Gregor5291c3c2010-07-13 08:18:22 +00002192 // cv-qualifiers on return types are pointless except when the type is a
2193 // class type in C++.
Douglas Gregorfff95132011-03-01 17:04:42 +00002194 if (isa<PointerType>(T) && T.getLocalCVRQualifiers() &&
Rafael Espindola1e153942011-03-11 04:56:58 +00002195 (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId) &&
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002196 (!LangOpts.CPlusPlus || !T->isDependentType())) {
Chandler Carruthd067c072011-02-23 18:51:59 +00002197 assert(chunkIndex + 1 < e && "No DeclaratorChunk for the return type?");
2198 DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1);
2199 assert(ReturnTypeChunk.Kind == DeclaratorChunk::Pointer);
2200
2201 DeclaratorChunk::PointerTypeInfo &PTI = ReturnTypeChunk.Ptr;
2202
2203 DiagnoseIgnoredQualifiers(PTI.TypeQuals,
2204 SourceLocation::getFromRawEncoding(PTI.ConstQualLoc),
2205 SourceLocation::getFromRawEncoding(PTI.VolatileQualLoc),
2206 SourceLocation::getFromRawEncoding(PTI.RestrictQualLoc),
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002207 S);
Chandler Carruthd067c072011-02-23 18:51:59 +00002208
2209 } else if (T.getCVRQualifiers() && D.getDeclSpec().getTypeQualifiers() &&
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002210 (!LangOpts.CPlusPlus ||
Douglas Gregor5291c3c2010-07-13 08:18:22 +00002211 (!T->isDependentType() && !T->isRecordType()))) {
Chandler Carruthd067c072011-02-23 18:51:59 +00002212
2213 DiagnoseIgnoredQualifiers(D.getDeclSpec().getTypeQualifiers(),
2214 D.getDeclSpec().getConstSpecLoc(),
2215 D.getDeclSpec().getVolatileSpecLoc(),
2216 D.getDeclSpec().getRestrictSpecLoc(),
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002217 S);
Douglas Gregor5291c3c2010-07-13 08:18:22 +00002218 }
Chandler Carruthd067c072011-02-23 18:51:59 +00002219
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002220 if (LangOpts.CPlusPlus && D.getDeclSpec().isTypeSpecOwned()) {
Douglas Gregor402abb52009-05-28 23:31:59 +00002221 // C++ [dcl.fct]p6:
2222 // Types shall not be defined in return or parameter types.
John McCallb3d87482010-08-24 05:47:05 +00002223 TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
John McCall5e1cdac2011-10-07 06:10:15 +00002224 if (Tag->isCompleteDefinition())
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002225 S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
Douglas Gregor402abb52009-05-28 23:31:59 +00002226 << Context.getTypeDeclType(Tag);
2227 }
2228
Sebastian Redl3cc97262009-05-31 11:47:27 +00002229 // Exception specs are not allowed in typedefs. Complain, but add it
2230 // anyway.
Richard Smith162e1c12011-04-15 14:24:37 +00002231 if (IsTypedefName && FTI.getExceptionSpecType())
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002232 S.Diag(FTI.getExceptionSpecLoc(), diag::err_exception_spec_in_typedef)
Richard Smith3e4c6c42011-05-05 21:57:07 +00002233 << (D.getContext() == Declarator::AliasDeclContext ||
2234 D.getContext() == Declarator::AliasTemplateContext);
Sebastian Redl3cc97262009-05-31 11:47:27 +00002235
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002236 if (!FTI.NumArgs && !FTI.isVariadic && !LangOpts.CPlusPlus) {
John McCall28654742010-06-05 06:41:15 +00002237 // Simple void foo(), where the incoming T is the result type.
2238 T = Context.getFunctionNoProtoType(T);
2239 } else {
2240 // We allow a zero-parameter variadic function in C if the
2241 // function is marked with the "overloadable" attribute. Scan
2242 // for this attribute now.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002243 if (!FTI.NumArgs && FTI.isVariadic && !LangOpts.CPlusPlus) {
Douglas Gregor965acbb2009-02-18 07:07:28 +00002244 bool Overloadable = false;
2245 for (const AttributeList *Attrs = D.getAttributes();
2246 Attrs; Attrs = Attrs->getNext()) {
2247 if (Attrs->getKind() == AttributeList::AT_overloadable) {
2248 Overloadable = true;
2249 break;
2250 }
2251 }
2252
2253 if (!Overloadable)
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002254 S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_arg);
Argyrios Kyrtzidisc6f73452008-10-16 17:31:08 +00002255 }
John McCall28654742010-06-05 06:41:15 +00002256
2257 if (FTI.NumArgs && FTI.ArgInfo[0].Param == 0) {
Chris Lattner788b0fd2010-06-23 06:00:24 +00002258 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function
2259 // definition.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002260 S.Diag(FTI.ArgInfo[0].IdentLoc, diag::err_ident_list_in_fn_declaration);
John McCall28654742010-06-05 06:41:15 +00002261 D.setInvalidType(true);
2262 break;
2263 }
2264
John McCalle23cf432010-12-14 08:05:40 +00002265 FunctionProtoType::ExtProtoInfo EPI;
2266 EPI.Variadic = FTI.isVariadic;
Richard Smitheefb3d52012-02-10 09:58:53 +00002267 EPI.HasTrailingReturn = FTI.TrailingReturnType;
John McCalle23cf432010-12-14 08:05:40 +00002268 EPI.TypeQuals = FTI.TypeQuals;
Douglas Gregorc938c162011-01-26 05:01:58 +00002269 EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None
2270 : FTI.RefQualifierIsLValueRef? RQ_LValue
2271 : RQ_RValue;
2272
Reid Spencer5f016e22007-07-11 17:01:13 +00002273 // Otherwise, we have a function with an argument list that is
2274 // potentially variadic.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002275 SmallVector<QualType, 16> ArgTys;
John McCall28654742010-06-05 06:41:15 +00002276 ArgTys.reserve(FTI.NumArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002277
Chris Lattner5f9e2722011-07-23 10:55:15 +00002278 SmallVector<bool, 16> ConsumedArguments;
John McCallf85e1932011-06-15 23:02:42 +00002279 ConsumedArguments.reserve(FTI.NumArgs);
2280 bool HasAnyConsumedArguments = false;
2281
Reid Spencer5f016e22007-07-11 17:01:13 +00002282 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
John McCalld226f652010-08-21 09:40:31 +00002283 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
Chris Lattner8123a952008-04-10 02:22:51 +00002284 QualType ArgTy = Param->getType();
Chris Lattner78c75fb2007-07-21 05:30:18 +00002285 assert(!ArgTy.isNull() && "Couldn't parse type?");
Douglas Gregor2dc0e642009-03-23 23:06:20 +00002286
2287 // Adjust the parameter type.
Douglas Gregor79e6bd32011-07-12 04:42:08 +00002288 assert((ArgTy == Context.getAdjustedParameterType(ArgTy)) &&
2289 "Unadjusted type?");
Douglas Gregor2dc0e642009-03-23 23:06:20 +00002290
Reid Spencer5f016e22007-07-11 17:01:13 +00002291 // Look for 'void'. void is allowed only as a single argument to a
2292 // function with no other parameters (C99 6.7.5.3p10). We record
Douglas Gregor72564e72009-02-26 23:50:07 +00002293 // int(void) as a FunctionProtoType with an empty argument list.
Douglas Gregor2dc0e642009-03-23 23:06:20 +00002294 if (ArgTy->isVoidType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002295 // If this is something like 'float(int, void)', reject it. 'void'
2296 // is an incomplete type (C99 6.2.5p19) and function decls cannot
2297 // have arguments of incomplete type.
2298 if (FTI.NumArgs != 1 || FTI.isVariadic) {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002299 S.Diag(DeclType.Loc, diag::err_void_only_param);
Chris Lattner2ff54262007-07-21 05:18:12 +00002300 ArgTy = Context.IntTy;
Chris Lattner8123a952008-04-10 02:22:51 +00002301 Param->setType(ArgTy);
Chris Lattner2ff54262007-07-21 05:18:12 +00002302 } else if (FTI.ArgInfo[i].Ident) {
2303 // Reject, but continue to parse 'int(void abc)'.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002304 S.Diag(FTI.ArgInfo[i].IdentLoc,
Chris Lattner4565d4e2007-07-21 05:26:43 +00002305 diag::err_param_with_void_type);
Chris Lattner2ff54262007-07-21 05:18:12 +00002306 ArgTy = Context.IntTy;
Chris Lattner8123a952008-04-10 02:22:51 +00002307 Param->setType(ArgTy);
Chris Lattner2ff54262007-07-21 05:18:12 +00002308 } else {
2309 // Reject, but continue to parse 'float(const void)'.
John McCall0953e762009-09-24 19:53:00 +00002310 if (ArgTy.hasQualifiers())
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002311 S.Diag(DeclType.Loc, diag::err_void_param_qualified);
Mike Stump1eb44332009-09-09 15:08:12 +00002312
Chris Lattner2ff54262007-07-21 05:18:12 +00002313 // Do not add 'void' to the ArgTys list.
2314 break;
2315 }
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00002316 } else if (ArgTy->isHalfType()) {
2317 // Disallow half FP arguments.
2318 // FIXME: This really should be in BuildFunctionType.
2319 S.Diag(Param->getLocation(),
2320 diag::err_parameters_retval_cannot_have_fp16_type) << 0
2321 << FixItHint::CreateInsertion(Param->getLocation(), "*");
2322 D.setInvalidType();
Eli Friedmaneb4b7052008-08-25 21:31:01 +00002323 } else if (!FTI.hasPrototype) {
2324 if (ArgTy->isPromotableIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00002325 ArgTy = Context.getPromotedIntegerType(ArgTy);
John McCalleecf5fa2011-03-09 04:22:44 +00002326 Param->setKNRPromoted(true);
John McCall183700f2009-09-21 23:43:11 +00002327 } else if (const BuiltinType* BTy = ArgTy->getAs<BuiltinType>()) {
John McCalleecf5fa2011-03-09 04:22:44 +00002328 if (BTy->getKind() == BuiltinType::Float) {
Eli Friedmaneb4b7052008-08-25 21:31:01 +00002329 ArgTy = Context.DoubleTy;
John McCalleecf5fa2011-03-09 04:22:44 +00002330 Param->setKNRPromoted(true);
2331 }
Eli Friedmaneb4b7052008-08-25 21:31:01 +00002332 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002333 }
Fariborz Jahanian56a965c2010-09-08 21:36:35 +00002334
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002335 if (LangOpts.ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00002336 bool Consumed = Param->hasAttr<NSConsumedAttr>();
2337 ConsumedArguments.push_back(Consumed);
2338 HasAnyConsumedArguments |= Consumed;
2339 }
2340
John McCall54e14c42009-10-22 22:37:11 +00002341 ArgTys.push_back(ArgTy);
Reid Spencer5f016e22007-07-11 17:01:13 +00002342 }
Sebastian Redl465226e2009-05-27 22:11:52 +00002343
John McCallf85e1932011-06-15 23:02:42 +00002344 if (HasAnyConsumedArguments)
2345 EPI.ConsumedArguments = ConsumedArguments.data();
2346
Chris Lattner5f9e2722011-07-23 10:55:15 +00002347 SmallVector<QualType, 4> Exceptions;
Sebastian Redl8b5b4092011-03-06 10:52:04 +00002348 EPI.ExceptionSpecType = FTI.getExceptionSpecType();
2349 if (FTI.getExceptionSpecType() == EST_Dynamic) {
John McCalle23cf432010-12-14 08:05:40 +00002350 Exceptions.reserve(FTI.NumExceptions);
2351 for (unsigned ei = 0, ee = FTI.NumExceptions; ei != ee; ++ei) {
2352 // FIXME: Preserve type source info.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002353 QualType ET = S.GetTypeFromParser(FTI.Exceptions[ei].Ty);
John McCalle23cf432010-12-14 08:05:40 +00002354 // Check that the type is valid for an exception spec, and
2355 // drop it if not.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002356 if (!S.CheckSpecifiedExceptionType(ET, FTI.Exceptions[ei].Range))
John McCalle23cf432010-12-14 08:05:40 +00002357 Exceptions.push_back(ET);
2358 }
John McCall373920b2010-12-14 16:45:57 +00002359 EPI.NumExceptions = Exceptions.size();
John McCalle23cf432010-12-14 08:05:40 +00002360 EPI.Exceptions = Exceptions.data();
Sebastian Redl8b5b4092011-03-06 10:52:04 +00002361 } else if (FTI.getExceptionSpecType() == EST_ComputedNoexcept) {
Sebastian Redl60618fa2011-03-12 11:50:43 +00002362 // If an error occurred, there's no expression here.
2363 if (Expr *NoexceptExpr = FTI.NoexceptExpr) {
2364 assert((NoexceptExpr->isTypeDependent() ||
2365 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
2366 Context.BoolTy) &&
2367 "Parser should have made sure that the expression is boolean");
Richard Smith282e7e62012-02-04 09:53:13 +00002368 if (!NoexceptExpr->isValueDependent())
2369 NoexceptExpr = S.VerifyIntegerConstantExpression(NoexceptExpr, 0,
2370 S.PDiag(diag::err_noexcept_needs_constant_expression),
2371 /*AllowFold*/ false).take();
2372 EPI.NoexceptExpr = NoexceptExpr;
Sebastian Redl60618fa2011-03-12 11:50:43 +00002373 }
Sebastian Redl8999fe12011-03-14 18:08:30 +00002374 } else if (FTI.getExceptionSpecType() == EST_None &&
2375 ImplicitlyNoexcept && chunkIndex == 0) {
2376 // Only the outermost chunk is marked noexcept, of course.
2377 EPI.ExceptionSpecType = EST_BasicNoexcept;
Sebastian Redlef65f062009-05-29 18:02:33 +00002378 }
Sebastian Redl465226e2009-05-27 22:11:52 +00002379
John McCalle23cf432010-12-14 08:05:40 +00002380 T = Context.getFunctionType(T, ArgTys.data(), ArgTys.size(), EPI);
Reid Spencer5f016e22007-07-11 17:01:13 +00002381 }
John McCall04a67a62010-02-05 21:31:56 +00002382
Reid Spencer5f016e22007-07-11 17:01:13 +00002383 break;
2384 }
Sebastian Redlf30208a2009-01-24 21:16:55 +00002385 case DeclaratorChunk::MemberPointer:
2386 // The scope spec must refer to a class, or be dependent.
Abramo Bagnara7bd06762010-08-13 12:56:25 +00002387 CXXScopeSpec &SS = DeclType.Mem.Scope();
Sebastian Redlf30208a2009-01-24 21:16:55 +00002388 QualType ClsType;
Abramo Bagnara7bd06762010-08-13 12:56:25 +00002389 if (SS.isInvalid()) {
Jeffrey Yasskinedc28772010-04-07 23:29:58 +00002390 // Avoid emitting extra errors if we already errored on the scope.
2391 D.setInvalidType(true);
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002392 } else if (S.isDependentScopeSpecifier(SS) ||
2393 dyn_cast_or_null<CXXRecordDecl>(S.computeDeclContext(SS))) {
Mike Stump1eb44332009-09-09 15:08:12 +00002394 NestedNameSpecifier *NNS
Abramo Bagnara7bd06762010-08-13 12:56:25 +00002395 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
Douglas Gregor87c12c42009-11-04 16:49:01 +00002396 NestedNameSpecifier *NNSPrefix = NNS->getPrefix();
2397 switch (NNS->getKind()) {
2398 case NestedNameSpecifier::Identifier:
Abramo Bagnara7bd06762010-08-13 12:56:25 +00002399 ClsType = Context.getDependentNameType(ETK_None, NNSPrefix,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002400 NNS->getAsIdentifier());
Douglas Gregor87c12c42009-11-04 16:49:01 +00002401 break;
2402
2403 case NestedNameSpecifier::Namespace:
Douglas Gregor14aba762011-02-24 02:36:08 +00002404 case NestedNameSpecifier::NamespaceAlias:
Douglas Gregor87c12c42009-11-04 16:49:01 +00002405 case NestedNameSpecifier::Global:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002406 llvm_unreachable("Nested-name-specifier must name a type");
Abramo Bagnara7bd06762010-08-13 12:56:25 +00002407
Douglas Gregor87c12c42009-11-04 16:49:01 +00002408 case NestedNameSpecifier::TypeSpec:
2409 case NestedNameSpecifier::TypeSpecWithTemplate:
2410 ClsType = QualType(NNS->getAsType(), 0);
Abramo Bagnara91ce2c42011-03-10 10:18:27 +00002411 // Note: if the NNS has a prefix and ClsType is a nondependent
2412 // TemplateSpecializationType, then the NNS prefix is NOT included
2413 // in ClsType; hence we wrap ClsType into an ElaboratedType.
2414 // NOTE: in particular, no wrap occurs if ClsType already is an
2415 // Elaborated, DependentName, or DependentTemplateSpecialization.
2416 if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType()))
Abramo Bagnara7bd06762010-08-13 12:56:25 +00002417 ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType);
Douglas Gregor87c12c42009-11-04 16:49:01 +00002418 break;
2419 }
Sebastian Redlf30208a2009-01-24 21:16:55 +00002420 } else {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002421 S.Diag(DeclType.Mem.Scope().getBeginLoc(),
Douglas Gregor949bf692009-06-09 22:17:39 +00002422 diag::err_illegal_decl_mempointer_in_nonclass)
2423 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
2424 << DeclType.Mem.Scope().getRange();
Sebastian Redlf30208a2009-01-24 21:16:55 +00002425 D.setInvalidType(true);
Sebastian Redlf30208a2009-01-24 21:16:55 +00002426 }
2427
Douglas Gregor949bf692009-06-09 22:17:39 +00002428 if (!ClsType.isNull())
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002429 T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc, D.getIdentifier());
Douglas Gregor949bf692009-06-09 22:17:39 +00002430 if (T.isNull()) {
2431 T = Context.IntTy;
Sebastian Redlf30208a2009-01-24 21:16:55 +00002432 D.setInvalidType(true);
John McCall28654742010-06-05 06:41:15 +00002433 } else if (DeclType.Mem.TypeQuals) {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002434 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals);
Sebastian Redlf30208a2009-01-24 21:16:55 +00002435 }
Sebastian Redlf30208a2009-01-24 21:16:55 +00002436 break;
2437 }
2438
Douglas Gregorcd281c32009-02-28 00:25:32 +00002439 if (T.isNull()) {
2440 D.setInvalidType(true);
2441 T = Context.IntTy;
2442 }
2443
Chris Lattnerc9b346d2008-06-29 00:50:08 +00002444 // See if there are any attributes on this declarator chunk.
John McCall711c52b2011-01-05 12:14:39 +00002445 if (AttributeList *attrs = const_cast<AttributeList*>(DeclType.getAttrs()))
2446 processTypeAttrs(state, T, false, attrs);
Reid Spencer5f016e22007-07-11 17:01:13 +00002447 }
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00002448
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002449 if (LangOpts.CPlusPlus && T->isFunctionType()) {
John McCall183700f2009-09-21 23:43:11 +00002450 const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
Chris Lattner778ed742009-10-25 17:36:50 +00002451 assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00002452
Douglas Gregor708f3b82010-10-14 22:03:51 +00002453 // C++ 8.3.5p4:
2454 // A cv-qualifier-seq shall only be part of the function type
2455 // for a nonstatic member function, the function type to which a pointer
2456 // to member refers, or the top-level function type of a function typedef
2457 // declaration.
Douglas Gregor683a81f2011-01-31 16:09:46 +00002458 //
2459 // Core issue 547 also allows cv-qualifiers on function types that are
2460 // top-level template type arguments.
John McCall613ef3d2010-10-19 01:54:45 +00002461 bool FreeFunction;
2462 if (!D.getCXXScopeSpec().isSet()) {
Eli Friedman906a7e12012-01-06 03:05:34 +00002463 FreeFunction = ((D.getContext() != Declarator::MemberContext &&
2464 D.getContext() != Declarator::LambdaExprContext) ||
John McCall613ef3d2010-10-19 01:54:45 +00002465 D.getDeclSpec().isFriendSpecified());
2466 } else {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002467 DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec());
John McCall613ef3d2010-10-19 01:54:45 +00002468 FreeFunction = (DC && !DC->isRecord());
2469 }
2470
Richard Smith55dec862011-09-30 00:45:47 +00002471 // C++0x [dcl.constexpr]p8: A constexpr specifier for a non-static member
2472 // function that is not a constructor declares that function to be const.
2473 if (D.getDeclSpec().isConstexprSpecified() && !FreeFunction &&
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002474 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static &&
Richard Smith55dec862011-09-30 00:45:47 +00002475 D.getName().getKind() != UnqualifiedId::IK_ConstructorName &&
2476 D.getName().getKind() != UnqualifiedId::IK_ConstructorTemplateId &&
2477 !(FnTy->getTypeQuals() & DeclSpec::TQ_const)) {
2478 // Rebuild function type adding a 'const' qualifier.
2479 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
2480 EPI.TypeQuals |= DeclSpec::TQ_const;
2481 T = Context.getFunctionType(FnTy->getResultType(),
2482 FnTy->arg_type_begin(),
2483 FnTy->getNumArgs(), EPI);
2484 }
2485
Richard Smithd37b3602012-02-10 11:05:11 +00002486 // C++11 [dcl.fct]p6 (w/DR1417):
2487 // An attempt to specify a function type with a cv-qualifier-seq or a
2488 // ref-qualifier (including by typedef-name) is ill-formed unless it is:
2489 // - the function type for a non-static member function,
2490 // - the function type to which a pointer to member refers,
2491 // - the top-level function type of a function typedef declaration or
2492 // alias-declaration,
2493 // - the type-id in the default argument of a type-parameter, or
2494 // - the type-id of a template-argument for a type-parameter
2495 if (IsQualifiedFunction &&
2496 !(!FreeFunction &&
2497 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) &&
2498 !IsTypedefName &&
2499 D.getContext() != Declarator::TemplateTypeArgContext) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00002500 SourceLocation Loc = D.getLocStart();
Richard Smithd37b3602012-02-10 11:05:11 +00002501 SourceRange RemovalRange;
2502 unsigned I;
2503 if (D.isFunctionDeclarator(I)) {
2504 SmallVector<SourceLocation, 4> RemovalLocs;
2505 const DeclaratorChunk &Chunk = D.getTypeObject(I);
2506 assert(Chunk.Kind == DeclaratorChunk::Function);
2507 if (Chunk.Fun.hasRefQualifier())
2508 RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc());
2509 if (Chunk.Fun.TypeQuals & Qualifiers::Const)
2510 RemovalLocs.push_back(Chunk.Fun.getConstQualifierLoc());
2511 if (Chunk.Fun.TypeQuals & Qualifiers::Volatile)
2512 RemovalLocs.push_back(Chunk.Fun.getVolatileQualifierLoc());
2513 // FIXME: We do not track the location of the __restrict qualifier.
2514 //if (Chunk.Fun.TypeQuals & Qualifiers::Restrict)
2515 // RemovalLocs.push_back(Chunk.Fun.getRestrictQualifierLoc());
2516 if (!RemovalLocs.empty()) {
2517 std::sort(RemovalLocs.begin(), RemovalLocs.end(),
2518 SourceManager::LocBeforeThanCompare(S.getSourceManager()));
2519 RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back());
2520 Loc = RemovalLocs.front();
Douglas Gregorc938c162011-01-26 05:01:58 +00002521 }
2522 }
Richard Smithd37b3602012-02-10 11:05:11 +00002523
2524 S.Diag(Loc, diag::err_invalid_qualified_function_type)
2525 << FreeFunction << D.isFunctionDeclarator() << T
2526 << getFunctionQualifiersAsString(FnTy)
2527 << FixItHint::CreateRemoval(RemovalRange);
2528
2529 // Strip the cv-qualifiers and ref-qualifiers from the type.
2530 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
2531 EPI.TypeQuals = 0;
2532 EPI.RefQualifier = RQ_None;
2533
2534 T = Context.getFunctionType(FnTy->getResultType(),
2535 FnTy->arg_type_begin(),
2536 FnTy->getNumArgs(), EPI);
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00002537 }
2538 }
Mike Stump1eb44332009-09-09 15:08:12 +00002539
John McCall711c52b2011-01-05 12:14:39 +00002540 // Apply any undistributed attributes from the declarator.
2541 if (!T.isNull())
2542 if (AttributeList *attrs = D.getAttributes())
2543 processTypeAttrs(state, T, false, attrs);
2544
2545 // Diagnose any ignored type attributes.
2546 if (!T.isNull()) state.diagnoseIgnoredTypeAttrs(T);
2547
Peter Collingbourne148f1f72011-03-20 08:06:45 +00002548 // C++0x [dcl.constexpr]p9:
2549 // A constexpr specifier used in an object declaration declares the object
2550 // as const.
2551 if (D.getDeclSpec().isConstexprSpecified() && T->isObjectType()) {
Sebastian Redl73780122010-06-09 21:19:43 +00002552 T.addConst();
2553 }
2554
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002555 // If there was an ellipsis in the declarator, the declaration declares a
2556 // parameter pack whose type may be a pack expansion type.
2557 if (D.hasEllipsis() && !T.isNull()) {
2558 // C++0x [dcl.fct]p13:
2559 // A declarator-id or abstract-declarator containing an ellipsis shall
2560 // only be used in a parameter-declaration. Such a parameter-declaration
2561 // is a parameter pack (14.5.3). [...]
2562 switch (D.getContext()) {
2563 case Declarator::PrototypeContext:
2564 // C++0x [dcl.fct]p13:
2565 // [...] When it is part of a parameter-declaration-clause, the
2566 // parameter pack is a function parameter pack (14.5.3). The type T
2567 // of the declarator-id of the function parameter pack shall contain
2568 // a template parameter pack; each template parameter pack in T is
2569 // expanded by the function parameter pack.
2570 //
2571 // We represent function parameter packs as function parameters whose
2572 // type is a pack expansion.
2573 if (!T->containsUnexpandedParameterPack()) {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002574 S.Diag(D.getEllipsisLoc(),
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002575 diag::err_function_parameter_pack_without_parameter_packs)
2576 << T << D.getSourceRange();
2577 D.setEllipsisLoc(SourceLocation());
2578 } else {
Douglas Gregorcded4f62011-01-14 17:04:44 +00002579 T = Context.getPackExpansionType(T, llvm::Optional<unsigned>());
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002580 }
2581 break;
2582
2583 case Declarator::TemplateParamContext:
2584 // C++0x [temp.param]p15:
2585 // If a template-parameter is a [...] is a parameter-declaration that
2586 // declares a parameter pack (8.3.5), then the template-parameter is a
2587 // template parameter pack (14.5.3).
2588 //
2589 // Note: core issue 778 clarifies that, if there are any unexpanded
2590 // parameter packs in the type of the non-type template parameter, then
2591 // it expands those parameter packs.
2592 if (T->containsUnexpandedParameterPack())
Douglas Gregorcded4f62011-01-14 17:04:44 +00002593 T = Context.getPackExpansionType(T, llvm::Optional<unsigned>());
Richard Smithe5acd132011-10-14 20:31:37 +00002594 else
2595 S.Diag(D.getEllipsisLoc(),
2596 LangOpts.CPlusPlus0x
2597 ? diag::warn_cxx98_compat_variadic_templates
2598 : diag::ext_variadic_templates);
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002599 break;
2600
2601 case Declarator::FileContext:
2602 case Declarator::KNRTypeListContext:
John McCallcdda47f2011-10-01 09:56:14 +00002603 case Declarator::ObjCParameterContext: // FIXME: special diagnostic here?
2604 case Declarator::ObjCResultContext: // FIXME: special diagnostic here?
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002605 case Declarator::TypeNameContext:
Argyrios Kyrtzidis0b8c98f2011-06-28 03:01:23 +00002606 case Declarator::CXXNewContext:
Richard Smith162e1c12011-04-15 14:24:37 +00002607 case Declarator::AliasDeclContext:
Richard Smith3e4c6c42011-05-05 21:57:07 +00002608 case Declarator::AliasTemplateContext:
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002609 case Declarator::MemberContext:
2610 case Declarator::BlockContext:
2611 case Declarator::ForContext:
2612 case Declarator::ConditionContext:
2613 case Declarator::CXXCatchContext:
Argyrios Kyrtzidis17b63992011-07-01 22:22:40 +00002614 case Declarator::ObjCCatchContext:
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002615 case Declarator::BlockLiteralContext:
Eli Friedmanf88c4002012-01-04 04:41:38 +00002616 case Declarator::LambdaExprContext:
Richard Smith7796eb52012-03-12 08:56:40 +00002617 case Declarator::TrailingReturnContext:
Douglas Gregor683a81f2011-01-31 16:09:46 +00002618 case Declarator::TemplateTypeArgContext:
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002619 // FIXME: We may want to allow parameter packs in block-literal contexts
2620 // in the future.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002621 S.Diag(D.getEllipsisLoc(), diag::err_ellipsis_in_declarator_not_parameter);
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002622 D.setEllipsisLoc(SourceLocation());
2623 break;
2624 }
2625 }
Richard Smithe7397c62011-02-22 00:36:53 +00002626
John McCallbf1a0282010-06-04 23:28:52 +00002627 if (T.isNull())
2628 return Context.getNullTypeSourceInfo();
2629 else if (D.isInvalidType())
2630 return Context.getTrivialTypeSourceInfo(T);
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +00002631
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002632 return S.GetTypeSourceInfoForDeclarator(D, T, TInfo);
2633}
2634
2635/// GetTypeForDeclarator - Convert the type for the specified
2636/// declarator to Type instances.
2637///
2638/// The result of this call will never be null, but the associated
2639/// type may be a null type if there's an unrecoverable error.
2640TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) {
2641 // Determine the type of the declarator. Not all forms of declarator
2642 // have a type.
2643
2644 TypeProcessingState state(*this, D);
2645
2646 TypeSourceInfo *ReturnTypeInfo = 0;
2647 QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
2648 if (T.isNull())
2649 return Context.getNullTypeSourceInfo();
2650
David Blaikie4e4d0842012-03-11 07:00:24 +00002651 if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount)
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002652 inferARCWriteback(state, T);
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +00002653
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002654 return GetFullTypeForDeclarator(state, T, ReturnTypeInfo);
Reid Spencer5f016e22007-07-11 17:01:13 +00002655}
2656
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00002657static void transferARCOwnershipToDeclSpec(Sema &S,
2658 QualType &declSpecTy,
2659 Qualifiers::ObjCLifetime ownership) {
2660 if (declSpecTy->isObjCRetainableType() &&
2661 declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) {
2662 Qualifiers qs;
2663 qs.addObjCLifetime(ownership);
2664 declSpecTy = S.Context.getQualifiedType(declSpecTy, qs);
2665 }
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00002666}
2667
2668static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
2669 Qualifiers::ObjCLifetime ownership,
2670 unsigned chunkIndex) {
2671 Sema &S = state.getSema();
2672 Declarator &D = state.getDeclarator();
2673
2674 // Look for an explicit lifetime attribute.
2675 DeclaratorChunk &chunk = D.getTypeObject(chunkIndex);
2676 for (const AttributeList *attr = chunk.getAttrs(); attr;
2677 attr = attr->getNext())
2678 if (attr->getKind() == AttributeList::AT_objc_ownership)
2679 return;
2680
2681 const char *attrStr = 0;
2682 switch (ownership) {
David Blaikie30263482012-01-20 21:50:17 +00002683 case Qualifiers::OCL_None: llvm_unreachable("no ownership!");
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00002684 case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break;
2685 case Qualifiers::OCL_Strong: attrStr = "strong"; break;
2686 case Qualifiers::OCL_Weak: attrStr = "weak"; break;
2687 case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break;
2688 }
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00002689
2690 // If there wasn't one, add one (with an invalid source location
2691 // so that we don't make an AttributedType for it).
2692 AttributeList *attr = D.getAttributePool()
2693 .create(&S.Context.Idents.get("objc_ownership"), SourceLocation(),
2694 /*scope*/ 0, SourceLocation(),
2695 &S.Context.Idents.get(attrStr), SourceLocation(),
2696 /*args*/ 0, 0,
2697 /*declspec*/ false, /*C++0x*/ false);
2698 spliceAttrIntoList(*attr, chunk.getAttrListRef());
2699
2700 // TODO: mark whether we did this inference?
2701}
2702
Argyrios Kyrtzidis6ee54922011-10-28 22:54:28 +00002703/// \brief Used for transfering ownership in casts resulting in l-values.
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00002704static void transferARCOwnership(TypeProcessingState &state,
2705 QualType &declSpecTy,
2706 Qualifiers::ObjCLifetime ownership) {
2707 Sema &S = state.getSema();
2708 Declarator &D = state.getDeclarator();
2709
2710 int inner = -1;
Argyrios Kyrtzidis6ee54922011-10-28 22:54:28 +00002711 bool hasIndirection = false;
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00002712 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
2713 DeclaratorChunk &chunk = D.getTypeObject(i);
2714 switch (chunk.Kind) {
2715 case DeclaratorChunk::Paren:
2716 // Ignore parens.
2717 break;
2718
2719 case DeclaratorChunk::Array:
2720 case DeclaratorChunk::Reference:
2721 case DeclaratorChunk::Pointer:
Argyrios Kyrtzidis6ee54922011-10-28 22:54:28 +00002722 if (inner != -1)
2723 hasIndirection = true;
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00002724 inner = i;
2725 break;
2726
2727 case DeclaratorChunk::BlockPointer:
Argyrios Kyrtzidis6ee54922011-10-28 22:54:28 +00002728 if (inner != -1)
2729 transferARCOwnershipToDeclaratorChunk(state, ownership, i);
2730 return;
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00002731
2732 case DeclaratorChunk::Function:
2733 case DeclaratorChunk::MemberPointer:
2734 return;
2735 }
2736 }
2737
2738 if (inner == -1)
Argyrios Kyrtzidis6ee54922011-10-28 22:54:28 +00002739 return;
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00002740
2741 DeclaratorChunk &chunk = D.getTypeObject(inner);
2742 if (chunk.Kind == DeclaratorChunk::Pointer) {
2743 if (declSpecTy->isObjCRetainableType())
2744 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
Argyrios Kyrtzidis6ee54922011-10-28 22:54:28 +00002745 if (declSpecTy->isObjCObjectType() && hasIndirection)
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00002746 return transferARCOwnershipToDeclaratorChunk(state, ownership, inner);
2747 } else {
2748 assert(chunk.Kind == DeclaratorChunk::Array ||
2749 chunk.Kind == DeclaratorChunk::Reference);
2750 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
2751 }
2752}
2753
2754TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) {
2755 TypeProcessingState state(*this, D);
2756
2757 TypeSourceInfo *ReturnTypeInfo = 0;
2758 QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
2759 if (declSpecTy.isNull())
2760 return Context.getNullTypeSourceInfo();
2761
David Blaikie4e4d0842012-03-11 07:00:24 +00002762 if (getLangOpts().ObjCAutoRefCount) {
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00002763 Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy);
2764 if (ownership != Qualifiers::OCL_None)
2765 transferARCOwnership(state, declSpecTy, ownership);
2766 }
2767
2768 return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo);
2769}
2770
John McCall14aa2172011-03-04 04:00:19 +00002771/// Map an AttributedType::Kind to an AttributeList::Kind.
2772static AttributeList::Kind getAttrListKind(AttributedType::Kind kind) {
2773 switch (kind) {
2774 case AttributedType::attr_address_space:
2775 return AttributeList::AT_address_space;
2776 case AttributedType::attr_regparm:
2777 return AttributeList::AT_regparm;
2778 case AttributedType::attr_vector_size:
2779 return AttributeList::AT_vector_size;
2780 case AttributedType::attr_neon_vector_type:
2781 return AttributeList::AT_neon_vector_type;
2782 case AttributedType::attr_neon_polyvector_type:
2783 return AttributeList::AT_neon_polyvector_type;
2784 case AttributedType::attr_objc_gc:
2785 return AttributeList::AT_objc_gc;
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00002786 case AttributedType::attr_objc_ownership:
2787 return AttributeList::AT_objc_ownership;
John McCall14aa2172011-03-04 04:00:19 +00002788 case AttributedType::attr_noreturn:
2789 return AttributeList::AT_noreturn;
2790 case AttributedType::attr_cdecl:
2791 return AttributeList::AT_cdecl;
2792 case AttributedType::attr_fastcall:
2793 return AttributeList::AT_fastcall;
2794 case AttributedType::attr_stdcall:
2795 return AttributeList::AT_stdcall;
2796 case AttributedType::attr_thiscall:
2797 return AttributeList::AT_thiscall;
2798 case AttributedType::attr_pascal:
2799 return AttributeList::AT_pascal;
Anton Korobeynikov414d8962011-04-14 20:06:49 +00002800 case AttributedType::attr_pcs:
2801 return AttributeList::AT_pcs;
John McCall14aa2172011-03-04 04:00:19 +00002802 }
2803 llvm_unreachable("unexpected attribute kind!");
John McCall14aa2172011-03-04 04:00:19 +00002804}
2805
2806static void fillAttributedTypeLoc(AttributedTypeLoc TL,
2807 const AttributeList *attrs) {
2808 AttributedType::Kind kind = TL.getAttrKind();
2809
2810 assert(attrs && "no type attributes in the expected location!");
2811 AttributeList::Kind parsedKind = getAttrListKind(kind);
2812 while (attrs->getKind() != parsedKind) {
2813 attrs = attrs->getNext();
2814 assert(attrs && "no matching attribute in expected location!");
2815 }
2816
2817 TL.setAttrNameLoc(attrs->getLoc());
2818 if (TL.hasAttrExprOperand())
2819 TL.setAttrExprOperand(attrs->getArg(0));
2820 else if (TL.hasAttrEnumOperand())
2821 TL.setAttrEnumOperandLoc(attrs->getParameterLoc());
2822
2823 // FIXME: preserve this information to here.
2824 if (TL.hasAttrOperand())
2825 TL.setAttrOperandParensRange(SourceRange());
2826}
2827
John McCall51bd8032009-10-18 01:05:36 +00002828namespace {
2829 class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
Douglas Gregorc21c7e92011-01-25 19:13:18 +00002830 ASTContext &Context;
John McCall51bd8032009-10-18 01:05:36 +00002831 const DeclSpec &DS;
Argyrios Kyrtzidisf352bdd2009-09-29 19:43:35 +00002832
John McCall51bd8032009-10-18 01:05:36 +00002833 public:
Douglas Gregorc21c7e92011-01-25 19:13:18 +00002834 TypeSpecLocFiller(ASTContext &Context, const DeclSpec &DS)
2835 : Context(Context), DS(DS) {}
Argyrios Kyrtzidisf352bdd2009-09-29 19:43:35 +00002836
John McCall14aa2172011-03-04 04:00:19 +00002837 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
2838 fillAttributedTypeLoc(TL, DS.getAttributes().getList());
2839 Visit(TL.getModifiedLoc());
2840 }
John McCall51bd8032009-10-18 01:05:36 +00002841 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
2842 Visit(TL.getUnqualifiedLoc());
2843 }
2844 void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
2845 TL.setNameLoc(DS.getTypeSpecTypeLoc());
2846 }
2847 void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
2848 TL.setNameLoc(DS.getTypeSpecTypeLoc());
John McCallc12c5bb2010-05-15 11:32:37 +00002849 }
2850 void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
2851 // Handle the base type, which might not have been written explicitly.
2852 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
2853 TL.setHasBaseTypeAsWritten(false);
Douglas Gregorc21c7e92011-01-25 19:13:18 +00002854 TL.getBaseLoc().initialize(Context, SourceLocation());
John McCallc12c5bb2010-05-15 11:32:37 +00002855 } else {
2856 TL.setHasBaseTypeAsWritten(true);
2857 Visit(TL.getBaseLoc());
2858 }
Argyrios Kyrtzidiseb667592009-09-29 19:45:22 +00002859
John McCallc12c5bb2010-05-15 11:32:37 +00002860 // Protocol qualifiers.
John McCall54e14c42009-10-22 22:37:11 +00002861 if (DS.getProtocolQualifiers()) {
2862 assert(TL.getNumProtocols() > 0);
2863 assert(TL.getNumProtocols() == DS.getNumProtocolQualifiers());
2864 TL.setLAngleLoc(DS.getProtocolLAngleLoc());
2865 TL.setRAngleLoc(DS.getSourceRange().getEnd());
2866 for (unsigned i = 0, e = DS.getNumProtocolQualifiers(); i != e; ++i)
2867 TL.setProtocolLoc(i, DS.getProtocolLocs()[i]);
2868 } else {
2869 assert(TL.getNumProtocols() == 0);
2870 TL.setLAngleLoc(SourceLocation());
2871 TL.setRAngleLoc(SourceLocation());
2872 }
2873 }
2874 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCall54e14c42009-10-22 22:37:11 +00002875 TL.setStarLoc(SourceLocation());
John McCallc12c5bb2010-05-15 11:32:37 +00002876 Visit(TL.getPointeeLoc());
John McCall51bd8032009-10-18 01:05:36 +00002877 }
John McCall833ca992009-10-29 08:12:44 +00002878 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
John McCalla93c9342009-12-07 02:54:59 +00002879 TypeSourceInfo *TInfo = 0;
John McCallb3d87482010-08-24 05:47:05 +00002880 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
John McCall833ca992009-10-29 08:12:44 +00002881
2882 // If we got no declarator info from previous Sema routines,
2883 // just fill with the typespec loc.
John McCalla93c9342009-12-07 02:54:59 +00002884 if (!TInfo) {
Abramo Bagnara0daaf322011-03-16 20:16:18 +00002885 TL.initialize(Context, DS.getTypeSpecTypeNameLoc());
John McCall833ca992009-10-29 08:12:44 +00002886 return;
2887 }
2888
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00002889 TypeLoc OldTL = TInfo->getTypeLoc();
2890 if (TInfo->getType()->getAs<ElaboratedType>()) {
2891 ElaboratedTypeLoc ElabTL = cast<ElaboratedTypeLoc>(OldTL);
2892 TemplateSpecializationTypeLoc NamedTL =
2893 cast<TemplateSpecializationTypeLoc>(ElabTL.getNamedTypeLoc());
2894 TL.copy(NamedTL);
2895 }
2896 else
2897 TL.copy(cast<TemplateSpecializationTypeLoc>(OldTL));
John McCall833ca992009-10-29 08:12:44 +00002898 }
John McCallcfb708c2010-01-13 20:03:27 +00002899 void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
2900 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr);
2901 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
2902 TL.setParensRange(DS.getTypeofParensRange());
2903 }
2904 void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
2905 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType);
2906 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
2907 TL.setParensRange(DS.getTypeofParensRange());
John McCallb3d87482010-08-24 05:47:05 +00002908 assert(DS.getRepAsType());
John McCallcfb708c2010-01-13 20:03:27 +00002909 TypeSourceInfo *TInfo = 0;
John McCallb3d87482010-08-24 05:47:05 +00002910 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
John McCallcfb708c2010-01-13 20:03:27 +00002911 TL.setUnderlyingTInfo(TInfo);
2912 }
Sean Huntca63c202011-05-24 22:41:36 +00002913 void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
2914 // FIXME: This holds only because we only have one unary transform.
2915 assert(DS.getTypeSpecType() == DeclSpec::TST_underlyingType);
2916 TL.setKWLoc(DS.getTypeSpecTypeLoc());
2917 TL.setParensRange(DS.getTypeofParensRange());
2918 assert(DS.getRepAsType());
2919 TypeSourceInfo *TInfo = 0;
2920 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
2921 TL.setUnderlyingTInfo(TInfo);
2922 }
Douglas Gregorddf889a2010-01-18 18:04:31 +00002923 void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
2924 // By default, use the source location of the type specifier.
2925 TL.setBuiltinLoc(DS.getTypeSpecTypeLoc());
2926 if (TL.needsExtraLocalData()) {
2927 // Set info for the written builtin specifiers.
2928 TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs();
2929 // Try to have a meaningful source location.
2930 if (TL.getWrittenSignSpec() != TSS_unspecified)
2931 // Sign spec loc overrides the others (e.g., 'unsigned long').
2932 TL.setBuiltinLoc(DS.getTypeSpecSignLoc());
2933 else if (TL.getWrittenWidthSpec() != TSW_unspecified)
2934 // Width spec loc overrides type spec loc (e.g., 'short int').
2935 TL.setBuiltinLoc(DS.getTypeSpecWidthLoc());
2936 }
2937 }
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00002938 void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
2939 ElaboratedTypeKeyword Keyword
2940 = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
Nico Weber253e80b2010-11-22 10:30:56 +00002941 if (DS.getTypeSpecType() == TST_typename) {
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00002942 TypeSourceInfo *TInfo = 0;
John McCallb3d87482010-08-24 05:47:05 +00002943 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00002944 if (TInfo) {
2945 TL.copy(cast<ElaboratedTypeLoc>(TInfo->getTypeLoc()));
2946 return;
2947 }
2948 }
Abramo Bagnara38a42912012-02-06 19:09:27 +00002949 TL.setElaboratedKeywordLoc(Keyword != ETK_None
2950 ? DS.getTypeSpecTypeLoc()
2951 : SourceLocation());
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00002952 const CXXScopeSpec& SS = DS.getTypeSpecScope();
Douglas Gregor9e876872011-03-01 18:12:44 +00002953 TL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00002954 Visit(TL.getNextTypeLoc().getUnqualifiedLoc());
2955 }
2956 void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
Abramo Bagnara66581d42012-02-06 22:45:07 +00002957 assert(DS.getTypeSpecType() == TST_typename);
2958 TypeSourceInfo *TInfo = 0;
2959 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
2960 assert(TInfo);
2961 TL.copy(cast<DependentNameTypeLoc>(TInfo->getTypeLoc()));
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00002962 }
John McCall33500952010-06-11 00:33:02 +00002963 void VisitDependentTemplateSpecializationTypeLoc(
2964 DependentTemplateSpecializationTypeLoc TL) {
Abramo Bagnara66581d42012-02-06 22:45:07 +00002965 assert(DS.getTypeSpecType() == TST_typename);
2966 TypeSourceInfo *TInfo = 0;
2967 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
2968 assert(TInfo);
2969 TL.copy(cast<DependentTemplateSpecializationTypeLoc>(
2970 TInfo->getTypeLoc()));
Abramo Bagnara0daaf322011-03-16 20:16:18 +00002971 }
2972 void VisitTagTypeLoc(TagTypeLoc TL) {
2973 TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
John McCall33500952010-06-11 00:33:02 +00002974 }
Eli Friedmanb001de72011-10-06 23:00:33 +00002975 void VisitAtomicTypeLoc(AtomicTypeLoc TL) {
2976 TL.setKWLoc(DS.getTypeSpecTypeLoc());
2977 TL.setParensRange(DS.getTypeofParensRange());
Douglas Gregor43fe2452011-10-09 18:45:17 +00002978
2979 TypeSourceInfo *TInfo = 0;
2980 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
2981 TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
Eli Friedmanb001de72011-10-06 23:00:33 +00002982 }
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00002983
John McCall51bd8032009-10-18 01:05:36 +00002984 void VisitTypeLoc(TypeLoc TL) {
2985 // FIXME: add other typespec types and change this to an assert.
Douglas Gregorc21c7e92011-01-25 19:13:18 +00002986 TL.initialize(Context, DS.getTypeSpecTypeLoc());
John McCall51bd8032009-10-18 01:05:36 +00002987 }
2988 };
Argyrios Kyrtzidisf352bdd2009-09-29 19:43:35 +00002989
John McCall51bd8032009-10-18 01:05:36 +00002990 class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
Abramo Bagnarab6ab6c12011-03-05 14:42:21 +00002991 ASTContext &Context;
John McCall51bd8032009-10-18 01:05:36 +00002992 const DeclaratorChunk &Chunk;
2993
2994 public:
Abramo Bagnarab6ab6c12011-03-05 14:42:21 +00002995 DeclaratorLocFiller(ASTContext &Context, const DeclaratorChunk &Chunk)
2996 : Context(Context), Chunk(Chunk) {}
John McCall51bd8032009-10-18 01:05:36 +00002997
2998 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002999 llvm_unreachable("qualified type locs not expected here!");
John McCall51bd8032009-10-18 01:05:36 +00003000 }
3001
John McCallf85e1932011-06-15 23:02:42 +00003002 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
3003 fillAttributedTypeLoc(TL, Chunk.getAttrs());
3004 }
John McCall51bd8032009-10-18 01:05:36 +00003005 void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
3006 assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
3007 TL.setCaretLoc(Chunk.Loc);
3008 }
3009 void VisitPointerTypeLoc(PointerTypeLoc TL) {
3010 assert(Chunk.Kind == DeclaratorChunk::Pointer);
3011 TL.setStarLoc(Chunk.Loc);
3012 }
3013 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
3014 assert(Chunk.Kind == DeclaratorChunk::Pointer);
3015 TL.setStarLoc(Chunk.Loc);
3016 }
3017 void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
3018 assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
Abramo Bagnarab6ab6c12011-03-05 14:42:21 +00003019 const CXXScopeSpec& SS = Chunk.Mem.Scope();
3020 NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context);
3021
3022 const Type* ClsTy = TL.getClass();
3023 QualType ClsQT = QualType(ClsTy, 0);
3024 TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0);
3025 // Now copy source location info into the type loc component.
3026 TypeLoc ClsTL = ClsTInfo->getTypeLoc();
3027 switch (NNSLoc.getNestedNameSpecifier()->getKind()) {
3028 case NestedNameSpecifier::Identifier:
3029 assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc");
3030 {
Abramo Bagnarafd9c42e2011-03-06 22:48:24 +00003031 DependentNameTypeLoc DNTLoc = cast<DependentNameTypeLoc>(ClsTL);
Abramo Bagnara38a42912012-02-06 19:09:27 +00003032 DNTLoc.setElaboratedKeywordLoc(SourceLocation());
Abramo Bagnarab6ab6c12011-03-05 14:42:21 +00003033 DNTLoc.setQualifierLoc(NNSLoc.getPrefix());
3034 DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc());
3035 }
3036 break;
3037
3038 case NestedNameSpecifier::TypeSpec:
3039 case NestedNameSpecifier::TypeSpecWithTemplate:
3040 if (isa<ElaboratedType>(ClsTy)) {
3041 ElaboratedTypeLoc ETLoc = *cast<ElaboratedTypeLoc>(&ClsTL);
Abramo Bagnara38a42912012-02-06 19:09:27 +00003042 ETLoc.setElaboratedKeywordLoc(SourceLocation());
Abramo Bagnarab6ab6c12011-03-05 14:42:21 +00003043 ETLoc.setQualifierLoc(NNSLoc.getPrefix());
3044 TypeLoc NamedTL = ETLoc.getNamedTypeLoc();
3045 NamedTL.initializeFullCopy(NNSLoc.getTypeLoc());
3046 } else {
3047 ClsTL.initializeFullCopy(NNSLoc.getTypeLoc());
3048 }
3049 break;
3050
3051 case NestedNameSpecifier::Namespace:
3052 case NestedNameSpecifier::NamespaceAlias:
3053 case NestedNameSpecifier::Global:
3054 llvm_unreachable("Nested-name-specifier must name a type");
Abramo Bagnarab6ab6c12011-03-05 14:42:21 +00003055 }
3056
3057 // Finally fill in MemberPointerLocInfo fields.
John McCall51bd8032009-10-18 01:05:36 +00003058 TL.setStarLoc(Chunk.Loc);
Abramo Bagnarab6ab6c12011-03-05 14:42:21 +00003059 TL.setClassTInfo(ClsTInfo);
John McCall51bd8032009-10-18 01:05:36 +00003060 }
3061 void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
3062 assert(Chunk.Kind == DeclaratorChunk::Reference);
John McCall54e14c42009-10-22 22:37:11 +00003063 // 'Amp' is misleading: this might have been originally
3064 /// spelled with AmpAmp.
John McCall51bd8032009-10-18 01:05:36 +00003065 TL.setAmpLoc(Chunk.Loc);
3066 }
3067 void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
3068 assert(Chunk.Kind == DeclaratorChunk::Reference);
3069 assert(!Chunk.Ref.LValueRef);
3070 TL.setAmpAmpLoc(Chunk.Loc);
3071 }
3072 void VisitArrayTypeLoc(ArrayTypeLoc TL) {
3073 assert(Chunk.Kind == DeclaratorChunk::Array);
3074 TL.setLBracketLoc(Chunk.Loc);
3075 TL.setRBracketLoc(Chunk.EndLoc);
3076 TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
3077 }
3078 void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
3079 assert(Chunk.Kind == DeclaratorChunk::Function);
Abramo Bagnara796aa442011-03-12 11:17:06 +00003080 TL.setLocalRangeBegin(Chunk.Loc);
3081 TL.setLocalRangeEnd(Chunk.EndLoc);
Douglas Gregordab60ad2010-10-01 18:44:50 +00003082 TL.setTrailingReturn(!!Chunk.Fun.TrailingReturnType);
John McCall51bd8032009-10-18 01:05:36 +00003083
3084 const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
John McCall54e14c42009-10-22 22:37:11 +00003085 for (unsigned i = 0, e = TL.getNumArgs(), tpi = 0; i != e; ++i) {
John McCalld226f652010-08-21 09:40:31 +00003086 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
John McCall54e14c42009-10-22 22:37:11 +00003087 TL.setArg(tpi++, Param);
John McCall51bd8032009-10-18 01:05:36 +00003088 }
3089 // FIXME: exception specs
3090 }
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003091 void VisitParenTypeLoc(ParenTypeLoc TL) {
3092 assert(Chunk.Kind == DeclaratorChunk::Paren);
3093 TL.setLParenLoc(Chunk.Loc);
3094 TL.setRParenLoc(Chunk.EndLoc);
3095 }
John McCall51bd8032009-10-18 01:05:36 +00003096
3097 void VisitTypeLoc(TypeLoc TL) {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00003098 llvm_unreachable("unsupported TypeLoc kind in declarator!");
John McCall51bd8032009-10-18 01:05:36 +00003099 }
3100 };
Argyrios Kyrtzidisf352bdd2009-09-29 19:43:35 +00003101}
3102
John McCalla93c9342009-12-07 02:54:59 +00003103/// \brief Create and instantiate a TypeSourceInfo with type source information.
Argyrios Kyrtzidis4adab7f2009-08-19 01:28:06 +00003104///
3105/// \param T QualType referring to the type as written in source code.
Douglas Gregor05baacb2010-04-12 23:19:01 +00003106///
3107/// \param ReturnTypeInfo For declarators whose return type does not show
3108/// up in the normal place in the declaration specifiers (such as a C++
3109/// conversion function), this pointer will refer to a type source information
3110/// for that return type.
John McCalla93c9342009-12-07 02:54:59 +00003111TypeSourceInfo *
Douglas Gregor05baacb2010-04-12 23:19:01 +00003112Sema::GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
3113 TypeSourceInfo *ReturnTypeInfo) {
John McCalla93c9342009-12-07 02:54:59 +00003114 TypeSourceInfo *TInfo = Context.CreateTypeSourceInfo(T);
3115 UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc();
Argyrios Kyrtzidis4adab7f2009-08-19 01:28:06 +00003116
Douglas Gregora8bc8c92010-12-23 22:44:42 +00003117 // Handle parameter packs whose type is a pack expansion.
3118 if (isa<PackExpansionType>(T)) {
3119 cast<PackExpansionTypeLoc>(CurrTL).setEllipsisLoc(D.getEllipsisLoc());
3120 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
3121 }
3122
Sebastian Redl8ce35b02009-10-25 21:45:37 +00003123 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
John McCall14aa2172011-03-04 04:00:19 +00003124 while (isa<AttributedTypeLoc>(CurrTL)) {
3125 AttributedTypeLoc TL = cast<AttributedTypeLoc>(CurrTL);
3126 fillAttributedTypeLoc(TL, D.getTypeObject(i).getAttrs());
3127 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
3128 }
3129
Abramo Bagnarab6ab6c12011-03-05 14:42:21 +00003130 DeclaratorLocFiller(Context, D.getTypeObject(i)).Visit(CurrTL);
John McCall51bd8032009-10-18 01:05:36 +00003131 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
Argyrios Kyrtzidis4adab7f2009-08-19 01:28:06 +00003132 }
Argyrios Kyrtzidisf352bdd2009-09-29 19:43:35 +00003133
John McCallb3d87482010-08-24 05:47:05 +00003134 // If we have different source information for the return type, use
3135 // that. This really only applies to C++ conversion functions.
3136 if (ReturnTypeInfo) {
Douglas Gregor05baacb2010-04-12 23:19:01 +00003137 TypeLoc TL = ReturnTypeInfo->getTypeLoc();
3138 assert(TL.getFullDataSize() == CurrTL.getFullDataSize());
3139 memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize());
John McCallb3d87482010-08-24 05:47:05 +00003140 } else {
Douglas Gregorc21c7e92011-01-25 19:13:18 +00003141 TypeSpecLocFiller(Context, D.getDeclSpec()).Visit(CurrTL);
Douglas Gregor05baacb2010-04-12 23:19:01 +00003142 }
3143
John McCalla93c9342009-12-07 02:54:59 +00003144 return TInfo;
Argyrios Kyrtzidis4adab7f2009-08-19 01:28:06 +00003145}
3146
John McCalla93c9342009-12-07 02:54:59 +00003147/// \brief Create a LocInfoType to hold the given QualType and TypeSourceInfo.
John McCallb3d87482010-08-24 05:47:05 +00003148ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) {
Argyrios Kyrtzidis1bb8a452009-08-19 01:28:17 +00003149 // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
3150 // and Sema during declaration parsing. Try deallocating/caching them when
3151 // it's appropriate, instead of allocating them and keeping them around.
Douglas Gregoreb0eb492010-12-10 08:12:03 +00003152 LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType),
3153 TypeAlignment);
John McCalla93c9342009-12-07 02:54:59 +00003154 new (LocT) LocInfoType(T, TInfo);
Argyrios Kyrtzidis1bb8a452009-08-19 01:28:17 +00003155 assert(LocT->getTypeClass() != T->getTypeClass() &&
3156 "LocInfoType's TypeClass conflicts with an existing Type class");
John McCallb3d87482010-08-24 05:47:05 +00003157 return ParsedType::make(QualType(LocT, 0));
Argyrios Kyrtzidis1bb8a452009-08-19 01:28:17 +00003158}
3159
3160void LocInfoType::getAsStringInternal(std::string &Str,
3161 const PrintingPolicy &Policy) const {
David Blaikieb219cfc2011-09-23 05:06:16 +00003162 llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*"
Argyrios Kyrtzidis35d44e52009-08-19 01:46:06 +00003163 " was used directly instead of getting the QualType through"
3164 " GetTypeFromParser");
Argyrios Kyrtzidis1bb8a452009-08-19 01:28:17 +00003165}
3166
John McCallf312b1e2010-08-26 23:41:50 +00003167TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003168 // C99 6.7.6: Type names have no identifier. This is already validated by
3169 // the parser.
3170 assert(D.getIdentifier() == 0 && "Type name should have no identifier!");
Mike Stump1eb44332009-09-09 15:08:12 +00003171
Argyrios Kyrtzidisd3880f82011-06-28 03:01:18 +00003172 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCallbf1a0282010-06-04 23:28:52 +00003173 QualType T = TInfo->getType();
Chris Lattner5153ee62009-04-25 08:47:54 +00003174 if (D.isInvalidType())
Douglas Gregor809070a2009-02-18 17:45:20 +00003175 return true;
Steve Naroff5912a352007-08-28 20:14:24 +00003176
John McCalle82247a2011-10-01 05:17:03 +00003177 // Make sure there are no unused decl attributes on the declarator.
John McCallcdda47f2011-10-01 09:56:14 +00003178 // We don't want to do this for ObjC parameters because we're going
3179 // to apply them to the actual parameter declaration.
3180 if (D.getContext() != Declarator::ObjCParameterContext)
3181 checkUnusedDeclAttributes(D);
John McCalle82247a2011-10-01 05:17:03 +00003182
David Blaikie4e4d0842012-03-11 07:00:24 +00003183 if (getLangOpts().CPlusPlus) {
Douglas Gregor402abb52009-05-28 23:31:59 +00003184 // Check that there are no default arguments (C++ only).
Douglas Gregor6d6eb572008-05-07 04:49:29 +00003185 CheckExtraCXXDefaultArguments(D);
Douglas Gregor402abb52009-05-28 23:31:59 +00003186 }
3187
John McCallb3d87482010-08-24 05:47:05 +00003188 return CreateParsedType(T, TInfo);
Reid Spencer5f016e22007-07-11 17:01:13 +00003189}
3190
Douglas Gregore97179c2011-09-08 01:46:34 +00003191ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) {
3192 QualType T = Context.getObjCInstanceType();
3193 TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
3194 return CreateParsedType(T, TInfo);
3195}
3196
3197
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003198//===----------------------------------------------------------------------===//
3199// Type Attribute Processing
3200//===----------------------------------------------------------------------===//
3201
3202/// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
3203/// specified type. The attribute contains 1 argument, the id of the address
3204/// space for the type.
Mike Stump1eb44332009-09-09 15:08:12 +00003205static void HandleAddressSpaceTypeAttribute(QualType &Type,
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003206 const AttributeList &Attr, Sema &S){
John McCall0953e762009-09-24 19:53:00 +00003207
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003208 // If this type is already address space qualified, reject it.
Peter Collingbourne29e3ef82011-07-27 20:29:53 +00003209 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified by
3210 // qualifiers for two or more different address spaces."
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003211 if (Type.getAddressSpace()) {
3212 S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers);
Abramo Bagnarae215f722010-04-30 13:10:51 +00003213 Attr.setInvalid();
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003214 return;
3215 }
Mike Stump1eb44332009-09-09 15:08:12 +00003216
Peter Collingbourne020972d2011-07-27 20:30:05 +00003217 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be
3218 // qualified by an address-space qualifier."
3219 if (Type->isFunctionType()) {
3220 S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type);
3221 Attr.setInvalid();
3222 return;
3223 }
3224
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003225 // Check the attribute arguments.
3226 if (Attr.getNumArgs() != 1) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003227 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
Abramo Bagnarae215f722010-04-30 13:10:51 +00003228 Attr.setInvalid();
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003229 return;
3230 }
3231 Expr *ASArgExpr = static_cast<Expr *>(Attr.getArg(0));
3232 llvm::APSInt addrSpace(32);
Douglas Gregorac06a0e2010-05-18 23:01:22 +00003233 if (ASArgExpr->isTypeDependent() || ASArgExpr->isValueDependent() ||
3234 !ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003235 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_not_int)
3236 << ASArgExpr->getSourceRange();
Abramo Bagnarae215f722010-04-30 13:10:51 +00003237 Attr.setInvalid();
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003238 return;
3239 }
3240
John McCallefadb772009-07-28 06:52:18 +00003241 // Bounds checking.
3242 if (addrSpace.isSigned()) {
3243 if (addrSpace.isNegative()) {
3244 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_negative)
3245 << ASArgExpr->getSourceRange();
Abramo Bagnarae215f722010-04-30 13:10:51 +00003246 Attr.setInvalid();
John McCallefadb772009-07-28 06:52:18 +00003247 return;
3248 }
3249 addrSpace.setIsSigned(false);
3250 }
3251 llvm::APSInt max(addrSpace.getBitWidth());
John McCall0953e762009-09-24 19:53:00 +00003252 max = Qualifiers::MaxAddressSpace;
John McCallefadb772009-07-28 06:52:18 +00003253 if (addrSpace > max) {
3254 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_too_high)
John McCall0953e762009-09-24 19:53:00 +00003255 << Qualifiers::MaxAddressSpace << ASArgExpr->getSourceRange();
Abramo Bagnarae215f722010-04-30 13:10:51 +00003256 Attr.setInvalid();
John McCallefadb772009-07-28 06:52:18 +00003257 return;
3258 }
3259
Mike Stump1eb44332009-09-09 15:08:12 +00003260 unsigned ASIdx = static_cast<unsigned>(addrSpace.getZExtValue());
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00003261 Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003262}
3263
John McCalld85bf9d2012-02-08 00:46:41 +00003264/// Does this type have a "direct" ownership qualifier? That is,
3265/// is it written like "__strong id", as opposed to something like
3266/// "typeof(foo)", where that happens to be strong?
3267static bool hasDirectOwnershipQualifier(QualType type) {
3268 // Fast path: no qualifier at all.
3269 assert(type.getQualifiers().hasObjCLifetime());
3270
3271 while (true) {
3272 // __strong id
3273 if (const AttributedType *attr = dyn_cast<AttributedType>(type)) {
3274 if (attr->getAttrKind() == AttributedType::attr_objc_ownership)
3275 return true;
3276
3277 type = attr->getModifiedType();
3278
3279 // X *__strong (...)
3280 } else if (const ParenType *paren = dyn_cast<ParenType>(type)) {
3281 type = paren->getInnerType();
3282
3283 // That's it for things we want to complain about. In particular,
3284 // we do not want to look through typedefs, typeof(expr),
3285 // typeof(type), or any other way that the type is somehow
3286 // abstracted.
3287 } else {
3288
3289 return false;
3290 }
3291 }
3292}
3293
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00003294/// handleObjCOwnershipTypeAttr - Process an objc_ownership
John McCallf85e1932011-06-15 23:02:42 +00003295/// attribute on the specified type.
3296///
3297/// Returns 'true' if the attribute was handled.
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00003298static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
John McCallf85e1932011-06-15 23:02:42 +00003299 AttributeList &attr,
3300 QualType &type) {
Argyrios Kyrtzidise71202e2011-11-04 20:37:24 +00003301 bool NonObjCPointer = false;
3302
3303 if (!type->isDependentType()) {
3304 if (const PointerType *ptr = type->getAs<PointerType>()) {
3305 QualType pointee = ptr->getPointeeType();
3306 if (pointee->isObjCRetainableType() || pointee->isPointerType())
3307 return false;
3308 // It is important not to lose the source info that there was an attribute
3309 // applied to non-objc pointer. We will create an attributed type but
3310 // its type will be the same as the original type.
3311 NonObjCPointer = true;
3312 } else if (!type->isObjCRetainableType()) {
3313 return false;
3314 }
3315 }
John McCallf85e1932011-06-15 23:02:42 +00003316
3317 Sema &S = state.getSema();
Argyrios Kyrtzidis440ec2e2011-09-28 18:35:06 +00003318 SourceLocation AttrLoc = attr.getLoc();
3319 if (AttrLoc.isMacroID())
3320 AttrLoc = S.getSourceManager().getImmediateExpansionRange(AttrLoc).first;
John McCallf85e1932011-06-15 23:02:42 +00003321
John McCallf85e1932011-06-15 23:02:42 +00003322 if (!attr.getParameterName()) {
Argyrios Kyrtzidis440ec2e2011-09-28 18:35:06 +00003323 S.Diag(AttrLoc, diag::err_attribute_argument_n_not_string)
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00003324 << "objc_ownership" << 1;
John McCallf85e1932011-06-15 23:02:42 +00003325 attr.setInvalid();
3326 return true;
3327 }
3328
John McCalld85bf9d2012-02-08 00:46:41 +00003329 // Consume lifetime attributes without further comment outside of
3330 // ARC mode.
David Blaikie4e4d0842012-03-11 07:00:24 +00003331 if (!S.getLangOpts().ObjCAutoRefCount)
John McCalld85bf9d2012-02-08 00:46:41 +00003332 return true;
3333
John McCallf85e1932011-06-15 23:02:42 +00003334 Qualifiers::ObjCLifetime lifetime;
3335 if (attr.getParameterName()->isStr("none"))
3336 lifetime = Qualifiers::OCL_ExplicitNone;
3337 else if (attr.getParameterName()->isStr("strong"))
3338 lifetime = Qualifiers::OCL_Strong;
3339 else if (attr.getParameterName()->isStr("weak"))
3340 lifetime = Qualifiers::OCL_Weak;
3341 else if (attr.getParameterName()->isStr("autoreleasing"))
3342 lifetime = Qualifiers::OCL_Autoreleasing;
3343 else {
Argyrios Kyrtzidis440ec2e2011-09-28 18:35:06 +00003344 S.Diag(AttrLoc, diag::warn_attribute_type_not_supported)
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00003345 << "objc_ownership" << attr.getParameterName();
John McCallf85e1932011-06-15 23:02:42 +00003346 attr.setInvalid();
3347 return true;
3348 }
3349
John McCalld85bf9d2012-02-08 00:46:41 +00003350 SplitQualType underlyingType = type.split();
3351
3352 // Check for redundant/conflicting ownership qualifiers.
3353 if (Qualifiers::ObjCLifetime previousLifetime
3354 = type.getQualifiers().getObjCLifetime()) {
3355 // If it's written directly, that's an error.
3356 if (hasDirectOwnershipQualifier(type)) {
3357 S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant)
3358 << type;
3359 return true;
3360 }
3361
3362 // Otherwise, if the qualifiers actually conflict, pull sugar off
3363 // until we reach a type that is directly qualified.
3364 if (previousLifetime != lifetime) {
3365 // This should always terminate: the canonical type is
3366 // qualified, so some bit of sugar must be hiding it.
3367 while (!underlyingType.Quals.hasObjCLifetime()) {
3368 underlyingType = underlyingType.getSingleStepDesugaredType();
3369 }
3370 underlyingType.Quals.removeObjCLifetime();
3371 }
3372 }
3373
3374 underlyingType.Quals.addObjCLifetime(lifetime);
John McCallf85e1932011-06-15 23:02:42 +00003375
Argyrios Kyrtzidise71202e2011-11-04 20:37:24 +00003376 if (NonObjCPointer) {
3377 StringRef name = attr.getName()->getName();
3378 switch (lifetime) {
3379 case Qualifiers::OCL_None:
3380 case Qualifiers::OCL_ExplicitNone:
3381 break;
3382 case Qualifiers::OCL_Strong: name = "__strong"; break;
3383 case Qualifiers::OCL_Weak: name = "__weak"; break;
3384 case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break;
3385 }
3386 S.Diag(AttrLoc, diag::warn_objc_object_attribute_wrong_type)
3387 << name << type;
3388 }
3389
John McCallf85e1932011-06-15 23:02:42 +00003390 QualType origType = type;
Argyrios Kyrtzidise71202e2011-11-04 20:37:24 +00003391 if (!NonObjCPointer)
John McCalld85bf9d2012-02-08 00:46:41 +00003392 type = S.Context.getQualifiedType(underlyingType);
John McCallf85e1932011-06-15 23:02:42 +00003393
3394 // If we have a valid source location for the attribute, use an
3395 // AttributedType instead.
Argyrios Kyrtzidis440ec2e2011-09-28 18:35:06 +00003396 if (AttrLoc.isValid())
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00003397 type = S.Context.getAttributedType(AttributedType::attr_objc_ownership,
John McCallf85e1932011-06-15 23:02:42 +00003398 origType, type);
3399
John McCall9f084a32011-07-06 00:26:06 +00003400 // Forbid __weak if the runtime doesn't support it.
John McCallf85e1932011-06-15 23:02:42 +00003401 if (lifetime == Qualifiers::OCL_Weak &&
David Blaikie4e4d0842012-03-11 07:00:24 +00003402 !S.getLangOpts().ObjCRuntimeHasWeak && !NonObjCPointer) {
John McCallf85e1932011-06-15 23:02:42 +00003403
3404 // Actually, delay this until we know what we're parsing.
3405 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
3406 S.DelayedDiagnostics.add(
Argyrios Kyrtzidis440ec2e2011-09-28 18:35:06 +00003407 sema::DelayedDiagnostic::makeForbiddenType(
3408 S.getSourceManager().getExpansionLoc(AttrLoc),
John McCallf85e1932011-06-15 23:02:42 +00003409 diag::err_arc_weak_no_runtime, type, /*ignored*/ 0));
3410 } else {
Argyrios Kyrtzidis440ec2e2011-09-28 18:35:06 +00003411 S.Diag(AttrLoc, diag::err_arc_weak_no_runtime);
John McCallf85e1932011-06-15 23:02:42 +00003412 }
3413
3414 attr.setInvalid();
3415 return true;
3416 }
Fariborz Jahanian742352a2011-07-06 19:24:05 +00003417
3418 // Forbid __weak for class objects marked as
3419 // objc_arc_weak_reference_unavailable
3420 if (lifetime == Qualifiers::OCL_Weak) {
3421 QualType T = type;
Fariborz Jahanian742352a2011-07-06 19:24:05 +00003422 while (const PointerType *ptr = T->getAs<PointerType>())
3423 T = ptr->getPointeeType();
3424 if (const ObjCObjectPointerType *ObjT = T->getAs<ObjCObjectPointerType>()) {
3425 ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl();
Fariborz Jahanian7263fee2011-07-06 20:48:48 +00003426 if (Class->isArcWeakrefUnavailable()) {
Argyrios Kyrtzidis440ec2e2011-09-28 18:35:06 +00003427 S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class);
Fariborz Jahanian742352a2011-07-06 19:24:05 +00003428 S.Diag(ObjT->getInterfaceDecl()->getLocation(),
3429 diag::note_class_declared);
Fariborz Jahanian742352a2011-07-06 19:24:05 +00003430 }
3431 }
3432 }
3433
John McCallf85e1932011-06-15 23:02:42 +00003434 return true;
3435}
3436
John McCall711c52b2011-01-05 12:14:39 +00003437/// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type
3438/// attribute on the specified type. Returns true to indicate that
3439/// the attribute was handled, false to indicate that the type does
3440/// not permit the attribute.
3441static bool handleObjCGCTypeAttr(TypeProcessingState &state,
3442 AttributeList &attr,
3443 QualType &type) {
3444 Sema &S = state.getSema();
3445
3446 // Delay if this isn't some kind of pointer.
3447 if (!type->isPointerType() &&
3448 !type->isObjCObjectPointerType() &&
3449 !type->isBlockPointerType())
3450 return false;
3451
3452 if (type.getObjCGCAttr() != Qualifiers::GCNone) {
3453 S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc);
3454 attr.setInvalid();
3455 return true;
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00003456 }
Mike Stump1eb44332009-09-09 15:08:12 +00003457
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00003458 // Check the attribute arguments.
John McCall711c52b2011-01-05 12:14:39 +00003459 if (!attr.getParameterName()) {
3460 S.Diag(attr.getLoc(), diag::err_attribute_argument_n_not_string)
Fariborz Jahanianba372b82009-02-18 17:52:36 +00003461 << "objc_gc" << 1;
John McCall711c52b2011-01-05 12:14:39 +00003462 attr.setInvalid();
3463 return true;
Fariborz Jahanianba372b82009-02-18 17:52:36 +00003464 }
John McCall0953e762009-09-24 19:53:00 +00003465 Qualifiers::GC GCAttr;
John McCall711c52b2011-01-05 12:14:39 +00003466 if (attr.getNumArgs() != 0) {
3467 S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
3468 attr.setInvalid();
3469 return true;
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00003470 }
John McCall711c52b2011-01-05 12:14:39 +00003471 if (attr.getParameterName()->isStr("weak"))
John McCall0953e762009-09-24 19:53:00 +00003472 GCAttr = Qualifiers::Weak;
John McCall711c52b2011-01-05 12:14:39 +00003473 else if (attr.getParameterName()->isStr("strong"))
John McCall0953e762009-09-24 19:53:00 +00003474 GCAttr = Qualifiers::Strong;
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00003475 else {
John McCall711c52b2011-01-05 12:14:39 +00003476 S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported)
3477 << "objc_gc" << attr.getParameterName();
3478 attr.setInvalid();
3479 return true;
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00003480 }
Mike Stump1eb44332009-09-09 15:08:12 +00003481
John McCall14aa2172011-03-04 04:00:19 +00003482 QualType origType = type;
3483 type = S.Context.getObjCGCQualType(origType, GCAttr);
3484
3485 // Make an attributed type to preserve the source information.
3486 if (attr.getLoc().isValid())
3487 type = S.Context.getAttributedType(AttributedType::attr_objc_gc,
3488 origType, type);
3489
John McCall711c52b2011-01-05 12:14:39 +00003490 return true;
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00003491}
3492
John McCalle6a365d2010-12-19 02:44:49 +00003493namespace {
3494 /// A helper class to unwrap a type down to a function for the
3495 /// purposes of applying attributes there.
3496 ///
3497 /// Use:
3498 /// FunctionTypeUnwrapper unwrapped(SemaRef, T);
3499 /// if (unwrapped.isFunctionType()) {
3500 /// const FunctionType *fn = unwrapped.get();
3501 /// // change fn somehow
3502 /// T = unwrapped.wrap(fn);
3503 /// }
3504 struct FunctionTypeUnwrapper {
3505 enum WrapKind {
3506 Desugar,
3507 Parens,
3508 Pointer,
3509 BlockPointer,
3510 Reference,
3511 MemberPointer
3512 };
3513
3514 QualType Original;
3515 const FunctionType *Fn;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003516 SmallVector<unsigned char /*WrapKind*/, 8> Stack;
John McCalle6a365d2010-12-19 02:44:49 +00003517
3518 FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) {
3519 while (true) {
3520 const Type *Ty = T.getTypePtr();
3521 if (isa<FunctionType>(Ty)) {
3522 Fn = cast<FunctionType>(Ty);
3523 return;
3524 } else if (isa<ParenType>(Ty)) {
3525 T = cast<ParenType>(Ty)->getInnerType();
3526 Stack.push_back(Parens);
3527 } else if (isa<PointerType>(Ty)) {
3528 T = cast<PointerType>(Ty)->getPointeeType();
3529 Stack.push_back(Pointer);
3530 } else if (isa<BlockPointerType>(Ty)) {
3531 T = cast<BlockPointerType>(Ty)->getPointeeType();
3532 Stack.push_back(BlockPointer);
3533 } else if (isa<MemberPointerType>(Ty)) {
3534 T = cast<MemberPointerType>(Ty)->getPointeeType();
3535 Stack.push_back(MemberPointer);
3536 } else if (isa<ReferenceType>(Ty)) {
3537 T = cast<ReferenceType>(Ty)->getPointeeType();
3538 Stack.push_back(Reference);
3539 } else {
3540 const Type *DTy = Ty->getUnqualifiedDesugaredType();
3541 if (Ty == DTy) {
3542 Fn = 0;
3543 return;
3544 }
3545
3546 T = QualType(DTy, 0);
3547 Stack.push_back(Desugar);
3548 }
3549 }
3550 }
3551
3552 bool isFunctionType() const { return (Fn != 0); }
3553 const FunctionType *get() const { return Fn; }
3554
3555 QualType wrap(Sema &S, const FunctionType *New) {
3556 // If T wasn't modified from the unwrapped type, do nothing.
3557 if (New == get()) return Original;
3558
3559 Fn = New;
3560 return wrap(S.Context, Original, 0);
3561 }
3562
3563 private:
3564 QualType wrap(ASTContext &C, QualType Old, unsigned I) {
3565 if (I == Stack.size())
3566 return C.getQualifiedType(Fn, Old.getQualifiers());
3567
3568 // Build up the inner type, applying the qualifiers from the old
3569 // type to the new type.
3570 SplitQualType SplitOld = Old.split();
3571
3572 // As a special case, tail-recurse if there are no qualifiers.
John McCall200fa532012-02-08 00:46:36 +00003573 if (SplitOld.Quals.empty())
3574 return wrap(C, SplitOld.Ty, I);
3575 return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals);
John McCalle6a365d2010-12-19 02:44:49 +00003576 }
3577
3578 QualType wrap(ASTContext &C, const Type *Old, unsigned I) {
3579 if (I == Stack.size()) return QualType(Fn, 0);
3580
3581 switch (static_cast<WrapKind>(Stack[I++])) {
3582 case Desugar:
3583 // This is the point at which we potentially lose source
3584 // information.
3585 return wrap(C, Old->getUnqualifiedDesugaredType(), I);
3586
3587 case Parens: {
3588 QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I);
3589 return C.getParenType(New);
3590 }
3591
3592 case Pointer: {
3593 QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I);
3594 return C.getPointerType(New);
3595 }
3596
3597 case BlockPointer: {
3598 QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I);
3599 return C.getBlockPointerType(New);
3600 }
3601
3602 case MemberPointer: {
3603 const MemberPointerType *OldMPT = cast<MemberPointerType>(Old);
3604 QualType New = wrap(C, OldMPT->getPointeeType(), I);
3605 return C.getMemberPointerType(New, OldMPT->getClass());
3606 }
3607
3608 case Reference: {
3609 const ReferenceType *OldRef = cast<ReferenceType>(Old);
3610 QualType New = wrap(C, OldRef->getPointeeType(), I);
3611 if (isa<LValueReferenceType>(OldRef))
3612 return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue());
3613 else
3614 return C.getRValueReferenceType(New);
3615 }
3616 }
3617
3618 llvm_unreachable("unknown wrapping kind");
John McCalle6a365d2010-12-19 02:44:49 +00003619 }
3620 };
3621}
3622
John McCall711c52b2011-01-05 12:14:39 +00003623/// Process an individual function attribute. Returns true to
3624/// indicate that the attribute was handled, false if it wasn't.
3625static bool handleFunctionTypeAttr(TypeProcessingState &state,
3626 AttributeList &attr,
3627 QualType &type) {
3628 Sema &S = state.getSema();
John McCalle6a365d2010-12-19 02:44:49 +00003629
John McCall711c52b2011-01-05 12:14:39 +00003630 FunctionTypeUnwrapper unwrapped(S, type);
Mike Stump24556362009-07-25 21:26:53 +00003631
John McCall711c52b2011-01-05 12:14:39 +00003632 if (attr.getKind() == AttributeList::AT_noreturn) {
3633 if (S.CheckNoReturnAttr(attr))
John McCall04a67a62010-02-05 21:31:56 +00003634 return true;
John McCalle6a365d2010-12-19 02:44:49 +00003635
John McCall711c52b2011-01-05 12:14:39 +00003636 // Delay if this is not a function type.
3637 if (!unwrapped.isFunctionType())
3638 return false;
3639
John McCall04a67a62010-02-05 21:31:56 +00003640 // Otherwise we can process right away.
John McCall711c52b2011-01-05 12:14:39 +00003641 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true);
3642 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
3643 return true;
John McCall04a67a62010-02-05 21:31:56 +00003644 }
Mike Stump24556362009-07-25 21:26:53 +00003645
John McCallf85e1932011-06-15 23:02:42 +00003646 // ns_returns_retained is not always a type attribute, but if we got
3647 // here, we're treating it as one right now.
3648 if (attr.getKind() == AttributeList::AT_ns_returns_retained) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003649 assert(S.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00003650 "ns_returns_retained treated as type attribute in non-ARC");
3651 if (attr.getNumArgs()) return true;
3652
3653 // Delay if this is not a function type.
3654 if (!unwrapped.isFunctionType())
3655 return false;
3656
3657 FunctionType::ExtInfo EI
3658 = unwrapped.get()->getExtInfo().withProducesResult(true);
3659 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
3660 return true;
3661 }
3662
John McCall711c52b2011-01-05 12:14:39 +00003663 if (attr.getKind() == AttributeList::AT_regparm) {
3664 unsigned value;
3665 if (S.CheckRegparmAttr(attr, value))
Rafael Espindola425ef722010-03-30 22:15:11 +00003666 return true;
3667
John McCall711c52b2011-01-05 12:14:39 +00003668 // Delay if this is not a function type.
3669 if (!unwrapped.isFunctionType())
Rafael Espindola425ef722010-03-30 22:15:11 +00003670 return false;
3671
Argyrios Kyrtzidisce955662011-01-25 23:16:40 +00003672 // Diagnose regparm with fastcall.
3673 const FunctionType *fn = unwrapped.get();
3674 CallingConv CC = fn->getCallConv();
3675 if (CC == CC_X86FastCall) {
3676 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
3677 << FunctionType::getNameForCallConv(CC)
3678 << "regparm";
3679 attr.setInvalid();
3680 return true;
3681 }
3682
John McCalle6a365d2010-12-19 02:44:49 +00003683 FunctionType::ExtInfo EI =
John McCall711c52b2011-01-05 12:14:39 +00003684 unwrapped.get()->getExtInfo().withRegParm(value);
3685 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
3686 return true;
Rafael Espindola425ef722010-03-30 22:15:11 +00003687 }
3688
John McCall04a67a62010-02-05 21:31:56 +00003689 // Otherwise, a calling convention.
John McCall711c52b2011-01-05 12:14:39 +00003690 CallingConv CC;
3691 if (S.CheckCallingConvAttr(attr, CC))
3692 return true;
John McCallf82b4e82010-02-04 05:44:44 +00003693
John McCall04a67a62010-02-05 21:31:56 +00003694 // Delay if the type didn't work out to a function.
John McCall711c52b2011-01-05 12:14:39 +00003695 if (!unwrapped.isFunctionType()) return false;
John McCall04a67a62010-02-05 21:31:56 +00003696
John McCall711c52b2011-01-05 12:14:39 +00003697 const FunctionType *fn = unwrapped.get();
3698 CallingConv CCOld = fn->getCallConv();
Charles Davis064f7db2010-02-23 06:13:55 +00003699 if (S.Context.getCanonicalCallConv(CC) ==
Abramo Bagnarae215f722010-04-30 13:10:51 +00003700 S.Context.getCanonicalCallConv(CCOld)) {
Argyrios Kyrtzidisce955662011-01-25 23:16:40 +00003701 FunctionType::ExtInfo EI= unwrapped.get()->getExtInfo().withCallingConv(CC);
3702 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
John McCall711c52b2011-01-05 12:14:39 +00003703 return true;
Abramo Bagnarae215f722010-04-30 13:10:51 +00003704 }
John McCall04a67a62010-02-05 21:31:56 +00003705
Roman Divacky8e68f1c2011-08-05 16:37:22 +00003706 if (CCOld != (S.LangOpts.MRTD ? CC_X86StdCall : CC_Default)) {
John McCall04a67a62010-02-05 21:31:56 +00003707 // Should we diagnose reapplications of the same convention?
John McCall711c52b2011-01-05 12:14:39 +00003708 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
John McCall04a67a62010-02-05 21:31:56 +00003709 << FunctionType::getNameForCallConv(CC)
3710 << FunctionType::getNameForCallConv(CCOld);
John McCall711c52b2011-01-05 12:14:39 +00003711 attr.setInvalid();
3712 return true;
John McCall04a67a62010-02-05 21:31:56 +00003713 }
3714
3715 // Diagnose the use of X86 fastcall on varargs or unprototyped functions.
3716 if (CC == CC_X86FastCall) {
John McCall711c52b2011-01-05 12:14:39 +00003717 if (isa<FunctionNoProtoType>(fn)) {
3718 S.Diag(attr.getLoc(), diag::err_cconv_knr)
John McCall04a67a62010-02-05 21:31:56 +00003719 << FunctionType::getNameForCallConv(CC);
John McCall711c52b2011-01-05 12:14:39 +00003720 attr.setInvalid();
3721 return true;
John McCall04a67a62010-02-05 21:31:56 +00003722 }
3723
John McCall711c52b2011-01-05 12:14:39 +00003724 const FunctionProtoType *FnP = cast<FunctionProtoType>(fn);
John McCall04a67a62010-02-05 21:31:56 +00003725 if (FnP->isVariadic()) {
John McCall711c52b2011-01-05 12:14:39 +00003726 S.Diag(attr.getLoc(), diag::err_cconv_varargs)
John McCall04a67a62010-02-05 21:31:56 +00003727 << FunctionType::getNameForCallConv(CC);
John McCall711c52b2011-01-05 12:14:39 +00003728 attr.setInvalid();
3729 return true;
John McCall04a67a62010-02-05 21:31:56 +00003730 }
Argyrios Kyrtzidisce955662011-01-25 23:16:40 +00003731
3732 // Also diagnose fastcall with regparm.
Eli Friedmana49218e2011-04-09 08:18:08 +00003733 if (fn->getHasRegParm()) {
Argyrios Kyrtzidisce955662011-01-25 23:16:40 +00003734 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
3735 << "regparm"
3736 << FunctionType::getNameForCallConv(CC);
3737 attr.setInvalid();
3738 return true;
3739 }
John McCall04a67a62010-02-05 21:31:56 +00003740 }
3741
John McCall711c52b2011-01-05 12:14:39 +00003742 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withCallingConv(CC);
3743 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
3744 return true;
John McCallf82b4e82010-02-04 05:44:44 +00003745}
3746
Peter Collingbourne207f4d82011-03-18 22:38:29 +00003747/// Handle OpenCL image access qualifiers: read_only, write_only, read_write
3748static void HandleOpenCLImageAccessAttribute(QualType& CurType,
3749 const AttributeList &Attr,
3750 Sema &S) {
3751 // Check the attribute arguments.
3752 if (Attr.getNumArgs() != 1) {
3753 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
3754 Attr.setInvalid();
3755 return;
3756 }
3757 Expr *sizeExpr = static_cast<Expr *>(Attr.getArg(0));
3758 llvm::APSInt arg(32);
3759 if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() ||
3760 !sizeExpr->isIntegerConstantExpr(arg, S.Context)) {
3761 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
3762 << "opencl_image_access" << sizeExpr->getSourceRange();
3763 Attr.setInvalid();
3764 return;
3765 }
3766 unsigned iarg = static_cast<unsigned>(arg.getZExtValue());
3767 switch (iarg) {
3768 case CLIA_read_only:
3769 case CLIA_write_only:
3770 case CLIA_read_write:
3771 // Implemented in a separate patch
3772 break;
3773 default:
3774 // Implemented in a separate patch
3775 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
3776 << sizeExpr->getSourceRange();
3777 Attr.setInvalid();
3778 break;
3779 }
3780}
3781
John Thompson6e132aa2009-12-04 21:51:28 +00003782/// HandleVectorSizeAttribute - this attribute is only applicable to integral
3783/// and float scalars, although arrays, pointers, and function return values are
3784/// allowed in conjunction with this construct. Aggregates with this attribute
3785/// are invalid, even if they are of the same size as a corresponding scalar.
3786/// The raw attribute should contain precisely 1 argument, the vector size for
3787/// the variable, measured in bytes. If curType and rawAttr are well formed,
3788/// this routine will return a new vector type.
Chris Lattner788b0fd2010-06-23 06:00:24 +00003789static void HandleVectorSizeAttr(QualType& CurType, const AttributeList &Attr,
3790 Sema &S) {
Bob Wilson56affbc2010-11-16 00:32:16 +00003791 // Check the attribute arguments.
John Thompson6e132aa2009-12-04 21:51:28 +00003792 if (Attr.getNumArgs() != 1) {
3793 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
Abramo Bagnarae215f722010-04-30 13:10:51 +00003794 Attr.setInvalid();
John Thompson6e132aa2009-12-04 21:51:28 +00003795 return;
3796 }
3797 Expr *sizeExpr = static_cast<Expr *>(Attr.getArg(0));
3798 llvm::APSInt vecSize(32);
Douglas Gregorac06a0e2010-05-18 23:01:22 +00003799 if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() ||
3800 !sizeExpr->isIntegerConstantExpr(vecSize, S.Context)) {
John Thompson6e132aa2009-12-04 21:51:28 +00003801 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
3802 << "vector_size" << sizeExpr->getSourceRange();
Abramo Bagnarae215f722010-04-30 13:10:51 +00003803 Attr.setInvalid();
John Thompson6e132aa2009-12-04 21:51:28 +00003804 return;
3805 }
3806 // the base type must be integer or float, and can't already be a vector.
Douglas Gregorf6094622010-07-23 15:58:24 +00003807 if (!CurType->isIntegerType() && !CurType->isRealFloatingType()) {
John Thompson6e132aa2009-12-04 21:51:28 +00003808 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
Abramo Bagnarae215f722010-04-30 13:10:51 +00003809 Attr.setInvalid();
John Thompson6e132aa2009-12-04 21:51:28 +00003810 return;
3811 }
3812 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
3813 // vecSize is specified in bytes - convert to bits.
3814 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
3815
3816 // the vector size needs to be an integral multiple of the type size.
3817 if (vectorSize % typeSize) {
3818 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
3819 << sizeExpr->getSourceRange();
Abramo Bagnarae215f722010-04-30 13:10:51 +00003820 Attr.setInvalid();
John Thompson6e132aa2009-12-04 21:51:28 +00003821 return;
3822 }
3823 if (vectorSize == 0) {
3824 S.Diag(Attr.getLoc(), diag::err_attribute_zero_size)
3825 << sizeExpr->getSourceRange();
Abramo Bagnarae215f722010-04-30 13:10:51 +00003826 Attr.setInvalid();
John Thompson6e132aa2009-12-04 21:51:28 +00003827 return;
3828 }
3829
3830 // Success! Instantiate the vector type, the number of elements is > 0, and
3831 // not required to be a power of 2, unlike GCC.
Chris Lattner788b0fd2010-06-23 06:00:24 +00003832 CurType = S.Context.getVectorType(CurType, vectorSize/typeSize,
Bob Wilsone86d78c2010-11-10 21:56:12 +00003833 VectorType::GenericVector);
John Thompson6e132aa2009-12-04 21:51:28 +00003834}
3835
Douglas Gregor4ac01402011-06-15 16:02:29 +00003836/// \brief Process the OpenCL-like ext_vector_type attribute when it occurs on
3837/// a type.
3838static void HandleExtVectorTypeAttr(QualType &CurType,
3839 const AttributeList &Attr,
3840 Sema &S) {
3841 Expr *sizeExpr;
3842
3843 // Special case where the argument is a template id.
3844 if (Attr.getParameterName()) {
3845 CXXScopeSpec SS;
Abramo Bagnarae4b92762012-01-27 09:46:47 +00003846 SourceLocation TemplateKWLoc;
Douglas Gregor4ac01402011-06-15 16:02:29 +00003847 UnqualifiedId id;
3848 id.setIdentifier(Attr.getParameterName(), Attr.getLoc());
Abramo Bagnarae4b92762012-01-27 09:46:47 +00003849
3850 ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, TemplateKWLoc,
3851 id, false, false);
Douglas Gregor4ac01402011-06-15 16:02:29 +00003852 if (Size.isInvalid())
3853 return;
3854
3855 sizeExpr = Size.get();
3856 } else {
3857 // check the attribute arguments.
3858 if (Attr.getNumArgs() != 1) {
3859 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
3860 return;
3861 }
3862 sizeExpr = Attr.getArg(0);
3863 }
3864
3865 // Create the vector type.
3866 QualType T = S.BuildExtVectorType(CurType, sizeExpr, Attr.getLoc());
3867 if (!T.isNull())
3868 CurType = T;
3869}
3870
Bob Wilson4211bb62010-11-16 00:32:24 +00003871/// HandleNeonVectorTypeAttr - The "neon_vector_type" and
3872/// "neon_polyvector_type" attributes are used to create vector types that
3873/// are mangled according to ARM's ABI. Otherwise, these types are identical
3874/// to those created with the "vector_size" attribute. Unlike "vector_size"
3875/// the argument to these Neon attributes is the number of vector elements,
3876/// not the vector size in bytes. The vector width and element type must
3877/// match one of the standard Neon vector types.
3878static void HandleNeonVectorTypeAttr(QualType& CurType,
3879 const AttributeList &Attr, Sema &S,
3880 VectorType::VectorKind VecKind,
3881 const char *AttrName) {
3882 // Check the attribute arguments.
3883 if (Attr.getNumArgs() != 1) {
3884 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
3885 Attr.setInvalid();
3886 return;
3887 }
3888 // The number of elements must be an ICE.
3889 Expr *numEltsExpr = static_cast<Expr *>(Attr.getArg(0));
3890 llvm::APSInt numEltsInt(32);
3891 if (numEltsExpr->isTypeDependent() || numEltsExpr->isValueDependent() ||
3892 !numEltsExpr->isIntegerConstantExpr(numEltsInt, S.Context)) {
3893 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
3894 << AttrName << numEltsExpr->getSourceRange();
3895 Attr.setInvalid();
3896 return;
3897 }
3898 // Only certain element types are supported for Neon vectors.
3899 const BuiltinType* BTy = CurType->getAs<BuiltinType>();
3900 if (!BTy ||
3901 (VecKind == VectorType::NeonPolyVector &&
3902 BTy->getKind() != BuiltinType::SChar &&
3903 BTy->getKind() != BuiltinType::Short) ||
3904 (BTy->getKind() != BuiltinType::SChar &&
3905 BTy->getKind() != BuiltinType::UChar &&
3906 BTy->getKind() != BuiltinType::Short &&
3907 BTy->getKind() != BuiltinType::UShort &&
3908 BTy->getKind() != BuiltinType::Int &&
3909 BTy->getKind() != BuiltinType::UInt &&
3910 BTy->getKind() != BuiltinType::LongLong &&
3911 BTy->getKind() != BuiltinType::ULongLong &&
3912 BTy->getKind() != BuiltinType::Float)) {
3913 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) <<CurType;
3914 Attr.setInvalid();
3915 return;
3916 }
3917 // The total size of the vector must be 64 or 128 bits.
3918 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
3919 unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue());
3920 unsigned vecSize = typeSize * numElts;
3921 if (vecSize != 64 && vecSize != 128) {
3922 S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType;
3923 Attr.setInvalid();
3924 return;
3925 }
3926
3927 CurType = S.Context.getVectorType(CurType, numElts, VecKind);
3928}
3929
John McCall711c52b2011-01-05 12:14:39 +00003930static void processTypeAttrs(TypeProcessingState &state, QualType &type,
3931 bool isDeclSpec, AttributeList *attrs) {
Chris Lattner232e8822008-02-21 01:08:11 +00003932 // Scan through and apply attributes to this type where it makes sense. Some
3933 // attributes (such as __address_space__, __vector_size__, etc) apply to the
3934 // type, but others can be present in the type specifiers even though they
Chris Lattnerfca0ddd2008-06-26 06:27:57 +00003935 // apply to the decl. Here we apply type attributes and ignore the rest.
John McCall711c52b2011-01-05 12:14:39 +00003936
3937 AttributeList *next;
3938 do {
3939 AttributeList &attr = *attrs;
3940 next = attr.getNext();
3941
Abramo Bagnarae215f722010-04-30 13:10:51 +00003942 // Skip attributes that were marked to be invalid.
John McCall711c52b2011-01-05 12:14:39 +00003943 if (attr.isInvalid())
Abramo Bagnarae215f722010-04-30 13:10:51 +00003944 continue;
3945
Abramo Bagnarab1f1b262010-04-30 09:13:03 +00003946 // If this is an attribute we can handle, do so now,
3947 // otherwise, add it to the FnAttrs list for rechaining.
John McCall711c52b2011-01-05 12:14:39 +00003948 switch (attr.getKind()) {
Chris Lattner232e8822008-02-21 01:08:11 +00003949 default: break;
John McCall04a67a62010-02-05 21:31:56 +00003950
Chandler Carruth682eae22011-10-07 18:40:27 +00003951 case AttributeList::AT_may_alias:
3952 // FIXME: This attribute needs to actually be handled, but if we ignore
3953 // it it breaks large amounts of Linux software.
3954 attr.setUsedAsTypeAttr();
3955 break;
Chris Lattner232e8822008-02-21 01:08:11 +00003956 case AttributeList::AT_address_space:
John McCall711c52b2011-01-05 12:14:39 +00003957 HandleAddressSpaceTypeAttribute(type, attr, state.getSema());
John McCalle82247a2011-10-01 05:17:03 +00003958 attr.setUsedAsTypeAttr();
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003959 break;
John McCall711c52b2011-01-05 12:14:39 +00003960 OBJC_POINTER_TYPE_ATTRS_CASELIST:
3961 if (!handleObjCPointerTypeAttr(state, attr, type))
3962 distributeObjCPointerTypeAttr(state, attr, type);
John McCalle82247a2011-10-01 05:17:03 +00003963 attr.setUsedAsTypeAttr();
Mike Stump24556362009-07-25 21:26:53 +00003964 break;
John Thompson6e132aa2009-12-04 21:51:28 +00003965 case AttributeList::AT_vector_size:
John McCall711c52b2011-01-05 12:14:39 +00003966 HandleVectorSizeAttr(type, attr, state.getSema());
John McCalle82247a2011-10-01 05:17:03 +00003967 attr.setUsedAsTypeAttr();
John McCall04a67a62010-02-05 21:31:56 +00003968 break;
Douglas Gregor4ac01402011-06-15 16:02:29 +00003969 case AttributeList::AT_ext_vector_type:
3970 if (state.getDeclarator().getDeclSpec().getStorageClassSpec()
3971 != DeclSpec::SCS_typedef)
3972 HandleExtVectorTypeAttr(type, attr, state.getSema());
John McCalle82247a2011-10-01 05:17:03 +00003973 attr.setUsedAsTypeAttr();
Douglas Gregor4ac01402011-06-15 16:02:29 +00003974 break;
Bob Wilson4211bb62010-11-16 00:32:24 +00003975 case AttributeList::AT_neon_vector_type:
John McCall711c52b2011-01-05 12:14:39 +00003976 HandleNeonVectorTypeAttr(type, attr, state.getSema(),
3977 VectorType::NeonVector, "neon_vector_type");
John McCalle82247a2011-10-01 05:17:03 +00003978 attr.setUsedAsTypeAttr();
Bob Wilson4211bb62010-11-16 00:32:24 +00003979 break;
3980 case AttributeList::AT_neon_polyvector_type:
John McCall711c52b2011-01-05 12:14:39 +00003981 HandleNeonVectorTypeAttr(type, attr, state.getSema(),
3982 VectorType::NeonPolyVector,
Bob Wilson4211bb62010-11-16 00:32:24 +00003983 "neon_polyvector_type");
John McCalle82247a2011-10-01 05:17:03 +00003984 attr.setUsedAsTypeAttr();
Bob Wilson4211bb62010-11-16 00:32:24 +00003985 break;
Peter Collingbourne207f4d82011-03-18 22:38:29 +00003986 case AttributeList::AT_opencl_image_access:
3987 HandleOpenCLImageAccessAttribute(type, attr, state.getSema());
John McCalle82247a2011-10-01 05:17:03 +00003988 attr.setUsedAsTypeAttr();
Peter Collingbourne207f4d82011-03-18 22:38:29 +00003989 break;
3990
John McCallf85e1932011-06-15 23:02:42 +00003991 case AttributeList::AT_ns_returns_retained:
David Blaikie4e4d0842012-03-11 07:00:24 +00003992 if (!state.getSema().getLangOpts().ObjCAutoRefCount)
John McCallf85e1932011-06-15 23:02:42 +00003993 break;
3994 // fallthrough into the function attrs
3995
John McCall711c52b2011-01-05 12:14:39 +00003996 FUNCTION_TYPE_ATTRS_CASELIST:
John McCalle82247a2011-10-01 05:17:03 +00003997 attr.setUsedAsTypeAttr();
3998
John McCall711c52b2011-01-05 12:14:39 +00003999 // Never process function type attributes as part of the
4000 // declaration-specifiers.
4001 if (isDeclSpec)
4002 distributeFunctionTypeAttrFromDeclSpec(state, attr, type);
4003
4004 // Otherwise, handle the possible delays.
4005 else if (!handleFunctionTypeAttr(state, attr, type))
4006 distributeFunctionTypeAttr(state, attr, type);
John Thompson6e132aa2009-12-04 21:51:28 +00004007 break;
Chris Lattner232e8822008-02-21 01:08:11 +00004008 }
John McCall711c52b2011-01-05 12:14:39 +00004009 } while ((attrs = next));
Chris Lattner232e8822008-02-21 01:08:11 +00004010}
4011
Chandler Carruthe4d645c2011-05-27 01:33:31 +00004012/// \brief Ensure that the type of the given expression is complete.
4013///
4014/// This routine checks whether the expression \p E has a complete type. If the
4015/// expression refers to an instantiable construct, that instantiation is
4016/// performed as needed to complete its type. Furthermore
4017/// Sema::RequireCompleteType is called for the expression's type (or in the
4018/// case of a reference type, the referred-to type).
4019///
4020/// \param E The expression whose type is required to be complete.
4021/// \param PD The partial diagnostic that will be printed out if the type cannot
4022/// be completed.
4023///
4024/// \returns \c true if the type of \p E is incomplete and diagnosed, \c false
4025/// otherwise.
4026bool Sema::RequireCompleteExprType(Expr *E, const PartialDiagnostic &PD,
4027 std::pair<SourceLocation,
4028 PartialDiagnostic> Note) {
4029 QualType T = E->getType();
4030
4031 // Fast path the case where the type is already complete.
4032 if (!T->isIncompleteType())
4033 return false;
4034
4035 // Incomplete array types may be completed by the initializer attached to
4036 // their definitions. For static data members of class templates we need to
4037 // instantiate the definition to get this initializer and complete the type.
4038 if (T->isIncompleteArrayType()) {
4039 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4040 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
4041 if (Var->isStaticDataMember() &&
4042 Var->getInstantiatedFromStaticDataMember()) {
Douglas Gregor36f255c2011-06-03 14:28:43 +00004043
4044 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
4045 assert(MSInfo && "Missing member specialization information?");
4046 if (MSInfo->getTemplateSpecializationKind()
4047 != TSK_ExplicitSpecialization) {
4048 // If we don't already have a point of instantiation, this is it.
4049 if (MSInfo->getPointOfInstantiation().isInvalid()) {
4050 MSInfo->setPointOfInstantiation(E->getLocStart());
4051
4052 // This is a modification of an existing AST node. Notify
4053 // listeners.
4054 if (ASTMutationListener *L = getASTMutationListener())
4055 L->StaticDataMemberInstantiated(Var);
4056 }
4057
4058 InstantiateStaticDataMemberDefinition(E->getExprLoc(), Var);
4059
4060 // Update the type to the newly instantiated definition's type both
4061 // here and within the expression.
4062 if (VarDecl *Def = Var->getDefinition()) {
4063 DRE->setDecl(Def);
4064 T = Def->getType();
4065 DRE->setType(T);
4066 E->setType(T);
4067 }
Douglas Gregorf15748a2011-06-03 03:35:07 +00004068 }
4069
Chandler Carruthe4d645c2011-05-27 01:33:31 +00004070 // We still go on to try to complete the type independently, as it
4071 // may also require instantiations or diagnostics if it remains
4072 // incomplete.
4073 }
4074 }
4075 }
4076 }
4077
4078 // FIXME: Are there other cases which require instantiating something other
4079 // than the type to complete the type of an expression?
4080
4081 // Look through reference types and complete the referred type.
4082 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
4083 T = Ref->getPointeeType();
4084
4085 return RequireCompleteType(E->getExprLoc(), T, PD, Note);
4086}
4087
Mike Stump1eb44332009-09-09 15:08:12 +00004088/// @brief Ensure that the type T is a complete type.
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004089///
4090/// This routine checks whether the type @p T is complete in any
4091/// context where a complete type is required. If @p T is a complete
Douglas Gregor86447ec2009-03-09 16:13:40 +00004092/// type, returns false. If @p T is a class template specialization,
4093/// this routine then attempts to perform class template
4094/// instantiation. If instantiation fails, or if @p T is incomplete
4095/// and cannot be completed, issues the diagnostic @p diag (giving it
4096/// the type @p T) and returns true.
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004097///
4098/// @param Loc The location in the source that the incomplete type
4099/// diagnostic should refer to.
4100///
4101/// @param T The type that this routine is examining for completeness.
4102///
Mike Stump1eb44332009-09-09 15:08:12 +00004103/// @param PD The partial diagnostic that will be printed out if T is not a
Anders Carlssonb7906612009-08-26 23:45:07 +00004104/// complete type.
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004105///
4106/// @returns @c true if @p T is incomplete and a diagnostic was emitted,
4107/// @c false otherwise.
Anders Carlsson91a0cc92009-08-26 22:33:56 +00004108bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
Anders Carlsson8c8d9192009-10-09 23:51:55 +00004109 const PartialDiagnostic &PD,
4110 std::pair<SourceLocation,
4111 PartialDiagnostic> Note) {
Anders Carlsson91a0cc92009-08-26 22:33:56 +00004112 unsigned diag = PD.getDiagID();
Mike Stump1eb44332009-09-09 15:08:12 +00004113
Douglas Gregor573d9c32009-10-21 23:19:44 +00004114 // FIXME: Add this assertion to make sure we always get instantiation points.
4115 // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
Douglas Gregor690dc7f2009-05-21 23:48:18 +00004116 // FIXME: Add this assertion to help us flush out problems with
4117 // checking for dependent types and type-dependent expressions.
4118 //
Mike Stump1eb44332009-09-09 15:08:12 +00004119 // assert(!T->isDependentType() &&
Douglas Gregor690dc7f2009-05-21 23:48:18 +00004120 // "Can't ask whether a dependent type is complete");
4121
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004122 // If we have a complete type, we're done.
Douglas Gregord07cc362012-01-02 17:18:37 +00004123 NamedDecl *Def = 0;
4124 if (!T->isIncompleteType(&Def)) {
4125 // If we know about the definition but it is not visible, complain.
4126 if (diag != 0 && Def && !LookupResult::isVisible(Def)) {
4127 // Suppress this error outside of a SFINAE context if we've already
4128 // emitted the error once for this type. There's no usefulness in
4129 // repeating the diagnostic.
4130 // FIXME: Add a Fix-It that imports the corresponding module or includes
4131 // the header.
4132 if (isSFINAEContext() || HiddenDefinitions.insert(Def)) {
4133 Diag(Loc, diag::err_module_private_definition) << T;
4134 Diag(Def->getLocation(), diag::note_previous_definition);
4135 }
4136 }
4137
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004138 return false;
Douglas Gregord07cc362012-01-02 17:18:37 +00004139 }
Eli Friedman3c0eb162008-05-27 03:33:27 +00004140
Sean Callananbd791192011-12-16 00:20:31 +00004141 const TagType *Tag = T->getAs<TagType>();
4142 const ObjCInterfaceType *IFace = 0;
4143
4144 if (Tag) {
4145 // Avoid diagnosing invalid decls as incomplete.
4146 if (Tag->getDecl()->isInvalidDecl())
4147 return true;
4148
4149 // Give the external AST source a chance to complete the type.
4150 if (Tag->getDecl()->hasExternalLexicalStorage()) {
4151 Context.getExternalSource()->CompleteType(Tag->getDecl());
4152 if (!Tag->isIncompleteType())
4153 return false;
4154 }
4155 }
4156 else if ((IFace = T->getAs<ObjCInterfaceType>())) {
4157 // Avoid diagnosing invalid decls as incomplete.
4158 if (IFace->getDecl()->isInvalidDecl())
4159 return true;
4160
4161 // Give the external AST source a chance to complete the type.
4162 if (IFace->getDecl()->hasExternalLexicalStorage()) {
4163 Context.getExternalSource()->CompleteType(IFace->getDecl());
4164 if (!IFace->isIncompleteType())
4165 return false;
4166 }
4167 }
4168
Douglas Gregord475b8d2009-03-25 21:17:03 +00004169 // If we have a class template specialization or a class member of a
Sebastian Redl923d56d2009-11-05 15:52:31 +00004170 // class template specialization, or an array with known size of such,
4171 // try to instantiate it.
4172 QualType MaybeTemplate = T;
Douglas Gregor89c49f02009-11-09 22:08:55 +00004173 if (const ConstantArrayType *Array = Context.getAsConstantArrayType(T))
Sebastian Redl923d56d2009-11-05 15:52:31 +00004174 MaybeTemplate = Array->getElementType();
4175 if (const RecordType *Record = MaybeTemplate->getAs<RecordType>()) {
Douglas Gregor2943aed2009-03-03 04:44:36 +00004176 if (ClassTemplateSpecializationDecl *ClassTemplateSpec
Douglas Gregord475b8d2009-03-25 21:17:03 +00004177 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
Douglas Gregor972e6ce2009-10-27 06:26:26 +00004178 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared)
4179 return InstantiateClassTemplateSpecialization(Loc, ClassTemplateSpec,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00004180 TSK_ImplicitInstantiation,
Douglas Gregor5842ba92009-08-24 15:23:48 +00004181 /*Complain=*/diag != 0);
Mike Stump1eb44332009-09-09 15:08:12 +00004182 } else if (CXXRecordDecl *Rec
Douglas Gregord475b8d2009-03-25 21:17:03 +00004183 = dyn_cast<CXXRecordDecl>(Record->getDecl())) {
4184 if (CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass()) {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004185 MemberSpecializationInfo *MSInfo = Rec->getMemberSpecializationInfo();
4186 assert(MSInfo && "Missing member specialization information?");
Douglas Gregor357bbd02009-08-28 20:50:45 +00004187 // This record was instantiated from a class within a template.
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004188 if (MSInfo->getTemplateSpecializationKind()
Douglas Gregor972e6ce2009-10-27 06:26:26 +00004189 != TSK_ExplicitSpecialization)
Douglas Gregorf6b11852009-10-08 15:14:33 +00004190 return InstantiateClass(Loc, Rec, Pattern,
4191 getTemplateInstantiationArgs(Rec),
4192 TSK_ImplicitInstantiation,
4193 /*Complain=*/diag != 0);
Douglas Gregord475b8d2009-03-25 21:17:03 +00004194 }
4195 }
4196 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00004197
Douglas Gregor5842ba92009-08-24 15:23:48 +00004198 if (diag == 0)
4199 return true;
Douglas Gregorb3029962011-11-14 22:10:01 +00004200
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004201 // We have an incomplete type. Produce a diagnostic.
Anders Carlsson91a0cc92009-08-26 22:33:56 +00004202 Diag(Loc, PD) << T;
Douglas Gregorb3029962011-11-14 22:10:01 +00004203
Anders Carlsson8c8d9192009-10-09 23:51:55 +00004204 // If we have a note, produce it.
4205 if (!Note.first.isInvalid())
4206 Diag(Note.first, Note.second);
4207
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004208 // If the type was a forward declaration of a class/struct/union
Rafael Espindola01620702010-03-21 22:56:43 +00004209 // type, produce a note.
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004210 if (Tag && !Tag->getDecl()->isInvalidDecl())
Mike Stump1eb44332009-09-09 15:08:12 +00004211 Diag(Tag->getDecl()->getLocation(),
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004212 Tag->isBeingDefined() ? diag::note_type_being_defined
4213 : diag::note_forward_declaration)
Douglas Gregorb3029962011-11-14 22:10:01 +00004214 << QualType(Tag, 0);
4215
4216 // If the Objective-C class was a forward declaration, produce a note.
4217 if (IFace && !IFace->getDecl()->isInvalidDecl())
4218 Diag(IFace->getDecl()->getLocation(), diag::note_forward_class);
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004219
4220 return true;
4221}
Douglas Gregore6258932009-03-19 00:39:20 +00004222
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004223bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
4224 const PartialDiagnostic &PD) {
4225 return RequireCompleteType(Loc, T, PD,
4226 std::make_pair(SourceLocation(), PDiag(0)));
4227}
4228
4229bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
4230 unsigned DiagID) {
4231 return RequireCompleteType(Loc, T, PDiag(DiagID),
4232 std::make_pair(SourceLocation(), PDiag(0)));
4233}
4234
Richard Smith9f569cc2011-10-01 02:31:28 +00004235/// @brief Ensure that the type T is a literal type.
4236///
4237/// This routine checks whether the type @p T is a literal type. If @p T is an
4238/// incomplete type, an attempt is made to complete it. If @p T is a literal
4239/// type, or @p AllowIncompleteType is true and @p T is an incomplete type,
4240/// returns false. Otherwise, this routine issues the diagnostic @p PD (giving
4241/// it the type @p T), along with notes explaining why the type is not a
4242/// literal type, and returns true.
4243///
4244/// @param Loc The location in the source that the non-literal type
4245/// diagnostic should refer to.
4246///
4247/// @param T The type that this routine is examining for literalness.
4248///
4249/// @param PD The partial diagnostic that will be printed out if T is not a
4250/// literal type.
4251///
Richard Smith9f569cc2011-10-01 02:31:28 +00004252/// @returns @c true if @p T is not a literal type and a diagnostic was emitted,
4253/// @c false otherwise.
4254bool Sema::RequireLiteralType(SourceLocation Loc, QualType T,
Richard Smith86c3ae42012-02-13 03:54:03 +00004255 const PartialDiagnostic &PD) {
Richard Smith9f569cc2011-10-01 02:31:28 +00004256 assert(!T->isDependentType() && "type should not be dependent");
4257
Eli Friedmanee065392012-02-20 23:58:14 +00004258 QualType ElemType = Context.getBaseElementType(T);
4259 RequireCompleteType(Loc, ElemType, 0);
4260
Richard Smith86c3ae42012-02-13 03:54:03 +00004261 if (T->isLiteralType())
Richard Smith9f569cc2011-10-01 02:31:28 +00004262 return false;
4263
4264 if (PD.getDiagID() == 0)
4265 return true;
4266
4267 Diag(Loc, PD) << T;
4268
4269 if (T->isVariableArrayType())
4270 return true;
4271
Eli Friedmanee065392012-02-20 23:58:14 +00004272 const RecordType *RT = ElemType->getAs<RecordType>();
Richard Smith9f569cc2011-10-01 02:31:28 +00004273 if (!RT)
4274 return true;
4275
4276 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4277
Eli Friedmanee065392012-02-20 23:58:14 +00004278 // FIXME: Better diagnostic for incomplete class?
4279 if (!RD->isCompleteDefinition())
4280 return true;
4281
Richard Smith9f569cc2011-10-01 02:31:28 +00004282 // If the class has virtual base classes, then it's not an aggregate, and
Richard Smith86c3ae42012-02-13 03:54:03 +00004283 // cannot have any constexpr constructors or a trivial default constructor,
4284 // so is non-literal. This is better to diagnose than the resulting absence
4285 // of constexpr constructors.
Richard Smith9f569cc2011-10-01 02:31:28 +00004286 if (RD->getNumVBases()) {
4287 Diag(RD->getLocation(), diag::note_non_literal_virtual_base)
4288 << RD->isStruct() << RD->getNumVBases();
4289 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
4290 E = RD->vbases_end(); I != E; ++I)
Daniel Dunbar96a00142012-03-09 18:35:03 +00004291 Diag(I->getLocStart(),
Richard Smith9f569cc2011-10-01 02:31:28 +00004292 diag::note_constexpr_virtual_base_here) << I->getSourceRange();
Richard Smith86c3ae42012-02-13 03:54:03 +00004293 } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() &&
4294 !RD->hasTrivialDefaultConstructor()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00004295 Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD;
Richard Smith9f569cc2011-10-01 02:31:28 +00004296 } else if (RD->hasNonLiteralTypeFieldsOrBases()) {
4297 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4298 E = RD->bases_end(); I != E; ++I) {
4299 if (!I->getType()->isLiteralType()) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00004300 Diag(I->getLocStart(),
Richard Smith9f569cc2011-10-01 02:31:28 +00004301 diag::note_non_literal_base_class)
4302 << RD << I->getType() << I->getSourceRange();
4303 return true;
4304 }
4305 }
4306 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
4307 E = RD->field_end(); I != E; ++I) {
Richard Smith86c3ae42012-02-13 03:54:03 +00004308 if (!(*I)->getType()->isLiteralType() ||
4309 (*I)->getType().isVolatileQualified()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00004310 Diag((*I)->getLocation(), diag::note_non_literal_field)
Richard Smith86c3ae42012-02-13 03:54:03 +00004311 << RD << (*I) << (*I)->getType()
4312 << (*I)->getType().isVolatileQualified();
Richard Smith9f569cc2011-10-01 02:31:28 +00004313 return true;
4314 }
4315 }
4316 } else if (!RD->hasTrivialDestructor()) {
4317 // All fields and bases are of literal types, so have trivial destructors.
4318 // If this class's destructor is non-trivial it must be user-declared.
4319 CXXDestructorDecl *Dtor = RD->getDestructor();
4320 assert(Dtor && "class has literal fields and bases but no dtor?");
4321 if (!Dtor)
4322 return true;
4323
4324 Diag(Dtor->getLocation(), Dtor->isUserProvided() ?
4325 diag::note_non_literal_user_provided_dtor :
4326 diag::note_non_literal_nontrivial_dtor) << RD;
4327 }
4328
4329 return true;
4330}
4331
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004332/// \brief Retrieve a version of the type 'T' that is elaborated by Keyword
4333/// and qualified by the nested-name-specifier contained in SS.
4334QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword,
4335 const CXXScopeSpec &SS, QualType T) {
4336 if (T.isNull())
Douglas Gregore6258932009-03-19 00:39:20 +00004337 return T;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004338 NestedNameSpecifier *NNS;
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00004339 if (SS.isValid())
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004340 NNS = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4341 else {
4342 if (Keyword == ETK_None)
4343 return T;
4344 NNS = 0;
4345 }
4346 return Context.getElaboratedType(Keyword, NNS, T);
Douglas Gregore6258932009-03-19 00:39:20 +00004347}
Anders Carlssonaf017e62009-06-29 22:58:55 +00004348
John McCall2a984ca2010-10-12 00:20:44 +00004349QualType Sema::BuildTypeofExprType(Expr *E, SourceLocation Loc) {
John McCallfb8721c2011-04-10 19:13:55 +00004350 ExprResult ER = CheckPlaceholderExpr(E);
John McCall2a984ca2010-10-12 00:20:44 +00004351 if (ER.isInvalid()) return QualType();
4352 E = ER.take();
4353
Fariborz Jahanian2b1d51b2010-10-05 23:24:00 +00004354 if (!E->isTypeDependent()) {
4355 QualType T = E->getType();
Fariborz Jahanianaca7f7b2010-10-06 00:23:25 +00004356 if (const TagType *TT = T->getAs<TagType>())
4357 DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc());
Fariborz Jahanian2b1d51b2010-10-05 23:24:00 +00004358 }
Anders Carlssonaf017e62009-06-29 22:58:55 +00004359 return Context.getTypeOfExprType(E);
4360}
4361
Douglas Gregorf8af9822012-02-12 18:42:33 +00004362/// getDecltypeForExpr - Given an expr, will return the decltype for
4363/// that expression, according to the rules in C++11
4364/// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18.
4365static QualType getDecltypeForExpr(Sema &S, Expr *E) {
4366 if (E->isTypeDependent())
4367 return S.Context.DependentTy;
4368
Douglas Gregor6d9ef302012-02-12 18:57:57 +00004369 // C++11 [dcl.type.simple]p4:
4370 // The type denoted by decltype(e) is defined as follows:
4371 //
4372 // - if e is an unparenthesized id-expression or an unparenthesized class
4373 // member access (5.2.5), decltype(e) is the type of the entity named
4374 // by e. If there is no such entity, or if e names a set of overloaded
4375 // functions, the program is ill-formed;
Douglas Gregorf8af9822012-02-12 18:42:33 +00004376 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
4377 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
4378 return VD->getType();
4379 }
4380 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
4381 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
4382 return FD->getType();
4383 }
Douglas Gregor6d9ef302012-02-12 18:57:57 +00004384
Douglas Gregorf8af9822012-02-12 18:42:33 +00004385 // C++11 [expr.lambda.prim]p18:
4386 // Every occurrence of decltype((x)) where x is a possibly
4387 // parenthesized id-expression that names an entity of automatic
4388 // storage duration is treated as if x were transformed into an
4389 // access to a corresponding data member of the closure type that
4390 // would have been declared if x were an odr-use of the denoted
4391 // entity.
4392 using namespace sema;
4393 if (S.getCurLambda()) {
4394 if (isa<ParenExpr>(E)) {
4395 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4396 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
Douglas Gregor68932842012-02-18 05:51:20 +00004397 QualType T = S.getCapturedDeclRefType(Var, DRE->getLocation());
4398 if (!T.isNull())
4399 return S.Context.getLValueReferenceType(T);
Douglas Gregorf8af9822012-02-12 18:42:33 +00004400 }
4401 }
4402 }
4403 }
4404
Douglas Gregor6d9ef302012-02-12 18:57:57 +00004405
4406 // C++11 [dcl.type.simple]p4:
4407 // [...]
Douglas Gregorf8af9822012-02-12 18:42:33 +00004408 QualType T = E->getType();
Douglas Gregor6d9ef302012-02-12 18:57:57 +00004409 switch (E->getValueKind()) {
4410 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
4411 // type of e;
4412 case VK_XValue: T = S.Context.getRValueReferenceType(T); break;
4413 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
4414 // type of e;
4415 case VK_LValue: T = S.Context.getLValueReferenceType(T); break;
4416 // - otherwise, decltype(e) is the type of e.
4417 case VK_RValue: break;
4418 }
4419
Douglas Gregorf8af9822012-02-12 18:42:33 +00004420 return T;
4421}
4422
John McCall2a984ca2010-10-12 00:20:44 +00004423QualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc) {
John McCallfb8721c2011-04-10 19:13:55 +00004424 ExprResult ER = CheckPlaceholderExpr(E);
John McCall2a984ca2010-10-12 00:20:44 +00004425 if (ER.isInvalid()) return QualType();
4426 E = ER.take();
Douglas Gregor4b52e252009-12-21 23:17:24 +00004427
Douglas Gregorf8af9822012-02-12 18:42:33 +00004428 return Context.getDecltypeType(E, getDecltypeForExpr(*this, E));
Anders Carlssonaf017e62009-06-29 22:58:55 +00004429}
Sean Huntca63c202011-05-24 22:41:36 +00004430
4431QualType Sema::BuildUnaryTransformType(QualType BaseType,
4432 UnaryTransformType::UTTKind UKind,
4433 SourceLocation Loc) {
4434 switch (UKind) {
4435 case UnaryTransformType::EnumUnderlyingType:
4436 if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) {
4437 Diag(Loc, diag::err_only_enums_have_underlying_types);
4438 return QualType();
4439 } else {
4440 QualType Underlying = BaseType;
4441 if (!BaseType->isDependentType()) {
4442 EnumDecl *ED = BaseType->getAs<EnumType>()->getDecl();
4443 assert(ED && "EnumType has no EnumDecl");
4444 DiagnoseUseOfDecl(ED, Loc);
4445 Underlying = ED->getIntegerType();
4446 }
4447 assert(!Underlying.isNull());
4448 return Context.getUnaryTransformType(BaseType, Underlying,
4449 UnaryTransformType::EnumUnderlyingType);
4450 }
4451 }
4452 llvm_unreachable("unknown unary transform type");
4453}
Eli Friedmanb001de72011-10-06 23:00:33 +00004454
4455QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) {
4456 if (!T->isDependentType()) {
Richard Smith83271182012-02-11 18:03:45 +00004457 // FIXME: It isn't entirely clear whether incomplete atomic types
4458 // are allowed or not; for simplicity, ban them for the moment.
4459 if (RequireCompleteType(Loc, T,
4460 PDiag(diag::err_atomic_specifier_bad_type) << 0))
4461 return QualType();
4462
Eli Friedmanb001de72011-10-06 23:00:33 +00004463 int DisallowedKind = -1;
Richard Smith83271182012-02-11 18:03:45 +00004464 if (T->isArrayType())
Eli Friedmanb001de72011-10-06 23:00:33 +00004465 DisallowedKind = 1;
4466 else if (T->isFunctionType())
4467 DisallowedKind = 2;
4468 else if (T->isReferenceType())
4469 DisallowedKind = 3;
4470 else if (T->isAtomicType())
4471 DisallowedKind = 4;
4472 else if (T.hasQualifiers())
4473 DisallowedKind = 5;
4474 else if (!T.isTriviallyCopyableType(Context))
4475 // Some other non-trivially-copyable type (probably a C++ class)
4476 DisallowedKind = 6;
4477
4478 if (DisallowedKind != -1) {
4479 Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T;
4480 return QualType();
4481 }
4482
4483 // FIXME: Do we need any handling for ARC here?
4484 }
4485
4486 // Build the pointer type.
4487 return Context.getAtomicType(T);
4488}