blob: 6b98ed872175200624d12837b3148d27646a06cd [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaType.cpp - Semantic Analysis for Types -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements type-related semantic analysis.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
John McCall7cd088e2010-08-24 07:21:54 +000015#include "clang/Sema/Template.h"
Peter Collingbourne207f4d82011-03-18 22:38:29 +000016#include "clang/Basic/OpenCL.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000017#include "clang/AST/ASTContext.h"
Douglas Gregor36f255c2011-06-03 14:28:43 +000018#include "clang/AST/ASTMutationListener.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000019#include "clang/AST/CXXInheritance.h"
Steve Naroff980e5082007-10-01 19:00:59 +000020#include "clang/AST/DeclObjC.h"
Douglas Gregor2943aed2009-03-03 04:44:36 +000021#include "clang/AST/DeclTemplate.h"
Argyrios Kyrtzidis4adab7f2009-08-19 01:28:06 +000022#include "clang/AST/TypeLoc.h"
John McCall51bd8032009-10-18 01:05:36 +000023#include "clang/AST/TypeLocVisitor.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000024#include "clang/AST/Expr.h"
Anders Carlsson91a0cc92009-08-26 22:33:56 +000025#include "clang/Basic/PartialDiagnostic.h"
Charles Davisd18f9f92010-08-16 04:01:50 +000026#include "clang/Basic/TargetInfo.h"
John McCall2792fa52011-03-08 04:17:03 +000027#include "clang/Lex/Preprocessor.h"
John McCall19510852010-08-20 18:27:03 +000028#include "clang/Sema/DeclSpec.h"
John McCallf85e1932011-06-15 23:02:42 +000029#include "clang/Sema/DelayedDiagnostic.h"
Sebastian Redl4994d2d2009-07-04 11:39:00 +000030#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor87c12c42009-11-04 16:49:01 +000031#include "llvm/Support/ErrorHandling.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000032using namespace clang;
33
Chris Lattner5db2bb12009-10-25 18:21:37 +000034/// isOmittedBlockReturnType - Return true if this declarator is missing a
35/// return type because this is a omitted return type on a block literal.
Sebastian Redl8ce35b02009-10-25 21:45:37 +000036static bool isOmittedBlockReturnType(const Declarator &D) {
Chris Lattner5db2bb12009-10-25 18:21:37 +000037 if (D.getContext() != Declarator::BlockLiteralContext ||
Sebastian Redl8ce35b02009-10-25 21:45:37 +000038 D.getDeclSpec().hasTypeSpecifier())
Chris Lattner5db2bb12009-10-25 18:21:37 +000039 return false;
40
41 if (D.getNumTypeObjects() == 0)
Chris Lattnera64ef0a2009-10-25 22:09:09 +000042 return true; // ^{ ... }
Chris Lattner5db2bb12009-10-25 18:21:37 +000043
44 if (D.getNumTypeObjects() == 1 &&
45 D.getTypeObject(0).Kind == DeclaratorChunk::Function)
Chris Lattnera64ef0a2009-10-25 22:09:09 +000046 return true; // ^(int X, float Y) { ... }
Chris Lattner5db2bb12009-10-25 18:21:37 +000047
48 return false;
49}
50
John McCall2792fa52011-03-08 04:17:03 +000051/// diagnoseBadTypeAttribute - Diagnoses a type attribute which
52/// doesn't apply to the given type.
53static void diagnoseBadTypeAttribute(Sema &S, const AttributeList &attr,
54 QualType type) {
Chandler Carruth108f7562011-07-26 05:40:03 +000055 bool useExpansionLoc = false;
John McCall2792fa52011-03-08 04:17:03 +000056
57 unsigned diagID = 0;
58 switch (attr.getKind()) {
59 case AttributeList::AT_objc_gc:
60 diagID = diag::warn_pointer_attribute_wrong_type;
Chandler Carruth108f7562011-07-26 05:40:03 +000061 useExpansionLoc = true;
John McCall2792fa52011-03-08 04:17:03 +000062 break;
63
Argyrios Kyrtzidis05d48762011-07-01 22:23:09 +000064 case AttributeList::AT_objc_ownership:
65 diagID = diag::warn_objc_object_attribute_wrong_type;
Chandler Carruth108f7562011-07-26 05:40:03 +000066 useExpansionLoc = true;
Argyrios Kyrtzidis05d48762011-07-01 22:23:09 +000067 break;
68
John McCall2792fa52011-03-08 04:17:03 +000069 default:
70 // Assume everything else was a function attribute.
71 diagID = diag::warn_function_attribute_wrong_type;
72 break;
73 }
74
75 SourceLocation loc = attr.getLoc();
Chris Lattner5f9e2722011-07-23 10:55:15 +000076 StringRef name = attr.getName()->getName();
John McCall2792fa52011-03-08 04:17:03 +000077
78 // The GC attributes are usually written with macros; special-case them.
Chandler Carruth108f7562011-07-26 05:40:03 +000079 if (useExpansionLoc && loc.isMacroID() && attr.getParameterName()) {
John McCall834e3f62011-03-08 07:59:04 +000080 if (attr.getParameterName()->isStr("strong")) {
81 if (S.findMacroSpelling(loc, "__strong")) name = "__strong";
82 } else if (attr.getParameterName()->isStr("weak")) {
83 if (S.findMacroSpelling(loc, "__weak")) name = "__weak";
John McCall2792fa52011-03-08 04:17:03 +000084 }
85 }
86
87 S.Diag(loc, diagID) << name << type;
88}
89
John McCall711c52b2011-01-05 12:14:39 +000090// objc_gc applies to Objective-C pointers or, otherwise, to the
91// smallest available pointer type (i.e. 'void*' in 'void**').
92#define OBJC_POINTER_TYPE_ATTRS_CASELIST \
John McCallf85e1932011-06-15 23:02:42 +000093 case AttributeList::AT_objc_gc: \
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +000094 case AttributeList::AT_objc_ownership
John McCall04a67a62010-02-05 21:31:56 +000095
John McCall711c52b2011-01-05 12:14:39 +000096// Function type attributes.
97#define FUNCTION_TYPE_ATTRS_CASELIST \
98 case AttributeList::AT_noreturn: \
99 case AttributeList::AT_cdecl: \
100 case AttributeList::AT_fastcall: \
101 case AttributeList::AT_stdcall: \
102 case AttributeList::AT_thiscall: \
103 case AttributeList::AT_pascal: \
Anton Korobeynikov414d8962011-04-14 20:06:49 +0000104 case AttributeList::AT_regparm: \
105 case AttributeList::AT_pcs \
John McCall04a67a62010-02-05 21:31:56 +0000106
John McCall711c52b2011-01-05 12:14:39 +0000107namespace {
108 /// An object which stores processing state for the entire
109 /// GetTypeForDeclarator process.
110 class TypeProcessingState {
111 Sema &sema;
112
113 /// The declarator being processed.
114 Declarator &declarator;
115
116 /// The index of the declarator chunk we're currently processing.
117 /// May be the total number of valid chunks, indicating the
118 /// DeclSpec.
119 unsigned chunkIndex;
120
121 /// Whether there are non-trivial modifications to the decl spec.
122 bool trivial;
123
John McCall7ea21932011-03-26 01:39:56 +0000124 /// Whether we saved the attributes in the decl spec.
125 bool hasSavedAttrs;
126
John McCall711c52b2011-01-05 12:14:39 +0000127 /// The original set of attributes on the DeclSpec.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000128 SmallVector<AttributeList*, 2> savedAttrs;
John McCall711c52b2011-01-05 12:14:39 +0000129
130 /// A list of attributes to diagnose the uselessness of when the
131 /// processing is complete.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000132 SmallVector<AttributeList*, 2> ignoredTypeAttrs;
John McCall711c52b2011-01-05 12:14:39 +0000133
134 public:
135 TypeProcessingState(Sema &sema, Declarator &declarator)
136 : sema(sema), declarator(declarator),
137 chunkIndex(declarator.getNumTypeObjects()),
John McCall7ea21932011-03-26 01:39:56 +0000138 trivial(true), hasSavedAttrs(false) {}
John McCall711c52b2011-01-05 12:14:39 +0000139
140 Sema &getSema() const {
141 return sema;
Abramo Bagnarae215f722010-04-30 13:10:51 +0000142 }
John McCall711c52b2011-01-05 12:14:39 +0000143
144 Declarator &getDeclarator() const {
145 return declarator;
146 }
147
148 unsigned getCurrentChunkIndex() const {
149 return chunkIndex;
150 }
151
152 void setCurrentChunkIndex(unsigned idx) {
153 assert(idx <= declarator.getNumTypeObjects());
154 chunkIndex = idx;
155 }
156
157 AttributeList *&getCurrentAttrListRef() const {
158 assert(chunkIndex <= declarator.getNumTypeObjects());
159 if (chunkIndex == declarator.getNumTypeObjects())
160 return getMutableDeclSpec().getAttributes().getListRef();
161 return declarator.getTypeObject(chunkIndex).getAttrListRef();
162 }
163
164 /// Save the current set of attributes on the DeclSpec.
165 void saveDeclSpecAttrs() {
166 // Don't try to save them multiple times.
John McCall7ea21932011-03-26 01:39:56 +0000167 if (hasSavedAttrs) return;
John McCall711c52b2011-01-05 12:14:39 +0000168
169 DeclSpec &spec = getMutableDeclSpec();
170 for (AttributeList *attr = spec.getAttributes().getList(); attr;
171 attr = attr->getNext())
172 savedAttrs.push_back(attr);
173 trivial &= savedAttrs.empty();
John McCall7ea21932011-03-26 01:39:56 +0000174 hasSavedAttrs = true;
John McCall711c52b2011-01-05 12:14:39 +0000175 }
176
177 /// Record that we had nowhere to put the given type attribute.
178 /// We will diagnose such attributes later.
179 void addIgnoredTypeAttr(AttributeList &attr) {
180 ignoredTypeAttrs.push_back(&attr);
181 }
182
183 /// Diagnose all the ignored type attributes, given that the
184 /// declarator worked out to the given type.
185 void diagnoseIgnoredTypeAttrs(QualType type) const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000186 for (SmallVectorImpl<AttributeList*>::const_iterator
John McCall711c52b2011-01-05 12:14:39 +0000187 i = ignoredTypeAttrs.begin(), e = ignoredTypeAttrs.end();
John McCall2792fa52011-03-08 04:17:03 +0000188 i != e; ++i)
189 diagnoseBadTypeAttribute(getSema(), **i, type);
John McCall711c52b2011-01-05 12:14:39 +0000190 }
191
192 ~TypeProcessingState() {
193 if (trivial) return;
194
195 restoreDeclSpecAttrs();
196 }
197
198 private:
199 DeclSpec &getMutableDeclSpec() const {
200 return const_cast<DeclSpec&>(declarator.getDeclSpec());
201 }
202
203 void restoreDeclSpecAttrs() {
John McCall7ea21932011-03-26 01:39:56 +0000204 assert(hasSavedAttrs);
205
206 if (savedAttrs.empty()) {
207 getMutableDeclSpec().getAttributes().set(0);
208 return;
209 }
210
John McCall711c52b2011-01-05 12:14:39 +0000211 getMutableDeclSpec().getAttributes().set(savedAttrs[0]);
212 for (unsigned i = 0, e = savedAttrs.size() - 1; i != e; ++i)
213 savedAttrs[i]->setNext(savedAttrs[i+1]);
214 savedAttrs.back()->setNext(0);
215 }
216 };
217
218 /// Basically std::pair except that we really want to avoid an
219 /// implicit operator= for safety concerns. It's also a minor
220 /// link-time optimization for this to be a private type.
221 struct AttrAndList {
222 /// The attribute.
223 AttributeList &first;
224
225 /// The head of the list the attribute is currently in.
226 AttributeList *&second;
227
228 AttrAndList(AttributeList &attr, AttributeList *&head)
229 : first(attr), second(head) {}
230 };
John McCall04a67a62010-02-05 21:31:56 +0000231}
232
John McCall711c52b2011-01-05 12:14:39 +0000233namespace llvm {
234 template <> struct isPodLike<AttrAndList> {
235 static const bool value = true;
236 };
237}
238
239static void spliceAttrIntoList(AttributeList &attr, AttributeList *&head) {
240 attr.setNext(head);
241 head = &attr;
242}
243
244static void spliceAttrOutOfList(AttributeList &attr, AttributeList *&head) {
245 if (head == &attr) {
246 head = attr.getNext();
247 return;
John McCall04a67a62010-02-05 21:31:56 +0000248 }
John McCall711c52b2011-01-05 12:14:39 +0000249
250 AttributeList *cur = head;
251 while (true) {
252 assert(cur && cur->getNext() && "ran out of attrs?");
253 if (cur->getNext() == &attr) {
254 cur->setNext(attr.getNext());
255 return;
256 }
257 cur = cur->getNext();
258 }
259}
260
261static void moveAttrFromListToList(AttributeList &attr,
262 AttributeList *&fromList,
263 AttributeList *&toList) {
264 spliceAttrOutOfList(attr, fromList);
265 spliceAttrIntoList(attr, toList);
266}
267
268static void processTypeAttrs(TypeProcessingState &state,
269 QualType &type, bool isDeclSpec,
270 AttributeList *attrs);
271
272static bool handleFunctionTypeAttr(TypeProcessingState &state,
273 AttributeList &attr,
274 QualType &type);
275
276static bool handleObjCGCTypeAttr(TypeProcessingState &state,
277 AttributeList &attr, QualType &type);
278
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +0000279static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
John McCallf85e1932011-06-15 23:02:42 +0000280 AttributeList &attr, QualType &type);
281
John McCall711c52b2011-01-05 12:14:39 +0000282static bool handleObjCPointerTypeAttr(TypeProcessingState &state,
283 AttributeList &attr, QualType &type) {
John McCallf85e1932011-06-15 23:02:42 +0000284 if (attr.getKind() == AttributeList::AT_objc_gc)
285 return handleObjCGCTypeAttr(state, attr, type);
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +0000286 assert(attr.getKind() == AttributeList::AT_objc_ownership);
287 return handleObjCOwnershipTypeAttr(state, attr, type);
John McCall711c52b2011-01-05 12:14:39 +0000288}
289
290/// Given that an objc_gc attribute was written somewhere on a
291/// declaration *other* than on the declarator itself (for which, use
292/// distributeObjCPointerTypeAttrFromDeclarator), and given that it
293/// didn't apply in whatever position it was written in, try to move
294/// it to a more appropriate position.
295static void distributeObjCPointerTypeAttr(TypeProcessingState &state,
296 AttributeList &attr,
297 QualType type) {
298 Declarator &declarator = state.getDeclarator();
299 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
300 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
301 switch (chunk.Kind) {
302 case DeclaratorChunk::Pointer:
303 case DeclaratorChunk::BlockPointer:
304 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
305 chunk.getAttrListRef());
306 return;
307
308 case DeclaratorChunk::Paren:
309 case DeclaratorChunk::Array:
310 continue;
311
312 // Don't walk through these.
313 case DeclaratorChunk::Reference:
314 case DeclaratorChunk::Function:
315 case DeclaratorChunk::MemberPointer:
316 goto error;
317 }
318 }
319 error:
John McCall2792fa52011-03-08 04:17:03 +0000320
321 diagnoseBadTypeAttribute(state.getSema(), attr, type);
John McCall711c52b2011-01-05 12:14:39 +0000322}
323
324/// Distribute an objc_gc type attribute that was written on the
325/// declarator.
326static void
327distributeObjCPointerTypeAttrFromDeclarator(TypeProcessingState &state,
328 AttributeList &attr,
329 QualType &declSpecType) {
330 Declarator &declarator = state.getDeclarator();
331
332 // objc_gc goes on the innermost pointer to something that's not a
333 // pointer.
334 unsigned innermost = -1U;
335 bool considerDeclSpec = true;
336 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
337 DeclaratorChunk &chunk = declarator.getTypeObject(i);
338 switch (chunk.Kind) {
339 case DeclaratorChunk::Pointer:
340 case DeclaratorChunk::BlockPointer:
341 innermost = i;
John McCallae278a32011-01-12 00:34:59 +0000342 continue;
John McCall711c52b2011-01-05 12:14:39 +0000343
344 case DeclaratorChunk::Reference:
345 case DeclaratorChunk::MemberPointer:
346 case DeclaratorChunk::Paren:
347 case DeclaratorChunk::Array:
348 continue;
349
350 case DeclaratorChunk::Function:
351 considerDeclSpec = false;
352 goto done;
353 }
354 }
355 done:
356
357 // That might actually be the decl spec if we weren't blocked by
358 // anything in the declarator.
359 if (considerDeclSpec) {
John McCall7ea21932011-03-26 01:39:56 +0000360 if (handleObjCPointerTypeAttr(state, attr, declSpecType)) {
361 // Splice the attribute into the decl spec. Prevents the
362 // attribute from being applied multiple times and gives
363 // the source-location-filler something to work with.
364 state.saveDeclSpecAttrs();
365 moveAttrFromListToList(attr, declarator.getAttrListRef(),
366 declarator.getMutableDeclSpec().getAttributes().getListRef());
John McCall711c52b2011-01-05 12:14:39 +0000367 return;
John McCall7ea21932011-03-26 01:39:56 +0000368 }
John McCall711c52b2011-01-05 12:14:39 +0000369 }
370
371 // Otherwise, if we found an appropriate chunk, splice the attribute
372 // into it.
373 if (innermost != -1U) {
374 moveAttrFromListToList(attr, declarator.getAttrListRef(),
375 declarator.getTypeObject(innermost).getAttrListRef());
376 return;
377 }
378
379 // Otherwise, diagnose when we're done building the type.
380 spliceAttrOutOfList(attr, declarator.getAttrListRef());
381 state.addIgnoredTypeAttr(attr);
382}
383
384/// A function type attribute was written somewhere in a declaration
385/// *other* than on the declarator itself or in the decl spec. Given
386/// that it didn't apply in whatever position it was written in, try
387/// to move it to a more appropriate position.
388static void distributeFunctionTypeAttr(TypeProcessingState &state,
389 AttributeList &attr,
390 QualType type) {
391 Declarator &declarator = state.getDeclarator();
392
393 // Try to push the attribute from the return type of a function to
394 // the function itself.
395 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
396 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
397 switch (chunk.Kind) {
398 case DeclaratorChunk::Function:
399 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
400 chunk.getAttrListRef());
401 return;
402
403 case DeclaratorChunk::Paren:
404 case DeclaratorChunk::Pointer:
405 case DeclaratorChunk::BlockPointer:
406 case DeclaratorChunk::Array:
407 case DeclaratorChunk::Reference:
408 case DeclaratorChunk::MemberPointer:
409 continue;
410 }
411 }
412
John McCall2792fa52011-03-08 04:17:03 +0000413 diagnoseBadTypeAttribute(state.getSema(), attr, type);
John McCall711c52b2011-01-05 12:14:39 +0000414}
415
416/// Try to distribute a function type attribute to the innermost
417/// function chunk or type. Returns true if the attribute was
418/// distributed, false if no location was found.
419static bool
420distributeFunctionTypeAttrToInnermost(TypeProcessingState &state,
421 AttributeList &attr,
422 AttributeList *&attrList,
423 QualType &declSpecType) {
424 Declarator &declarator = state.getDeclarator();
425
426 // Put it on the innermost function chunk, if there is one.
427 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
428 DeclaratorChunk &chunk = declarator.getTypeObject(i);
429 if (chunk.Kind != DeclaratorChunk::Function) continue;
430
431 moveAttrFromListToList(attr, attrList, chunk.getAttrListRef());
432 return true;
433 }
434
John McCallf85e1932011-06-15 23:02:42 +0000435 if (handleFunctionTypeAttr(state, attr, declSpecType)) {
436 spliceAttrOutOfList(attr, attrList);
437 return true;
438 }
439
440 return false;
John McCall711c52b2011-01-05 12:14:39 +0000441}
442
443/// A function type attribute was written in the decl spec. Try to
444/// apply it somewhere.
445static void
446distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state,
447 AttributeList &attr,
448 QualType &declSpecType) {
449 state.saveDeclSpecAttrs();
450
451 // Try to distribute to the innermost.
452 if (distributeFunctionTypeAttrToInnermost(state, attr,
453 state.getCurrentAttrListRef(),
454 declSpecType))
455 return;
456
457 // If that failed, diagnose the bad attribute when the declarator is
458 // fully built.
459 state.addIgnoredTypeAttr(attr);
460}
461
462/// A function type attribute was written on the declarator. Try to
463/// apply it somewhere.
464static void
465distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state,
466 AttributeList &attr,
467 QualType &declSpecType) {
468 Declarator &declarator = state.getDeclarator();
469
470 // Try to distribute to the innermost.
471 if (distributeFunctionTypeAttrToInnermost(state, attr,
472 declarator.getAttrListRef(),
473 declSpecType))
474 return;
475
476 // If that failed, diagnose the bad attribute when the declarator is
477 // fully built.
478 spliceAttrOutOfList(attr, declarator.getAttrListRef());
479 state.addIgnoredTypeAttr(attr);
480}
481
482/// \brief Given that there are attributes written on the declarator
483/// itself, try to distribute any type attributes to the appropriate
484/// declarator chunk.
485///
486/// These are attributes like the following:
487/// int f ATTR;
488/// int (f ATTR)();
489/// but not necessarily this:
490/// int f() ATTR;
491static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state,
492 QualType &declSpecType) {
493 // Collect all the type attributes from the declarator itself.
494 assert(state.getDeclarator().getAttributes() && "declarator has no attrs!");
495 AttributeList *attr = state.getDeclarator().getAttributes();
496 AttributeList *next;
497 do {
498 next = attr->getNext();
499
500 switch (attr->getKind()) {
501 OBJC_POINTER_TYPE_ATTRS_CASELIST:
502 distributeObjCPointerTypeAttrFromDeclarator(state, *attr, declSpecType);
503 break;
504
John McCallf85e1932011-06-15 23:02:42 +0000505 case AttributeList::AT_ns_returns_retained:
506 if (!state.getSema().getLangOptions().ObjCAutoRefCount)
507 break;
508 // fallthrough
509
John McCall711c52b2011-01-05 12:14:39 +0000510 FUNCTION_TYPE_ATTRS_CASELIST:
511 distributeFunctionTypeAttrFromDeclarator(state, *attr, declSpecType);
512 break;
513
514 default:
515 break;
516 }
517 } while ((attr = next));
518}
519
520/// Add a synthetic '()' to a block-literal declarator if it is
521/// required, given the return type.
522static void maybeSynthesizeBlockSignature(TypeProcessingState &state,
523 QualType declSpecType) {
524 Declarator &declarator = state.getDeclarator();
525
526 // First, check whether the declarator would produce a function,
527 // i.e. whether the innermost semantic chunk is a function.
528 if (declarator.isFunctionDeclarator()) {
529 // If so, make that declarator a prototyped declarator.
530 declarator.getFunctionTypeInfo().hasPrototype = true;
531 return;
532 }
533
John McCallda263792011-02-08 01:59:10 +0000534 // If there are any type objects, the type as written won't name a
535 // function, regardless of the decl spec type. This is because a
536 // block signature declarator is always an abstract-declarator, and
537 // abstract-declarators can't just be parentheses chunks. Therefore
538 // we need to build a function chunk unless there are no type
539 // objects and the decl spec type is a function.
John McCall711c52b2011-01-05 12:14:39 +0000540 if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType())
541 return;
542
John McCallda263792011-02-08 01:59:10 +0000543 // Note that there *are* cases with invalid declarators where
544 // declarators consist solely of parentheses. In general, these
545 // occur only in failed efforts to make function declarators, so
546 // faking up the function chunk is still the right thing to do.
John McCall711c52b2011-01-05 12:14:39 +0000547
548 // Otherwise, we need to fake up a function declarator.
549 SourceLocation loc = declarator.getSourceRange().getBegin();
550
551 // ...and *prepend* it to the declarator.
552 declarator.AddInnermostTypeInfo(DeclaratorChunk::getFunction(
John McCall711c52b2011-01-05 12:14:39 +0000553 /*proto*/ true,
554 /*variadic*/ false, SourceLocation(),
555 /*args*/ 0, 0,
556 /*type quals*/ 0,
Douglas Gregor83f51722011-01-26 03:43:54 +0000557 /*ref-qualifier*/true, SourceLocation(),
Douglas Gregor90ebed02011-07-13 21:47:47 +0000558 /*mutable qualifier*/SourceLocation(),
Sebastian Redl6e5d3192011-03-05 22:42:13 +0000559 /*EH*/ EST_None, SourceLocation(), 0, 0, 0, 0,
John McCall711c52b2011-01-05 12:14:39 +0000560 /*parens*/ loc, loc,
561 declarator));
562
563 // For consistency, make sure the state still has us as processing
564 // the decl spec.
565 assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1);
566 state.setCurrentChunkIndex(declarator.getNumTypeObjects());
John McCall04a67a62010-02-05 21:31:56 +0000567}
568
Douglas Gregor930d8b52009-01-30 22:09:00 +0000569/// \brief Convert the specified declspec to the appropriate type
570/// object.
Chris Lattner5db2bb12009-10-25 18:21:37 +0000571/// \param D the declarator containing the declaration specifier.
Chris Lattner5153ee62009-04-25 08:47:54 +0000572/// \returns The type described by the declaration specifiers. This function
573/// never returns null.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +0000574static QualType ConvertDeclSpecToType(TypeProcessingState &state) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000575 // FIXME: Should move the logic from DeclSpec::Finish to here for validity
576 // checking.
John McCall711c52b2011-01-05 12:14:39 +0000577
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +0000578 Sema &S = state.getSema();
John McCall711c52b2011-01-05 12:14:39 +0000579 Declarator &declarator = state.getDeclarator();
580 const DeclSpec &DS = declarator.getDeclSpec();
581 SourceLocation DeclLoc = declarator.getIdentifierLoc();
Chris Lattner5db2bb12009-10-25 18:21:37 +0000582 if (DeclLoc.isInvalid())
583 DeclLoc = DS.getSourceRange().getBegin();
Chris Lattner1564e392009-10-25 18:07:27 +0000584
John McCall711c52b2011-01-05 12:14:39 +0000585 ASTContext &Context = S.Context;
Mike Stump1eb44332009-09-09 15:08:12 +0000586
Chris Lattner5db2bb12009-10-25 18:21:37 +0000587 QualType Result;
Reid Spencer5f016e22007-07-11 17:01:13 +0000588 switch (DS.getTypeSpecType()) {
Chris Lattner96b77fc2008-04-02 06:50:17 +0000589 case DeclSpec::TST_void:
590 Result = Context.VoidTy;
591 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000592 case DeclSpec::TST_char:
593 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
Chris Lattnerfab5b452008-02-20 23:53:49 +0000594 Result = Context.CharTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000595 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed)
Chris Lattnerfab5b452008-02-20 23:53:49 +0000596 Result = Context.SignedCharTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000597 else {
598 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
599 "Unknown TSS value");
Chris Lattnerfab5b452008-02-20 23:53:49 +0000600 Result = Context.UnsignedCharTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000601 }
Chris Lattner958858e2008-02-20 21:40:32 +0000602 break;
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000603 case DeclSpec::TST_wchar:
604 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
605 Result = Context.WCharTy;
606 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) {
John McCall711c52b2011-01-05 12:14:39 +0000607 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000608 << DS.getSpecifierName(DS.getTypeSpecType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000609 Result = Context.getSignedWCharType();
610 } else {
611 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
612 "Unknown TSS value");
John McCall711c52b2011-01-05 12:14:39 +0000613 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000614 << DS.getSpecifierName(DS.getTypeSpecType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000615 Result = Context.getUnsignedWCharType();
616 }
617 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000618 case DeclSpec::TST_char16:
619 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
620 "Unknown TSS value");
621 Result = Context.Char16Ty;
622 break;
623 case DeclSpec::TST_char32:
624 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
625 "Unknown TSS value");
626 Result = Context.Char32Ty;
627 break;
Chris Lattnerd658b562008-04-05 06:32:51 +0000628 case DeclSpec::TST_unspecified:
Chris Lattner62f5f7f2008-07-26 00:46:50 +0000629 // "<proto1,proto2>" is an objc qualified ID with a missing id.
Chris Lattner097e9162008-10-20 02:01:50 +0000630 if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) {
John McCallc12c5bb2010-05-15 11:32:37 +0000631 Result = Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
632 (ObjCProtocolDecl**)PQ,
633 DS.getNumProtocolQualifiers());
634 Result = Context.getObjCObjectPointerType(Result);
Chris Lattner62f5f7f2008-07-26 00:46:50 +0000635 break;
636 }
Chris Lattner5db2bb12009-10-25 18:21:37 +0000637
638 // If this is a missing declspec in a block literal return context, then it
639 // is inferred from the return statements inside the block.
John McCall711c52b2011-01-05 12:14:39 +0000640 if (isOmittedBlockReturnType(declarator)) {
Chris Lattner5db2bb12009-10-25 18:21:37 +0000641 Result = Context.DependentTy;
642 break;
643 }
Mike Stump1eb44332009-09-09 15:08:12 +0000644
Chris Lattnerd658b562008-04-05 06:32:51 +0000645 // Unspecified typespec defaults to int in C90. However, the C90 grammar
646 // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
647 // type-qualifier, or storage-class-specifier. If not, emit an extwarn.
648 // Note that the one exception to this is function definitions, which are
649 // allowed to be completely missing a declspec. This is handled in the
650 // parser already though by it pretending to have seen an 'int' in this
651 // case.
John McCall711c52b2011-01-05 12:14:39 +0000652 if (S.getLangOptions().ImplicitInt) {
Chris Lattner35d276f2009-02-27 18:53:28 +0000653 // In C89 mode, we only warn if there is a completely missing declspec
654 // when one is not allowed.
Chris Lattner3f84ad22009-04-22 05:27:59 +0000655 if (DS.isEmpty()) {
John McCall711c52b2011-01-05 12:14:39 +0000656 S.Diag(DeclLoc, diag::ext_missing_declspec)
Chris Lattner3f84ad22009-04-22 05:27:59 +0000657 << DS.getSourceRange()
Douglas Gregor849b2432010-03-31 17:46:05 +0000658 << FixItHint::CreateInsertion(DS.getSourceRange().getBegin(), "int");
Chris Lattner3f84ad22009-04-22 05:27:59 +0000659 }
Douglas Gregor4310f4e2009-02-16 22:38:20 +0000660 } else if (!DS.hasTypeSpecifier()) {
Chris Lattnerd658b562008-04-05 06:32:51 +0000661 // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says:
662 // "At least one type specifier shall be given in the declaration
663 // specifiers in each declaration, and in the specifier-qualifier list in
664 // each struct declaration and type name."
Douglas Gregor4310f4e2009-02-16 22:38:20 +0000665 // FIXME: Does Microsoft really have the implicit int extension in C++?
John McCall711c52b2011-01-05 12:14:39 +0000666 if (S.getLangOptions().CPlusPlus &&
Francois Pichet62ec1f22011-09-17 17:15:52 +0000667 !S.getLangOptions().MicrosoftExt) {
John McCall711c52b2011-01-05 12:14:39 +0000668 S.Diag(DeclLoc, diag::err_missing_type_specifier)
Chris Lattner3f84ad22009-04-22 05:27:59 +0000669 << DS.getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000670
Chris Lattnerb78d8332009-06-26 04:45:06 +0000671 // When this occurs in C++ code, often something is very broken with the
672 // value being declared, poison it as invalid so we don't get chains of
673 // errors.
John McCall711c52b2011-01-05 12:14:39 +0000674 declarator.setInvalidType(true);
Chris Lattnerb78d8332009-06-26 04:45:06 +0000675 } else {
John McCall711c52b2011-01-05 12:14:39 +0000676 S.Diag(DeclLoc, diag::ext_missing_type_specifier)
Chris Lattner3f84ad22009-04-22 05:27:59 +0000677 << DS.getSourceRange();
Chris Lattnerb78d8332009-06-26 04:45:06 +0000678 }
Chris Lattnerd658b562008-04-05 06:32:51 +0000679 }
Mike Stump1eb44332009-09-09 15:08:12 +0000680
681 // FALL THROUGH.
Chris Lattner3cbc38b2007-08-21 17:02:28 +0000682 case DeclSpec::TST_int: {
Reid Spencer5f016e22007-07-11 17:01:13 +0000683 if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) {
684 switch (DS.getTypeSpecWidth()) {
Chris Lattnerfab5b452008-02-20 23:53:49 +0000685 case DeclSpec::TSW_unspecified: Result = Context.IntTy; break;
686 case DeclSpec::TSW_short: Result = Context.ShortTy; break;
687 case DeclSpec::TSW_long: Result = Context.LongTy; break;
Chris Lattner311157f2009-10-25 18:25:04 +0000688 case DeclSpec::TSW_longlong:
689 Result = Context.LongLongTy;
690
691 // long long is a C99 feature.
John McCall711c52b2011-01-05 12:14:39 +0000692 if (!S.getLangOptions().C99 &&
693 !S.getLangOptions().CPlusPlus0x)
694 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_longlong);
Chris Lattner311157f2009-10-25 18:25:04 +0000695 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000696 }
697 } else {
698 switch (DS.getTypeSpecWidth()) {
Chris Lattnerfab5b452008-02-20 23:53:49 +0000699 case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break;
700 case DeclSpec::TSW_short: Result = Context.UnsignedShortTy; break;
701 case DeclSpec::TSW_long: Result = Context.UnsignedLongTy; break;
Chris Lattner311157f2009-10-25 18:25:04 +0000702 case DeclSpec::TSW_longlong:
703 Result = Context.UnsignedLongLongTy;
704
705 // long long is a C99 feature.
John McCall711c52b2011-01-05 12:14:39 +0000706 if (!S.getLangOptions().C99 &&
707 !S.getLangOptions().CPlusPlus0x)
708 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_longlong);
Chris Lattner311157f2009-10-25 18:25:04 +0000709 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000710 }
711 }
Chris Lattner958858e2008-02-20 21:40:32 +0000712 break;
Chris Lattner3cbc38b2007-08-21 17:02:28 +0000713 }
Chris Lattnerfab5b452008-02-20 23:53:49 +0000714 case DeclSpec::TST_float: Result = Context.FloatTy; break;
Chris Lattner958858e2008-02-20 21:40:32 +0000715 case DeclSpec::TST_double:
716 if (DS.getTypeSpecWidth() == DeclSpec::TSW_long)
Chris Lattnerfab5b452008-02-20 23:53:49 +0000717 Result = Context.LongDoubleTy;
Chris Lattner958858e2008-02-20 21:40:32 +0000718 else
Chris Lattnerfab5b452008-02-20 23:53:49 +0000719 Result = Context.DoubleTy;
Peter Collingbourne39d3e7a2011-02-15 19:46:23 +0000720
721 if (S.getLangOptions().OpenCL && !S.getOpenCLOptions().cl_khr_fp64) {
722 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_double_requires_fp64);
723 declarator.setInvalidType(true);
724 }
Chris Lattner958858e2008-02-20 21:40:32 +0000725 break;
Chris Lattnerfab5b452008-02-20 23:53:49 +0000726 case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool
Reid Spencer5f016e22007-07-11 17:01:13 +0000727 case DeclSpec::TST_decimal32: // _Decimal32
728 case DeclSpec::TST_decimal64: // _Decimal64
729 case DeclSpec::TST_decimal128: // _Decimal128
John McCall711c52b2011-01-05 12:14:39 +0000730 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
Chris Lattner8f12f652009-05-13 05:02:08 +0000731 Result = Context.IntTy;
John McCall711c52b2011-01-05 12:14:39 +0000732 declarator.setInvalidType(true);
Chris Lattner8f12f652009-05-13 05:02:08 +0000733 break;
Chris Lattner99dc9142008-04-13 18:59:07 +0000734 case DeclSpec::TST_class:
Reid Spencer5f016e22007-07-11 17:01:13 +0000735 case DeclSpec::TST_enum:
736 case DeclSpec::TST_union:
737 case DeclSpec::TST_struct: {
John McCallb3d87482010-08-24 05:47:05 +0000738 TypeDecl *D = dyn_cast_or_null<TypeDecl>(DS.getRepAsDecl());
John McCall6e247262009-10-10 05:48:19 +0000739 if (!D) {
740 // This can happen in C++ with ambiguous lookups.
741 Result = Context.IntTy;
John McCall711c52b2011-01-05 12:14:39 +0000742 declarator.setInvalidType(true);
John McCall6e247262009-10-10 05:48:19 +0000743 break;
744 }
745
Chris Lattnera64ef0a2009-10-25 22:09:09 +0000746 // If the type is deprecated or unavailable, diagnose it.
Abramo Bagnara0daaf322011-03-16 20:16:18 +0000747 S.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeNameLoc());
Chris Lattnera64ef0a2009-10-25 22:09:09 +0000748
Reid Spencer5f016e22007-07-11 17:01:13 +0000749 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
Chris Lattnera64ef0a2009-10-25 22:09:09 +0000750 DS.getTypeSpecSign() == 0 && "No qualifiers on tag names!");
751
Reid Spencer5f016e22007-07-11 17:01:13 +0000752 // TypeQuals handled by caller.
Chris Lattnera64ef0a2009-10-25 22:09:09 +0000753 Result = Context.getTypeDeclType(D);
John McCall2191b202009-09-05 06:31:47 +0000754
Abramo Bagnara0daaf322011-03-16 20:16:18 +0000755 // In both C and C++, make an ElaboratedType.
756 ElaboratedTypeKeyword Keyword
757 = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType());
758 Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result);
759
Chris Lattner5153ee62009-04-25 08:47:54 +0000760 if (D->isInvalidDecl())
John McCall711c52b2011-01-05 12:14:39 +0000761 declarator.setInvalidType(true);
Chris Lattner958858e2008-02-20 21:40:32 +0000762 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000763 }
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000764 case DeclSpec::TST_typename: {
Reid Spencer5f016e22007-07-11 17:01:13 +0000765 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
766 DS.getTypeSpecSign() == 0 &&
767 "Can't handle qualifiers on typedef names yet!");
John McCall711c52b2011-01-05 12:14:39 +0000768 Result = S.GetTypeFromParser(DS.getRepAsType());
John McCall27940d22010-07-30 05:17:22 +0000769 if (Result.isNull())
John McCall711c52b2011-01-05 12:14:39 +0000770 declarator.setInvalidType(true);
John McCall27940d22010-07-30 05:17:22 +0000771 else if (DeclSpec::ProtocolQualifierListTy PQ
772 = DS.getProtocolQualifiers()) {
John McCallc12c5bb2010-05-15 11:32:37 +0000773 if (const ObjCObjectType *ObjT = Result->getAs<ObjCObjectType>()) {
774 // Silently drop any existing protocol qualifiers.
775 // TODO: determine whether that's the right thing to do.
776 if (ObjT->getNumProtocols())
777 Result = ObjT->getBaseType();
778
779 if (DS.getNumProtocolQualifiers())
780 Result = Context.getObjCObjectType(Result,
781 (ObjCProtocolDecl**) PQ,
782 DS.getNumProtocolQualifiers());
783 } else if (Result->isObjCIdType()) {
Chris Lattnerae4da612008-07-26 01:53:50 +0000784 // id<protocol-list>
John McCallc12c5bb2010-05-15 11:32:37 +0000785 Result = Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
786 (ObjCProtocolDecl**) PQ,
787 DS.getNumProtocolQualifiers());
788 Result = Context.getObjCObjectPointerType(Result);
789 } else if (Result->isObjCClassType()) {
Steve Naroff4262a072009-02-23 18:53:24 +0000790 // Class<protocol-list>
John McCallc12c5bb2010-05-15 11:32:37 +0000791 Result = Context.getObjCObjectType(Context.ObjCBuiltinClassTy,
792 (ObjCProtocolDecl**) PQ,
793 DS.getNumProtocolQualifiers());
794 Result = Context.getObjCObjectPointerType(Result);
Chris Lattner3f84ad22009-04-22 05:27:59 +0000795 } else {
John McCall711c52b2011-01-05 12:14:39 +0000796 S.Diag(DeclLoc, diag::err_invalid_protocol_qualifiers)
Chris Lattner3f84ad22009-04-22 05:27:59 +0000797 << DS.getSourceRange();
John McCall711c52b2011-01-05 12:14:39 +0000798 declarator.setInvalidType(true);
Chris Lattner3f84ad22009-04-22 05:27:59 +0000799 }
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000800 }
Mike Stump1eb44332009-09-09 15:08:12 +0000801
Reid Spencer5f016e22007-07-11 17:01:13 +0000802 // TypeQuals handled by caller.
Chris Lattner958858e2008-02-20 21:40:32 +0000803 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000804 }
Chris Lattner958858e2008-02-20 21:40:32 +0000805 case DeclSpec::TST_typeofType:
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000806 // FIXME: Preserve type source info.
John McCall711c52b2011-01-05 12:14:39 +0000807 Result = S.GetTypeFromParser(DS.getRepAsType());
Chris Lattner958858e2008-02-20 21:40:32 +0000808 assert(!Result.isNull() && "Didn't get a type for typeof?");
Fariborz Jahanian730e1752010-10-06 17:00:02 +0000809 if (!Result->isDependentType())
810 if (const TagType *TT = Result->getAs<TagType>())
John McCall711c52b2011-01-05 12:14:39 +0000811 S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc());
Steve Naroffd1861fd2007-07-31 12:34:36 +0000812 // TypeQuals handled by caller.
Chris Lattnerfab5b452008-02-20 23:53:49 +0000813 Result = Context.getTypeOfType(Result);
Chris Lattner958858e2008-02-20 21:40:32 +0000814 break;
Steve Naroffd1861fd2007-07-31 12:34:36 +0000815 case DeclSpec::TST_typeofExpr: {
John McCallb3d87482010-08-24 05:47:05 +0000816 Expr *E = DS.getRepAsExpr();
Steve Naroffd1861fd2007-07-31 12:34:36 +0000817 assert(E && "Didn't get an expression for typeof?");
818 // TypeQuals handled by caller.
John McCall711c52b2011-01-05 12:14:39 +0000819 Result = S.BuildTypeofExprType(E, DS.getTypeSpecTypeLoc());
Douglas Gregor4b52e252009-12-21 23:17:24 +0000820 if (Result.isNull()) {
821 Result = Context.IntTy;
John McCall711c52b2011-01-05 12:14:39 +0000822 declarator.setInvalidType(true);
Douglas Gregor4b52e252009-12-21 23:17:24 +0000823 }
Chris Lattner958858e2008-02-20 21:40:32 +0000824 break;
Steve Naroffd1861fd2007-07-31 12:34:36 +0000825 }
Anders Carlsson6fd634f2009-06-24 17:47:40 +0000826 case DeclSpec::TST_decltype: {
John McCallb3d87482010-08-24 05:47:05 +0000827 Expr *E = DS.getRepAsExpr();
Anders Carlsson6fd634f2009-06-24 17:47:40 +0000828 assert(E && "Didn't get an expression for decltype?");
829 // TypeQuals handled by caller.
John McCall711c52b2011-01-05 12:14:39 +0000830 Result = S.BuildDecltypeType(E, DS.getTypeSpecTypeLoc());
Anders Carlssonaf017e62009-06-29 22:58:55 +0000831 if (Result.isNull()) {
832 Result = Context.IntTy;
John McCall711c52b2011-01-05 12:14:39 +0000833 declarator.setInvalidType(true);
Anders Carlssonaf017e62009-06-29 22:58:55 +0000834 }
Anders Carlsson6fd634f2009-06-24 17:47:40 +0000835 break;
836 }
Sean Huntca63c202011-05-24 22:41:36 +0000837 case DeclSpec::TST_underlyingType:
Sean Huntdb5d44b2011-05-19 05:37:45 +0000838 Result = S.GetTypeFromParser(DS.getRepAsType());
839 assert(!Result.isNull() && "Didn't get a type for __underlying_type?");
Sean Huntca63c202011-05-24 22:41:36 +0000840 Result = S.BuildUnaryTransformType(Result,
841 UnaryTransformType::EnumUnderlyingType,
842 DS.getTypeSpecTypeLoc());
843 if (Result.isNull()) {
844 Result = Context.IntTy;
845 declarator.setInvalidType(true);
Sean Huntdb5d44b2011-05-19 05:37:45 +0000846 }
847 break;
848
Anders Carlssone89d1592009-06-26 18:41:36 +0000849 case DeclSpec::TST_auto: {
850 // TypeQuals handled by caller.
Richard Smith34b41d92011-02-20 03:19:35 +0000851 Result = Context.getAutoType(QualType());
Anders Carlssone89d1592009-06-26 18:41:36 +0000852 break;
853 }
Mike Stump1eb44332009-09-09 15:08:12 +0000854
John McCalla5fc4722011-04-09 22:50:59 +0000855 case DeclSpec::TST_unknown_anytype:
856 Result = Context.UnknownAnyTy;
857 break;
858
Douglas Gregor809070a2009-02-18 17:45:20 +0000859 case DeclSpec::TST_error:
Chris Lattner5153ee62009-04-25 08:47:54 +0000860 Result = Context.IntTy;
John McCall711c52b2011-01-05 12:14:39 +0000861 declarator.setInvalidType(true);
Chris Lattner5153ee62009-04-25 08:47:54 +0000862 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000863 }
Mike Stump1eb44332009-09-09 15:08:12 +0000864
Chris Lattner958858e2008-02-20 21:40:32 +0000865 // Handle complex types.
Douglas Gregorf244cd72009-02-14 21:06:05 +0000866 if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
John McCall711c52b2011-01-05 12:14:39 +0000867 if (S.getLangOptions().Freestanding)
868 S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
Chris Lattnerfab5b452008-02-20 23:53:49 +0000869 Result = Context.getComplexType(Result);
John Thompson82287d12010-02-05 00:12:22 +0000870 } else if (DS.isTypeAltiVecVector()) {
871 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result));
872 assert(typeSize > 0 && "type size for vector must be greater than 0 bits");
Bob Wilsone86d78c2010-11-10 21:56:12 +0000873 VectorType::VectorKind VecKind = VectorType::AltiVecVector;
Chris Lattner788b0fd2010-06-23 06:00:24 +0000874 if (DS.isTypeAltiVecPixel())
Bob Wilsone86d78c2010-11-10 21:56:12 +0000875 VecKind = VectorType::AltiVecPixel;
Chris Lattner788b0fd2010-06-23 06:00:24 +0000876 else if (DS.isTypeAltiVecBool())
Bob Wilsone86d78c2010-11-10 21:56:12 +0000877 VecKind = VectorType::AltiVecBool;
878 Result = Context.getVectorType(Result, 128/typeSize, VecKind);
Douglas Gregorf244cd72009-02-14 21:06:05 +0000879 }
Mike Stump1eb44332009-09-09 15:08:12 +0000880
Argyrios Kyrtzidis47423bd2010-09-23 09:40:31 +0000881 // FIXME: Imaginary.
882 if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary)
John McCall711c52b2011-01-05 12:14:39 +0000883 S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported);
Mike Stump1eb44332009-09-09 15:08:12 +0000884
John McCall711c52b2011-01-05 12:14:39 +0000885 // Before we process any type attributes, synthesize a block literal
886 // function declarator if necessary.
887 if (declarator.getContext() == Declarator::BlockLiteralContext)
888 maybeSynthesizeBlockSignature(state, Result);
889
890 // Apply any type attributes from the decl spec. This may cause the
891 // list of type attributes to be temporarily saved while the type
892 // attributes are pushed around.
893 if (AttributeList *attrs = DS.getAttributes().getList())
894 processTypeAttrs(state, Result, true, attrs);
Mike Stump1eb44332009-09-09 15:08:12 +0000895
Chris Lattner96b77fc2008-04-02 06:50:17 +0000896 // Apply const/volatile/restrict qualifiers to T.
897 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
898
899 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
900 // or incomplete types shall not be restrict-qualified." C++ also allows
901 // restrict-qualified references.
John McCall0953e762009-09-24 19:53:00 +0000902 if (TypeQuals & DeclSpec::TQ_restrict) {
Fariborz Jahanian2b5ff1a2009-12-07 18:08:58 +0000903 if (Result->isAnyPointerType() || Result->isReferenceType()) {
904 QualType EltTy;
905 if (Result->isObjCObjectPointerType())
906 EltTy = Result;
907 else
908 EltTy = Result->isPointerType() ?
909 Result->getAs<PointerType>()->getPointeeType() :
910 Result->getAs<ReferenceType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +0000911
Douglas Gregorbad0e652009-03-24 20:32:41 +0000912 // If we have a pointer or reference, the pointee must have an object
Chris Lattnerbdcd6372008-04-02 17:35:06 +0000913 // incomplete type.
914 if (!EltTy->isIncompleteOrObjectType()) {
John McCall711c52b2011-01-05 12:14:39 +0000915 S.Diag(DS.getRestrictSpecLoc(),
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000916 diag::err_typecheck_invalid_restrict_invalid_pointee)
Chris Lattnerd1625842008-11-24 06:25:27 +0000917 << EltTy << DS.getSourceRange();
John McCall0953e762009-09-24 19:53:00 +0000918 TypeQuals &= ~DeclSpec::TQ_restrict; // Remove the restrict qualifier.
Chris Lattnerbdcd6372008-04-02 17:35:06 +0000919 }
920 } else {
John McCall711c52b2011-01-05 12:14:39 +0000921 S.Diag(DS.getRestrictSpecLoc(),
922 diag::err_typecheck_invalid_restrict_not_pointer)
Chris Lattnerd1625842008-11-24 06:25:27 +0000923 << Result << DS.getSourceRange();
John McCall0953e762009-09-24 19:53:00 +0000924 TypeQuals &= ~DeclSpec::TQ_restrict; // Remove the restrict qualifier.
Chris Lattner96b77fc2008-04-02 06:50:17 +0000925 }
Chris Lattner96b77fc2008-04-02 06:50:17 +0000926 }
Mike Stump1eb44332009-09-09 15:08:12 +0000927
Chris Lattner96b77fc2008-04-02 06:50:17 +0000928 // Warn about CV qualifiers on functions: C99 6.7.3p8: "If the specification
929 // of a function type includes any type qualifiers, the behavior is
930 // undefined."
931 if (Result->isFunctionType() && TypeQuals) {
932 // Get some location to point at, either the C or V location.
933 SourceLocation Loc;
John McCall0953e762009-09-24 19:53:00 +0000934 if (TypeQuals & DeclSpec::TQ_const)
Chris Lattner96b77fc2008-04-02 06:50:17 +0000935 Loc = DS.getConstSpecLoc();
John McCall0953e762009-09-24 19:53:00 +0000936 else if (TypeQuals & DeclSpec::TQ_volatile)
Chris Lattner96b77fc2008-04-02 06:50:17 +0000937 Loc = DS.getVolatileSpecLoc();
John McCall0953e762009-09-24 19:53:00 +0000938 else {
939 assert((TypeQuals & DeclSpec::TQ_restrict) &&
940 "Has CVR quals but not C, V, or R?");
941 Loc = DS.getRestrictSpecLoc();
Chris Lattner96b77fc2008-04-02 06:50:17 +0000942 }
John McCall711c52b2011-01-05 12:14:39 +0000943 S.Diag(Loc, diag::warn_typecheck_function_qualifiers)
Chris Lattnerd1625842008-11-24 06:25:27 +0000944 << Result << DS.getSourceRange();
Chris Lattner96b77fc2008-04-02 06:50:17 +0000945 }
Mike Stump1eb44332009-09-09 15:08:12 +0000946
Douglas Gregorf1f9b4e2008-11-03 15:51:28 +0000947 // C++ [dcl.ref]p1:
948 // Cv-qualified references are ill-formed except when the
949 // cv-qualifiers are introduced through the use of a typedef
950 // (7.1.3) or of a template type argument (14.3), in which
951 // case the cv-qualifiers are ignored.
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000952 // FIXME: Shouldn't we be checking SCS_typedef here?
953 if (DS.getTypeSpecType() == DeclSpec::TST_typename &&
Douglas Gregorf1f9b4e2008-11-03 15:51:28 +0000954 TypeQuals && Result->isReferenceType()) {
John McCall0953e762009-09-24 19:53:00 +0000955 TypeQuals &= ~DeclSpec::TQ_const;
956 TypeQuals &= ~DeclSpec::TQ_volatile;
Mike Stump1eb44332009-09-09 15:08:12 +0000957 }
958
John McCall0953e762009-09-24 19:53:00 +0000959 Qualifiers Quals = Qualifiers::fromCVRMask(TypeQuals);
960 Result = Context.getQualifiedType(Result, Quals);
Chris Lattner96b77fc2008-04-02 06:50:17 +0000961 }
John McCall0953e762009-09-24 19:53:00 +0000962
Chris Lattnerf1d705c2008-02-21 01:07:18 +0000963 return Result;
964}
965
Douglas Gregorcd281c32009-02-28 00:25:32 +0000966static std::string getPrintableNameForEntity(DeclarationName Entity) {
967 if (Entity)
968 return Entity.getAsString();
Mike Stump1eb44332009-09-09 15:08:12 +0000969
Douglas Gregorcd281c32009-02-28 00:25:32 +0000970 return "type name";
971}
972
John McCall28654742010-06-05 06:41:15 +0000973QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
974 Qualifiers Qs) {
975 // Enforce C99 6.7.3p2: "Types other than pointer types derived from
976 // object or incomplete types shall not be restrict-qualified."
977 if (Qs.hasRestrict()) {
978 unsigned DiagID = 0;
979 QualType ProblemTy;
980
981 const Type *Ty = T->getCanonicalTypeInternal().getTypePtr();
982 if (const ReferenceType *RTy = dyn_cast<ReferenceType>(Ty)) {
983 if (!RTy->getPointeeType()->isIncompleteOrObjectType()) {
984 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
985 ProblemTy = T->getAs<ReferenceType>()->getPointeeType();
986 }
987 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
988 if (!PTy->getPointeeType()->isIncompleteOrObjectType()) {
989 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
990 ProblemTy = T->getAs<PointerType>()->getPointeeType();
991 }
992 } else if (const MemberPointerType *PTy = dyn_cast<MemberPointerType>(Ty)) {
993 if (!PTy->getPointeeType()->isIncompleteOrObjectType()) {
994 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
995 ProblemTy = T->getAs<PointerType>()->getPointeeType();
996 }
997 } else if (!Ty->isDependentType()) {
998 // FIXME: this deserves a proper diagnostic
999 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1000 ProblemTy = T;
1001 }
1002
1003 if (DiagID) {
1004 Diag(Loc, DiagID) << ProblemTy;
1005 Qs.removeRestrict();
1006 }
1007 }
1008
1009 return Context.getQualifiedType(T, Qs);
1010}
1011
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001012/// \brief Build a paren type including \p T.
1013QualType Sema::BuildParenType(QualType T) {
1014 return Context.getParenType(T);
1015}
1016
John McCallf85e1932011-06-15 23:02:42 +00001017/// Given that we're building a pointer or reference to the given
1018static QualType inferARCLifetimeForPointee(Sema &S, QualType type,
1019 SourceLocation loc,
1020 bool isReference) {
1021 // Bail out if retention is unrequired or already specified.
1022 if (!type->isObjCLifetimeType() ||
1023 type.getObjCLifetime() != Qualifiers::OCL_None)
1024 return type;
1025
1026 Qualifiers::ObjCLifetime implicitLifetime = Qualifiers::OCL_None;
1027
1028 // If the object type is const-qualified, we can safely use
1029 // __unsafe_unretained. This is safe (because there are no read
1030 // barriers), and it'll be safe to coerce anything but __weak* to
1031 // the resulting type.
1032 if (type.isConstQualified()) {
1033 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1034
1035 // Otherwise, check whether the static type does not require
1036 // retaining. This currently only triggers for Class (possibly
1037 // protocol-qualifed, and arrays thereof).
1038 } else if (type->isObjCARCImplicitlyUnretainedType()) {
1039 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1040
Argyrios Kyrtzidis5b76f372011-09-20 23:49:22 +00001041 // If we are in an unevaluated context, like sizeof, assume ExplicitNone and
1042 // don't give error.
1043 } else if (S.ExprEvalContexts.back().Context == Sema::Unevaluated) {
1044 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1045
John McCallf85e1932011-06-15 23:02:42 +00001046 // If that failed, give an error and recover using __autoreleasing.
1047 } else {
1048 // These types can show up in private ivars in system headers, so
1049 // we need this to not be an error in those cases. Instead we
1050 // want to delay.
1051 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
1052 S.DelayedDiagnostics.add(
1053 sema::DelayedDiagnostic::makeForbiddenType(loc,
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00001054 diag::err_arc_indirect_no_ownership, type, isReference));
John McCallf85e1932011-06-15 23:02:42 +00001055 } else {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00001056 S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference;
John McCallf85e1932011-06-15 23:02:42 +00001057 }
1058 implicitLifetime = Qualifiers::OCL_Autoreleasing;
1059 }
1060 assert(implicitLifetime && "didn't infer any lifetime!");
1061
1062 Qualifiers qs;
1063 qs.addObjCLifetime(implicitLifetime);
1064 return S.Context.getQualifiedType(type, qs);
1065}
1066
Douglas Gregorcd281c32009-02-28 00:25:32 +00001067/// \brief Build a pointer type.
1068///
1069/// \param T The type to which we'll be building a pointer.
1070///
Douglas Gregorcd281c32009-02-28 00:25:32 +00001071/// \param Loc The location of the entity whose type involves this
1072/// pointer type or, if there is no such entity, the location of the
1073/// type that will have pointer type.
1074///
1075/// \param Entity The name of the entity that involves the pointer
1076/// type, if known.
1077///
1078/// \returns A suitable pointer type, if there are no
1079/// errors. Otherwise, returns a NULL type.
John McCall28654742010-06-05 06:41:15 +00001080QualType Sema::BuildPointerType(QualType T,
Douglas Gregorcd281c32009-02-28 00:25:32 +00001081 SourceLocation Loc, DeclarationName Entity) {
1082 if (T->isReferenceType()) {
1083 // C++ 8.3.2p4: There shall be no ... pointers to references ...
1084 Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
John McCallac406052009-10-30 00:37:20 +00001085 << getPrintableNameForEntity(Entity) << T;
Douglas Gregorcd281c32009-02-28 00:25:32 +00001086 return QualType();
1087 }
1088
John McCallc12c5bb2010-05-15 11:32:37 +00001089 assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType");
Douglas Gregor92e986e2010-04-22 16:44:27 +00001090
John McCallf85e1932011-06-15 23:02:42 +00001091 // In ARC, it is forbidden to build pointers to unqualified pointers.
1092 if (getLangOptions().ObjCAutoRefCount)
1093 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false);
1094
Douglas Gregorcd281c32009-02-28 00:25:32 +00001095 // Build the pointer type.
John McCall28654742010-06-05 06:41:15 +00001096 return Context.getPointerType(T);
Douglas Gregorcd281c32009-02-28 00:25:32 +00001097}
1098
1099/// \brief Build a reference type.
1100///
1101/// \param T The type to which we'll be building a reference.
1102///
Douglas Gregorcd281c32009-02-28 00:25:32 +00001103/// \param Loc The location of the entity whose type involves this
1104/// reference type or, if there is no such entity, the location of the
1105/// type that will have reference type.
1106///
1107/// \param Entity The name of the entity that involves the reference
1108/// type, if known.
1109///
1110/// \returns A suitable reference type, if there are no
1111/// errors. Otherwise, returns a NULL type.
John McCall54e14c42009-10-22 22:37:11 +00001112QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue,
John McCall28654742010-06-05 06:41:15 +00001113 SourceLocation Loc,
John McCall54e14c42009-10-22 22:37:11 +00001114 DeclarationName Entity) {
Douglas Gregor9625e442011-05-21 22:16:50 +00001115 assert(Context.getCanonicalType(T) != Context.OverloadTy &&
1116 "Unresolved overloaded function type");
1117
Douglas Gregor69d83162011-01-20 16:08:06 +00001118 // C++0x [dcl.ref]p6:
1119 // If a typedef (7.1.3), a type template-parameter (14.3.1), or a
1120 // decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a
1121 // type T, an attempt to create the type "lvalue reference to cv TR" creates
1122 // the type "lvalue reference to T", while an attempt to create the type
1123 // "rvalue reference to cv TR" creates the type TR.
John McCall54e14c42009-10-22 22:37:11 +00001124 bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
1125
John McCall54e14c42009-10-22 22:37:11 +00001126 // C++ [dcl.ref]p4: There shall be no references to references.
1127 //
1128 // According to C++ DR 106, references to references are only
1129 // diagnosed when they are written directly (e.g., "int & &"),
1130 // but not when they happen via a typedef:
1131 //
1132 // typedef int& intref;
1133 // typedef intref& intref2;
1134 //
1135 // Parser::ParseDeclaratorInternal diagnoses the case where
1136 // references are written directly; here, we handle the
Douglas Gregor69d83162011-01-20 16:08:06 +00001137 // collapsing of references-to-references as described in C++0x.
1138 // DR 106 and 540 introduce reference-collapsing into C++98/03.
Douglas Gregorcd281c32009-02-28 00:25:32 +00001139
1140 // C++ [dcl.ref]p1:
Eli Friedman33a31382009-08-05 19:21:58 +00001141 // A declarator that specifies the type "reference to cv void"
Douglas Gregorcd281c32009-02-28 00:25:32 +00001142 // is ill-formed.
1143 if (T->isVoidType()) {
1144 Diag(Loc, diag::err_reference_to_void);
1145 return QualType();
1146 }
1147
John McCallf85e1932011-06-15 23:02:42 +00001148 // In ARC, it is forbidden to build references to unqualified pointers.
1149 if (getLangOptions().ObjCAutoRefCount)
1150 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true);
1151
Douglas Gregorcd281c32009-02-28 00:25:32 +00001152 // Handle restrict on references.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001153 if (LValueRef)
John McCall28654742010-06-05 06:41:15 +00001154 return Context.getLValueReferenceType(T, SpelledAsLValue);
1155 return Context.getRValueReferenceType(T);
Douglas Gregorcd281c32009-02-28 00:25:32 +00001156}
1157
Chris Lattnere1eed382011-06-14 06:38:10 +00001158/// Check whether the specified array size makes the array type a VLA. If so,
1159/// return true, if not, return the size of the array in SizeVal.
1160static bool isArraySizeVLA(Expr *ArraySize, llvm::APSInt &SizeVal, Sema &S) {
1161 // If the size is an ICE, it certainly isn't a VLA.
1162 if (ArraySize->isIntegerConstantExpr(SizeVal, S.Context))
1163 return false;
1164
1165 // If we're in a GNU mode (like gnu99, but not c99) accept any evaluatable
1166 // value as an extension.
1167 Expr::EvalResult Result;
1168 if (S.LangOpts.GNUMode && ArraySize->Evaluate(Result, S.Context)) {
1169 if (!Result.hasSideEffects() && Result.Val.isInt()) {
1170 SizeVal = Result.Val.getInt();
1171 S.Diag(ArraySize->getLocStart(), diag::ext_vla_folded_to_constant);
1172 return false;
1173 }
1174 }
1175
1176 return true;
1177}
1178
1179
Douglas Gregorcd281c32009-02-28 00:25:32 +00001180/// \brief Build an array type.
1181///
1182/// \param T The type of each element in the array.
1183///
1184/// \param ASM C99 array size modifier (e.g., '*', 'static').
Mike Stump1eb44332009-09-09 15:08:12 +00001185///
1186/// \param ArraySize Expression describing the size of the array.
Douglas Gregorcd281c32009-02-28 00:25:32 +00001187///
Douglas Gregorcd281c32009-02-28 00:25:32 +00001188/// \param Loc The location of the entity whose type involves this
1189/// array type or, if there is no such entity, the location of the
1190/// type that will have array type.
1191///
1192/// \param Entity The name of the entity that involves the array
1193/// type, if known.
1194///
1195/// \returns A suitable array type, if there are no errors. Otherwise,
1196/// returns a NULL type.
1197QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1198 Expr *ArraySize, unsigned Quals,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001199 SourceRange Brackets, DeclarationName Entity) {
John McCall0953e762009-09-24 19:53:00 +00001200
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001201 SourceLocation Loc = Brackets.getBegin();
Sebastian Redl923d56d2009-11-05 15:52:31 +00001202 if (getLangOptions().CPlusPlus) {
Douglas Gregor138bb232010-04-27 19:38:14 +00001203 // C++ [dcl.array]p1:
1204 // T is called the array element type; this type shall not be a reference
1205 // type, the (possibly cv-qualified) type void, a function type or an
1206 // abstract class type.
1207 //
1208 // Note: function types are handled in the common path with C.
1209 if (T->isReferenceType()) {
1210 Diag(Loc, diag::err_illegal_decl_array_of_references)
1211 << getPrintableNameForEntity(Entity) << T;
1212 return QualType();
1213 }
1214
Sebastian Redl923d56d2009-11-05 15:52:31 +00001215 if (T->isVoidType()) {
1216 Diag(Loc, diag::err_illegal_decl_array_incomplete_type) << T;
1217 return QualType();
1218 }
Douglas Gregor138bb232010-04-27 19:38:14 +00001219
1220 if (RequireNonAbstractType(Brackets.getBegin(), T,
1221 diag::err_array_of_abstract_type))
1222 return QualType();
1223
Sebastian Redl923d56d2009-11-05 15:52:31 +00001224 } else {
Douglas Gregor138bb232010-04-27 19:38:14 +00001225 // C99 6.7.5.2p1: If the element type is an incomplete or function type,
1226 // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
Sebastian Redl923d56d2009-11-05 15:52:31 +00001227 if (RequireCompleteType(Loc, T,
1228 diag::err_illegal_decl_array_incomplete_type))
1229 return QualType();
1230 }
Douglas Gregorcd281c32009-02-28 00:25:32 +00001231
1232 if (T->isFunctionType()) {
1233 Diag(Loc, diag::err_illegal_decl_array_of_functions)
John McCallac406052009-10-30 00:37:20 +00001234 << getPrintableNameForEntity(Entity) << T;
Douglas Gregorcd281c32009-02-28 00:25:32 +00001235 return QualType();
1236 }
Mike Stump1eb44332009-09-09 15:08:12 +00001237
Richard Smith34b41d92011-02-20 03:19:35 +00001238 if (T->getContainedAutoType()) {
1239 Diag(Loc, diag::err_illegal_decl_array_of_auto)
1240 << getPrintableNameForEntity(Entity) << T;
Anders Carlssone7cf07d2009-06-26 19:33:28 +00001241 return QualType();
1242 }
Mike Stump1eb44332009-09-09 15:08:12 +00001243
Ted Kremenek6217b802009-07-29 21:53:49 +00001244 if (const RecordType *EltTy = T->getAs<RecordType>()) {
Douglas Gregorcd281c32009-02-28 00:25:32 +00001245 // If the element type is a struct or union that contains a variadic
1246 // array, accept it as a GNU extension: C99 6.7.2.1p2.
1247 if (EltTy->getDecl()->hasFlexibleArrayMember())
1248 Diag(Loc, diag::ext_flexible_array_in_array) << T;
John McCallc12c5bb2010-05-15 11:32:37 +00001249 } else if (T->isObjCObjectType()) {
Chris Lattnerc7c11b12009-04-27 01:55:56 +00001250 Diag(Loc, diag::err_objc_array_of_interfaces) << T;
1251 return QualType();
Douglas Gregorcd281c32009-02-28 00:25:32 +00001252 }
Mike Stump1eb44332009-09-09 15:08:12 +00001253
John McCall5e3c67b2010-12-15 04:42:30 +00001254 // Do lvalue-to-rvalue conversions on the array size expression.
John Wiegley429bb272011-04-08 18:41:53 +00001255 if (ArraySize && !ArraySize->isRValue()) {
1256 ExprResult Result = DefaultLvalueConversion(ArraySize);
1257 if (Result.isInvalid())
1258 return QualType();
1259
1260 ArraySize = Result.take();
1261 }
John McCall5e3c67b2010-12-15 04:42:30 +00001262
Douglas Gregorcd281c32009-02-28 00:25:32 +00001263 // C99 6.7.5.2p1: The size expression shall have integer type.
John McCall5e3c67b2010-12-15 04:42:30 +00001264 // TODO: in theory, if we were insane, we could allow contextual
1265 // conversions to integer type here.
Douglas Gregorcd281c32009-02-28 00:25:32 +00001266 if (ArraySize && !ArraySize->isTypeDependent() &&
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001267 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
Douglas Gregorcd281c32009-02-28 00:25:32 +00001268 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
1269 << ArraySize->getType() << ArraySize->getSourceRange();
Douglas Gregorcd281c32009-02-28 00:25:32 +00001270 return QualType();
1271 }
Douglas Gregor2767ce22010-08-18 00:39:00 +00001272 llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType()));
Douglas Gregorcd281c32009-02-28 00:25:32 +00001273 if (!ArraySize) {
Eli Friedmanf91f5c82009-04-26 21:57:51 +00001274 if (ASM == ArrayType::Star)
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001275 T = Context.getVariableArrayType(T, 0, ASM, Quals, Brackets);
Eli Friedmanf91f5c82009-04-26 21:57:51 +00001276 else
1277 T = Context.getIncompleteArrayType(T, ASM, Quals);
Douglas Gregorac06a0e2010-05-18 23:01:22 +00001278 } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) {
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001279 T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets);
Chris Lattnere1eed382011-06-14 06:38:10 +00001280 } else if (!T->isDependentType() && !T->isIncompleteType() &&
1281 !T->isConstantSizeType()) {
1282 // C99: an array with an element type that has a non-constant-size is a VLA.
1283 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
1284 } else if (isArraySizeVLA(ArraySize, ConstVal, *this)) {
1285 // C99: an array with a non-ICE size is a VLA. We accept any expression
1286 // that we can fold to a non-zero positive value as an extension.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001287 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
Douglas Gregorcd281c32009-02-28 00:25:32 +00001288 } else {
1289 // C99 6.7.5.2p1: If the expression is a constant expression, it shall
1290 // have a value greater than zero.
Sebastian Redl923d56d2009-11-05 15:52:31 +00001291 if (ConstVal.isSigned() && ConstVal.isNegative()) {
Chandler Carruthb2b5cc02011-01-04 04:44:35 +00001292 if (Entity)
1293 Diag(ArraySize->getLocStart(), diag::err_decl_negative_array_size)
1294 << getPrintableNameForEntity(Entity) << ArraySize->getSourceRange();
1295 else
1296 Diag(ArraySize->getLocStart(), diag::err_typecheck_negative_array_size)
1297 << ArraySize->getSourceRange();
Sebastian Redl923d56d2009-11-05 15:52:31 +00001298 return QualType();
1299 }
1300 if (ConstVal == 0) {
Douglas Gregor02024a92010-03-28 02:42:43 +00001301 // GCC accepts zero sized static arrays. We allow them when
1302 // we're not in a SFINAE context.
1303 Diag(ArraySize->getLocStart(),
1304 isSFINAEContext()? diag::err_typecheck_zero_array_size
1305 : diag::ext_typecheck_zero_array_size)
Sebastian Redl923d56d2009-11-05 15:52:31 +00001306 << ArraySize->getSourceRange();
Douglas Gregor2767ce22010-08-18 00:39:00 +00001307 } else if (!T->isDependentType() && !T->isVariablyModifiedType() &&
1308 !T->isIncompleteType()) {
1309 // Is the array too large?
1310 unsigned ActiveSizeBits
1311 = ConstantArrayType::getNumAddressingBits(Context, T, ConstVal);
1312 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
1313 Diag(ArraySize->getLocStart(), diag::err_array_too_large)
1314 << ConstVal.toString(10)
1315 << ArraySize->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001316 }
Douglas Gregor2767ce22010-08-18 00:39:00 +00001317
John McCall46a617a2009-10-16 00:14:28 +00001318 T = Context.getConstantArrayType(T, ConstVal, ASM, Quals);
Douglas Gregorcd281c32009-02-28 00:25:32 +00001319 }
David Chisnallaf407762010-01-11 23:08:08 +00001320 // If this is not C99, extwarn about VLA's and C99 array size modifiers.
1321 if (!getLangOptions().C99) {
Douglas Gregor0fddb972010-05-22 16:17:30 +00001322 if (T->isVariableArrayType()) {
1323 // Prohibit the use of non-POD types in VLAs.
John McCallf85e1932011-06-15 23:02:42 +00001324 QualType BaseT = Context.getBaseElementType(T);
Douglas Gregor204ce172010-05-24 20:42:30 +00001325 if (!T->isDependentType() &&
John McCallf85e1932011-06-15 23:02:42 +00001326 !BaseT.isPODType(Context) &&
1327 !BaseT->isObjCLifetimeType()) {
Douglas Gregor0fddb972010-05-22 16:17:30 +00001328 Diag(Loc, diag::err_vla_non_pod)
John McCallf85e1932011-06-15 23:02:42 +00001329 << BaseT;
Douglas Gregor0fddb972010-05-22 16:17:30 +00001330 return QualType();
1331 }
Douglas Gregora481ec42010-05-23 19:57:01 +00001332 // Prohibit the use of VLAs during template argument deduction.
1333 else if (isSFINAEContext()) {
1334 Diag(Loc, diag::err_vla_in_sfinae);
1335 return QualType();
1336 }
Douglas Gregor0fddb972010-05-22 16:17:30 +00001337 // Just extwarn about VLAs.
1338 else
1339 Diag(Loc, diag::ext_vla);
1340 } else if (ASM != ArrayType::Normal || Quals != 0)
Douglas Gregor043cad22009-09-11 00:18:58 +00001341 Diag(Loc,
1342 getLangOptions().CPlusPlus? diag::err_c99_array_usage_cxx
1343 : diag::ext_c99_array_usage);
Douglas Gregorcd281c32009-02-28 00:25:32 +00001344 }
1345
1346 return T;
1347}
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001348
1349/// \brief Build an ext-vector type.
1350///
1351/// Run the required checks for the extended vector type.
John McCall9ae2f072010-08-23 23:25:46 +00001352QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize,
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001353 SourceLocation AttrLoc) {
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001354 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1355 // in conjunction with complex types (pointers, arrays, functions, etc.).
Mike Stump1eb44332009-09-09 15:08:12 +00001356 if (!T->isDependentType() &&
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001357 !T->isIntegerType() && !T->isRealFloatingType()) {
1358 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
1359 return QualType();
1360 }
1361
John McCall9ae2f072010-08-23 23:25:46 +00001362 if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) {
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001363 llvm::APSInt vecSize(32);
John McCall9ae2f072010-08-23 23:25:46 +00001364 if (!ArraySize->isIntegerConstantExpr(vecSize, Context)) {
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001365 Diag(AttrLoc, diag::err_attribute_argument_not_int)
John McCall9ae2f072010-08-23 23:25:46 +00001366 << "ext_vector_type" << ArraySize->getSourceRange();
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001367 return QualType();
1368 }
Mike Stump1eb44332009-09-09 15:08:12 +00001369
1370 // unlike gcc's vector_size attribute, the size is specified as the
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001371 // number of elements, not the number of bytes.
Mike Stump1eb44332009-09-09 15:08:12 +00001372 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
1373
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001374 if (vectorSize == 0) {
1375 Diag(AttrLoc, diag::err_attribute_zero_size)
John McCall9ae2f072010-08-23 23:25:46 +00001376 << ArraySize->getSourceRange();
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001377 return QualType();
1378 }
Mike Stump1eb44332009-09-09 15:08:12 +00001379
Douglas Gregor4ac01402011-06-15 16:02:29 +00001380 return Context.getExtVectorType(T, vectorSize);
Mike Stump1eb44332009-09-09 15:08:12 +00001381 }
1382
John McCall9ae2f072010-08-23 23:25:46 +00001383 return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc);
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001384}
Mike Stump1eb44332009-09-09 15:08:12 +00001385
Douglas Gregor724651c2009-02-28 01:04:19 +00001386/// \brief Build a function type.
1387///
1388/// This routine checks the function type according to C++ rules and
1389/// under the assumption that the result type and parameter types have
1390/// just been instantiated from a template. It therefore duplicates
Douglas Gregor2943aed2009-03-03 04:44:36 +00001391/// some of the behavior of GetTypeForDeclarator, but in a much
Douglas Gregor724651c2009-02-28 01:04:19 +00001392/// simpler form that is only suitable for this narrow use case.
1393///
1394/// \param T The return type of the function.
1395///
1396/// \param ParamTypes The parameter types of the function. This array
1397/// will be modified to account for adjustments to the types of the
1398/// function parameters.
1399///
1400/// \param NumParamTypes The number of parameter types in ParamTypes.
1401///
1402/// \param Variadic Whether this is a variadic function type.
1403///
1404/// \param Quals The cvr-qualifiers to be applied to the function type.
1405///
1406/// \param Loc The location of the entity whose type involves this
1407/// function type or, if there is no such entity, the location of the
1408/// type that will have function type.
1409///
1410/// \param Entity The name of the entity that involves the function
1411/// type, if known.
1412///
1413/// \returns A suitable function type, if there are no
1414/// errors. Otherwise, returns a NULL type.
1415QualType Sema::BuildFunctionType(QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00001416 QualType *ParamTypes,
Douglas Gregor724651c2009-02-28 01:04:19 +00001417 unsigned NumParamTypes,
1418 bool Variadic, unsigned Quals,
Douglas Gregorc938c162011-01-26 05:01:58 +00001419 RefQualifierKind RefQualifier,
Eli Friedmanfa869542010-08-05 02:54:05 +00001420 SourceLocation Loc, DeclarationName Entity,
John McCalle23cf432010-12-14 08:05:40 +00001421 FunctionType::ExtInfo Info) {
Douglas Gregor724651c2009-02-28 01:04:19 +00001422 if (T->isArrayType() || T->isFunctionType()) {
Douglas Gregor58408bc2010-01-11 18:46:21 +00001423 Diag(Loc, diag::err_func_returning_array_function)
1424 << T->isFunctionType() << T;
Douglas Gregor724651c2009-02-28 01:04:19 +00001425 return QualType();
1426 }
Douglas Gregor5291c3c2010-07-13 08:18:22 +00001427
Douglas Gregor724651c2009-02-28 01:04:19 +00001428 bool Invalid = false;
1429 for (unsigned Idx = 0; Idx < NumParamTypes; ++Idx) {
Douglas Gregor79e6bd32011-07-12 04:42:08 +00001430 QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001431 if (ParamType->isVoidType()) {
Douglas Gregor724651c2009-02-28 01:04:19 +00001432 Diag(Loc, diag::err_param_with_void_type);
1433 Invalid = true;
1434 }
Douglas Gregorcd281c32009-02-28 00:25:32 +00001435
John McCall54e14c42009-10-22 22:37:11 +00001436 ParamTypes[Idx] = ParamType;
Douglas Gregor724651c2009-02-28 01:04:19 +00001437 }
1438
1439 if (Invalid)
1440 return QualType();
1441
John McCalle23cf432010-12-14 08:05:40 +00001442 FunctionProtoType::ExtProtoInfo EPI;
1443 EPI.Variadic = Variadic;
1444 EPI.TypeQuals = Quals;
Douglas Gregorc938c162011-01-26 05:01:58 +00001445 EPI.RefQualifier = RefQualifier;
John McCalle23cf432010-12-14 08:05:40 +00001446 EPI.ExtInfo = Info;
1447
1448 return Context.getFunctionType(T, ParamTypes, NumParamTypes, EPI);
Douglas Gregor724651c2009-02-28 01:04:19 +00001449}
Mike Stump1eb44332009-09-09 15:08:12 +00001450
Douglas Gregor949bf692009-06-09 22:17:39 +00001451/// \brief Build a member pointer type \c T Class::*.
1452///
1453/// \param T the type to which the member pointer refers.
1454/// \param Class the class type into which the member pointer points.
John McCall0953e762009-09-24 19:53:00 +00001455/// \param CVR Qualifiers applied to the member pointer type
Douglas Gregor949bf692009-06-09 22:17:39 +00001456/// \param Loc the location where this type begins
1457/// \param Entity the name of the entity that will have this member pointer type
1458///
1459/// \returns a member pointer type, if successful, or a NULL type if there was
1460/// an error.
Mike Stump1eb44332009-09-09 15:08:12 +00001461QualType Sema::BuildMemberPointerType(QualType T, QualType Class,
John McCall28654742010-06-05 06:41:15 +00001462 SourceLocation Loc,
Douglas Gregor949bf692009-06-09 22:17:39 +00001463 DeclarationName Entity) {
1464 // Verify that we're not building a pointer to pointer to function with
1465 // exception specification.
1466 if (CheckDistantExceptionSpec(T)) {
1467 Diag(Loc, diag::err_distant_exception_spec);
1468
1469 // FIXME: If we're doing this as part of template instantiation,
1470 // we should return immediately.
1471
1472 // Build the type anyway, but use the canonical type so that the
1473 // exception specifiers are stripped off.
1474 T = Context.getCanonicalType(T);
1475 }
1476
Sebastian Redl73780122010-06-09 21:19:43 +00001477 // C++ 8.3.3p3: A pointer to member shall not point to ... a member
Douglas Gregor949bf692009-06-09 22:17:39 +00001478 // with reference type, or "cv void."
1479 if (T->isReferenceType()) {
Anders Carlsson8d4655d2009-06-30 00:06:57 +00001480 Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
John McCallac406052009-10-30 00:37:20 +00001481 << (Entity? Entity.getAsString() : "type name") << T;
Douglas Gregor949bf692009-06-09 22:17:39 +00001482 return QualType();
1483 }
1484
1485 if (T->isVoidType()) {
1486 Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
1487 << (Entity? Entity.getAsString() : "type name");
1488 return QualType();
1489 }
1490
Douglas Gregor949bf692009-06-09 22:17:39 +00001491 if (!Class->isDependentType() && !Class->isRecordType()) {
1492 Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
1493 return QualType();
1494 }
1495
Charles Davisd18f9f92010-08-16 04:01:50 +00001496 // In the Microsoft ABI, the class is allowed to be an incomplete
1497 // type. In such cases, the compiler makes a worst-case assumption.
1498 // We make no such assumption right now, so emit an error if the
1499 // class isn't a complete type.
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001500 if (Context.getTargetInfo().getCXXABI() == CXXABI_Microsoft &&
Charles Davisd18f9f92010-08-16 04:01:50 +00001501 RequireCompleteType(Loc, Class, diag::err_incomplete_type))
1502 return QualType();
1503
John McCall28654742010-06-05 06:41:15 +00001504 return Context.getMemberPointerType(T, Class.getTypePtr());
Douglas Gregor949bf692009-06-09 22:17:39 +00001505}
Mike Stump1eb44332009-09-09 15:08:12 +00001506
Anders Carlsson9a917e42009-06-12 22:56:54 +00001507/// \brief Build a block pointer type.
1508///
1509/// \param T The type to which we'll be building a block pointer.
1510///
John McCall0953e762009-09-24 19:53:00 +00001511/// \param CVR The cvr-qualifiers to be applied to the block pointer type.
Anders Carlsson9a917e42009-06-12 22:56:54 +00001512///
1513/// \param Loc The location of the entity whose type involves this
1514/// block pointer type or, if there is no such entity, the location of the
1515/// type that will have block pointer type.
1516///
1517/// \param Entity The name of the entity that involves the block pointer
1518/// type, if known.
1519///
1520/// \returns A suitable block pointer type, if there are no
1521/// errors. Otherwise, returns a NULL type.
John McCall28654742010-06-05 06:41:15 +00001522QualType Sema::BuildBlockPointerType(QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00001523 SourceLocation Loc,
Anders Carlsson9a917e42009-06-12 22:56:54 +00001524 DeclarationName Entity) {
John McCall0953e762009-09-24 19:53:00 +00001525 if (!T->isFunctionType()) {
Anders Carlsson9a917e42009-06-12 22:56:54 +00001526 Diag(Loc, diag::err_nonfunction_block_type);
1527 return QualType();
1528 }
Mike Stump1eb44332009-09-09 15:08:12 +00001529
John McCall28654742010-06-05 06:41:15 +00001530 return Context.getBlockPointerType(T);
Anders Carlsson9a917e42009-06-12 22:56:54 +00001531}
1532
John McCallb3d87482010-08-24 05:47:05 +00001533QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) {
1534 QualType QT = Ty.get();
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001535 if (QT.isNull()) {
John McCalla93c9342009-12-07 02:54:59 +00001536 if (TInfo) *TInfo = 0;
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001537 return QualType();
1538 }
1539
John McCalla93c9342009-12-07 02:54:59 +00001540 TypeSourceInfo *DI = 0;
John McCallf4c73712011-01-19 06:33:43 +00001541 if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001542 QT = LIT->getType();
John McCalla93c9342009-12-07 02:54:59 +00001543 DI = LIT->getTypeSourceInfo();
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001544 }
Mike Stump1eb44332009-09-09 15:08:12 +00001545
John McCalla93c9342009-12-07 02:54:59 +00001546 if (TInfo) *TInfo = DI;
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001547 return QT;
1548}
1549
Argyrios Kyrtzidisa8349f52011-07-01 22:23:05 +00001550static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
1551 Qualifiers::ObjCLifetime ownership,
1552 unsigned chunkIndex);
1553
John McCallf85e1932011-06-15 23:02:42 +00001554/// Given that this is the declaration of a parameter under ARC,
1555/// attempt to infer attributes and such for pointer-to-whatever
1556/// types.
1557static void inferARCWriteback(TypeProcessingState &state,
1558 QualType &declSpecType) {
1559 Sema &S = state.getSema();
1560 Declarator &declarator = state.getDeclarator();
1561
1562 // TODO: should we care about decl qualifiers?
1563
1564 // Check whether the declarator has the expected form. We walk
1565 // from the inside out in order to make the block logic work.
1566 unsigned outermostPointerIndex = 0;
1567 bool isBlockPointer = false;
1568 unsigned numPointers = 0;
1569 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
1570 unsigned chunkIndex = i;
1571 DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex);
1572 switch (chunk.Kind) {
1573 case DeclaratorChunk::Paren:
1574 // Ignore parens.
1575 break;
1576
1577 case DeclaratorChunk::Reference:
1578 case DeclaratorChunk::Pointer:
1579 // Count the number of pointers. Treat references
1580 // interchangeably as pointers; if they're mis-ordered, normal
1581 // type building will discover that.
1582 outermostPointerIndex = chunkIndex;
1583 numPointers++;
1584 break;
1585
1586 case DeclaratorChunk::BlockPointer:
1587 // If we have a pointer to block pointer, that's an acceptable
1588 // indirect reference; anything else is not an application of
1589 // the rules.
1590 if (numPointers != 1) return;
1591 numPointers++;
1592 outermostPointerIndex = chunkIndex;
1593 isBlockPointer = true;
1594
1595 // We don't care about pointer structure in return values here.
1596 goto done;
1597
1598 case DeclaratorChunk::Array: // suppress if written (id[])?
1599 case DeclaratorChunk::Function:
1600 case DeclaratorChunk::MemberPointer:
1601 return;
1602 }
1603 }
1604 done:
1605
1606 // If we have *one* pointer, then we want to throw the qualifier on
1607 // the declaration-specifiers, which means that it needs to be a
1608 // retainable object type.
1609 if (numPointers == 1) {
1610 // If it's not a retainable object type, the rule doesn't apply.
1611 if (!declSpecType->isObjCRetainableType()) return;
1612
1613 // If it already has lifetime, don't do anything.
1614 if (declSpecType.getObjCLifetime()) return;
1615
1616 // Otherwise, modify the type in-place.
1617 Qualifiers qs;
1618
1619 if (declSpecType->isObjCARCImplicitlyUnretainedType())
1620 qs.addObjCLifetime(Qualifiers::OCL_ExplicitNone);
1621 else
1622 qs.addObjCLifetime(Qualifiers::OCL_Autoreleasing);
1623 declSpecType = S.Context.getQualifiedType(declSpecType, qs);
1624
1625 // If we have *two* pointers, then we want to throw the qualifier on
1626 // the outermost pointer.
1627 } else if (numPointers == 2) {
1628 // If we don't have a block pointer, we need to check whether the
1629 // declaration-specifiers gave us something that will turn into a
1630 // retainable object pointer after we slap the first pointer on it.
1631 if (!isBlockPointer && !declSpecType->isObjCObjectType())
1632 return;
1633
1634 // Look for an explicit lifetime attribute there.
1635 DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex);
Argyrios Kyrtzidis1c73dcb2011-07-01 22:23:03 +00001636 if (chunk.Kind != DeclaratorChunk::Pointer &&
1637 chunk.Kind != DeclaratorChunk::BlockPointer)
1638 return;
John McCallf85e1932011-06-15 23:02:42 +00001639 for (const AttributeList *attr = chunk.getAttrs(); attr;
1640 attr = attr->getNext())
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00001641 if (attr->getKind() == AttributeList::AT_objc_ownership)
John McCallf85e1932011-06-15 23:02:42 +00001642 return;
1643
Argyrios Kyrtzidisa8349f52011-07-01 22:23:05 +00001644 transferARCOwnershipToDeclaratorChunk(state, Qualifiers::OCL_Autoreleasing,
1645 outermostPointerIndex);
John McCallf85e1932011-06-15 23:02:42 +00001646
1647 // Any other number of pointers/references does not trigger the rule.
1648 } else return;
1649
1650 // TODO: mark whether we did this inference?
1651}
1652
Chandler Carruthd067c072011-02-23 18:51:59 +00001653static void DiagnoseIgnoredQualifiers(unsigned Quals,
1654 SourceLocation ConstQualLoc,
1655 SourceLocation VolatileQualLoc,
1656 SourceLocation RestrictQualLoc,
1657 Sema& S) {
1658 std::string QualStr;
1659 unsigned NumQuals = 0;
1660 SourceLocation Loc;
1661
1662 FixItHint ConstFixIt;
1663 FixItHint VolatileFixIt;
1664 FixItHint RestrictFixIt;
1665
Hans Wennborga08fcb82011-06-03 17:37:26 +00001666 const SourceManager &SM = S.getSourceManager();
1667
Chandler Carruthd067c072011-02-23 18:51:59 +00001668 // FIXME: The locations here are set kind of arbitrarily. It'd be nicer to
1669 // find a range and grow it to encompass all the qualifiers, regardless of
1670 // the order in which they textually appear.
1671 if (Quals & Qualifiers::Const) {
1672 ConstFixIt = FixItHint::CreateRemoval(ConstQualLoc);
Chandler Carruthd067c072011-02-23 18:51:59 +00001673 QualStr = "const";
Hans Wennborga08fcb82011-06-03 17:37:26 +00001674 ++NumQuals;
1675 if (!Loc.isValid() || SM.isBeforeInTranslationUnit(ConstQualLoc, Loc))
1676 Loc = ConstQualLoc;
Chandler Carruthd067c072011-02-23 18:51:59 +00001677 }
1678 if (Quals & Qualifiers::Volatile) {
1679 VolatileFixIt = FixItHint::CreateRemoval(VolatileQualLoc);
Hans Wennborga08fcb82011-06-03 17:37:26 +00001680 QualStr += (NumQuals == 0 ? "volatile" : " volatile");
Chandler Carruthd067c072011-02-23 18:51:59 +00001681 ++NumQuals;
Hans Wennborga08fcb82011-06-03 17:37:26 +00001682 if (!Loc.isValid() || SM.isBeforeInTranslationUnit(VolatileQualLoc, Loc))
1683 Loc = VolatileQualLoc;
Chandler Carruthd067c072011-02-23 18:51:59 +00001684 }
1685 if (Quals & Qualifiers::Restrict) {
1686 RestrictFixIt = FixItHint::CreateRemoval(RestrictQualLoc);
Hans Wennborga08fcb82011-06-03 17:37:26 +00001687 QualStr += (NumQuals == 0 ? "restrict" : " restrict");
Chandler Carruthd067c072011-02-23 18:51:59 +00001688 ++NumQuals;
Hans Wennborga08fcb82011-06-03 17:37:26 +00001689 if (!Loc.isValid() || SM.isBeforeInTranslationUnit(RestrictQualLoc, Loc))
1690 Loc = RestrictQualLoc;
Chandler Carruthd067c072011-02-23 18:51:59 +00001691 }
1692
1693 assert(NumQuals > 0 && "No known qualifiers?");
1694
1695 S.Diag(Loc, diag::warn_qual_return_type)
Hans Wennborga08fcb82011-06-03 17:37:26 +00001696 << QualStr << NumQuals << ConstFixIt << VolatileFixIt << RestrictFixIt;
Chandler Carruthd067c072011-02-23 18:51:59 +00001697}
1698
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001699static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state,
1700 TypeSourceInfo *&ReturnTypeInfo) {
1701 Sema &SemaRef = state.getSema();
1702 Declarator &D = state.getDeclarator();
Douglas Gregor930d8b52009-01-30 22:09:00 +00001703 QualType T;
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001704 ReturnTypeInfo = 0;
1705
1706 // The TagDecl owned by the DeclSpec.
Argyrios Kyrtzidisd3880f82011-06-28 03:01:18 +00001707 TagDecl *OwnedTagDecl = 0;
John McCall711c52b2011-01-05 12:14:39 +00001708
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001709 switch (D.getName().getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001710 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001711 case UnqualifiedId::IK_OperatorFunctionId:
Sebastian Redl8999fe12011-03-14 18:08:30 +00001712 case UnqualifiedId::IK_Identifier:
Sean Hunt0486d742009-11-28 04:44:28 +00001713 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001714 case UnqualifiedId::IK_TemplateId:
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001715 T = ConvertDeclSpecToType(state);
Chris Lattner5db2bb12009-10-25 18:21:37 +00001716
Douglas Gregor591bd3c2010-02-08 22:07:33 +00001717 if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) {
Argyrios Kyrtzidisd3880f82011-06-28 03:01:18 +00001718 OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
Abramo Bagnara15987972011-03-08 22:33:38 +00001719 // Owned declaration is embedded in declarator.
Argyrios Kyrtzidisd3880f82011-06-28 03:01:18 +00001720 OwnedTagDecl->setEmbeddedInDeclarator(true);
Douglas Gregor591bd3c2010-02-08 22:07:33 +00001721 }
Douglas Gregor930d8b52009-01-30 22:09:00 +00001722 break;
1723
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001724 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00001725 case UnqualifiedId::IK_ConstructorTemplateId:
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001726 case UnqualifiedId::IK_DestructorName:
Douglas Gregor930d8b52009-01-30 22:09:00 +00001727 // Constructors and destructors don't have return types. Use
Douglas Gregor48026d22010-01-11 18:40:55 +00001728 // "void" instead.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001729 T = SemaRef.Context.VoidTy;
Douglas Gregor930d8b52009-01-30 22:09:00 +00001730 break;
Douglas Gregor48026d22010-01-11 18:40:55 +00001731
1732 case UnqualifiedId::IK_ConversionFunctionId:
1733 // The result type of a conversion function is the type that it
1734 // converts to.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001735 T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId,
1736 &ReturnTypeInfo);
Douglas Gregor48026d22010-01-11 18:40:55 +00001737 break;
Douglas Gregor930d8b52009-01-30 22:09:00 +00001738 }
Douglas Gregordab60ad2010-10-01 18:44:50 +00001739
John McCall711c52b2011-01-05 12:14:39 +00001740 if (D.getAttributes())
1741 distributeTypeAttrsFromDeclarator(state, T);
1742
Richard Smithe7397c62011-02-22 00:36:53 +00001743 // C++0x [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context.
Richard Smith8110f042011-02-22 01:22:29 +00001744 // In C++0x, a function declarator using 'auto' must have a trailing return
1745 // type (this is checked later) and we can skip this. In other languages
1746 // using auto, we need to check regardless.
Richard Smith34b41d92011-02-20 03:19:35 +00001747 if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto &&
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001748 (!SemaRef.getLangOptions().CPlusPlus0x || !D.isFunctionDeclarator())) {
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001749 int Error = -1;
Mike Stump1eb44332009-09-09 15:08:12 +00001750
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001751 switch (D.getContext()) {
1752 case Declarator::KNRTypeListContext:
1753 assert(0 && "K&R type lists aren't allowed in C++");
1754 break;
John McCallc05a94b2011-03-23 23:43:04 +00001755 case Declarator::ObjCPrototypeContext:
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001756 case Declarator::PrototypeContext:
1757 Error = 0; // Function prototype
1758 break;
1759 case Declarator::MemberContext:
Richard Smith7a614d82011-06-11 17:19:42 +00001760 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)
1761 break;
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001762 switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001763 case TTK_Enum: assert(0 && "unhandled tag kind"); break;
1764 case TTK_Struct: Error = 1; /* Struct member */ break;
1765 case TTK_Union: Error = 2; /* Union member */ break;
1766 case TTK_Class: Error = 3; /* Class member */ break;
Mike Stump1eb44332009-09-09 15:08:12 +00001767 }
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001768 break;
1769 case Declarator::CXXCatchContext:
Argyrios Kyrtzidis17b63992011-07-01 22:22:40 +00001770 case Declarator::ObjCCatchContext:
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001771 Error = 4; // Exception declaration
1772 break;
1773 case Declarator::TemplateParamContext:
1774 Error = 5; // Template parameter
1775 break;
1776 case Declarator::BlockLiteralContext:
Richard Smith34b41d92011-02-20 03:19:35 +00001777 Error = 6; // Block literal
1778 break;
1779 case Declarator::TemplateTypeArgContext:
1780 Error = 7; // Template type argument
1781 break;
Richard Smith162e1c12011-04-15 14:24:37 +00001782 case Declarator::AliasDeclContext:
Richard Smith3e4c6c42011-05-05 21:57:07 +00001783 case Declarator::AliasTemplateContext:
Richard Smith162e1c12011-04-15 14:24:37 +00001784 Error = 9; // Type alias
1785 break;
Richard Smith34b41d92011-02-20 03:19:35 +00001786 case Declarator::TypeNameContext:
Argyrios Kyrtzidis0b8c98f2011-06-28 03:01:23 +00001787 Error = 11; // Generic
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001788 break;
1789 case Declarator::FileContext:
1790 case Declarator::BlockContext:
1791 case Declarator::ForContext:
1792 case Declarator::ConditionContext:
Argyrios Kyrtzidis0b8c98f2011-06-28 03:01:23 +00001793 case Declarator::CXXNewContext:
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001794 break;
1795 }
1796
Richard Smithddc83f92011-02-21 23:18:00 +00001797 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
1798 Error = 8;
1799
Richard Smith8110f042011-02-22 01:22:29 +00001800 // In Objective-C it is an error to use 'auto' on a function declarator.
1801 if (D.isFunctionDeclarator())
Richard Smith162e1c12011-04-15 14:24:37 +00001802 Error = 10;
Richard Smith8110f042011-02-22 01:22:29 +00001803
Richard Smithe7397c62011-02-22 00:36:53 +00001804 // C++0x [dcl.spec.auto]p2: 'auto' is always fine if the declarator
1805 // contains a trailing return type. That is only legal at the outermost
1806 // level. Check all declarator chunks (outermost first) anyway, to give
1807 // better diagnostics.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001808 if (SemaRef.getLangOptions().CPlusPlus0x && Error != -1) {
Richard Smithe7397c62011-02-22 00:36:53 +00001809 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
1810 unsigned chunkIndex = e - i - 1;
1811 state.setCurrentChunkIndex(chunkIndex);
1812 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
1813 if (DeclType.Kind == DeclaratorChunk::Function) {
1814 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
1815 if (FTI.TrailingReturnType) {
1816 Error = -1;
1817 break;
1818 }
1819 }
1820 }
1821 }
1822
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001823 if (Error != -1) {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001824 SemaRef.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
1825 diag::err_auto_not_allowed)
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001826 << Error;
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001827 T = SemaRef.Context.IntTy;
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001828 D.setInvalidType(true);
1829 }
1830 }
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001831
1832 if (SemaRef.getLangOptions().CPlusPlus &&
1833 OwnedTagDecl && OwnedTagDecl->isDefinition()) {
1834 // Check the contexts where C++ forbids the declaration of a new class
1835 // or enumeration in a type-specifier-seq.
1836 switch (D.getContext()) {
1837 case Declarator::FileContext:
1838 case Declarator::MemberContext:
1839 case Declarator::BlockContext:
1840 case Declarator::ForContext:
1841 case Declarator::BlockLiteralContext:
1842 // C++0x [dcl.type]p3:
1843 // A type-specifier-seq shall not define a class or enumeration unless
1844 // it appears in the type-id of an alias-declaration (7.1.3) that is not
1845 // the declaration of a template-declaration.
1846 case Declarator::AliasDeclContext:
1847 break;
1848 case Declarator::AliasTemplateContext:
1849 SemaRef.Diag(OwnedTagDecl->getLocation(),
1850 diag::err_type_defined_in_alias_template)
1851 << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
1852 break;
1853 case Declarator::TypeNameContext:
1854 case Declarator::TemplateParamContext:
1855 case Declarator::CXXNewContext:
1856 case Declarator::CXXCatchContext:
1857 case Declarator::ObjCCatchContext:
1858 case Declarator::TemplateTypeArgContext:
1859 SemaRef.Diag(OwnedTagDecl->getLocation(),
1860 diag::err_type_defined_in_type_specifier)
1861 << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
1862 break;
1863 case Declarator::PrototypeContext:
1864 case Declarator::ObjCPrototypeContext:
1865 case Declarator::KNRTypeListContext:
1866 // C++ [dcl.fct]p6:
1867 // Types shall not be defined in return or parameter types.
1868 SemaRef.Diag(OwnedTagDecl->getLocation(),
1869 diag::err_type_defined_in_param_type)
1870 << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
1871 break;
1872 case Declarator::ConditionContext:
1873 // C++ 6.4p2:
1874 // The type-specifier-seq shall not contain typedef and shall not declare
1875 // a new class or enumeration.
1876 SemaRef.Diag(OwnedTagDecl->getLocation(),
1877 diag::err_type_defined_in_condition);
1878 break;
1879 }
1880 }
1881
1882 return T;
1883}
1884
1885static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
1886 QualType declSpecType,
1887 TypeSourceInfo *TInfo) {
1888
1889 QualType T = declSpecType;
1890 Declarator &D = state.getDeclarator();
1891 Sema &S = state.getSema();
1892 ASTContext &Context = S.Context;
1893 const LangOptions &LangOpts = S.getLangOptions();
1894
1895 bool ImplicitlyNoexcept = false;
1896 if (D.getName().getKind() == UnqualifiedId::IK_OperatorFunctionId &&
1897 LangOpts.CPlusPlus0x) {
1898 OverloadedOperatorKind OO = D.getName().OperatorFunctionId.Operator;
1899 /// In C++0x, deallocation functions (normal and array operator delete)
1900 /// are implicitly noexcept.
1901 if (OO == OO_Delete || OO == OO_Array_Delete)
1902 ImplicitlyNoexcept = true;
1903 }
Richard Smith34b41d92011-02-20 03:19:35 +00001904
Douglas Gregorcd281c32009-02-28 00:25:32 +00001905 // The name we're declaring, if any.
1906 DeclarationName Name;
1907 if (D.getIdentifier())
1908 Name = D.getIdentifier();
Mike Stump1eb44332009-09-09 15:08:12 +00001909
Richard Smith162e1c12011-04-15 14:24:37 +00001910 // Does this declaration declare a typedef-name?
1911 bool IsTypedefName =
1912 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef ||
Richard Smith3e4c6c42011-05-05 21:57:07 +00001913 D.getContext() == Declarator::AliasDeclContext ||
1914 D.getContext() == Declarator::AliasTemplateContext;
Richard Smith162e1c12011-04-15 14:24:37 +00001915
Mike Stump98eb8a72009-02-04 22:31:32 +00001916 // Walk the DeclTypeInfo, building the recursive type as we go.
1917 // DeclTypeInfos are ordered from the identifier out, which is
1918 // opposite of what we want :).
Sebastian Redl8ce35b02009-10-25 21:45:37 +00001919 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
John McCall711c52b2011-01-05 12:14:39 +00001920 unsigned chunkIndex = e - i - 1;
1921 state.setCurrentChunkIndex(chunkIndex);
1922 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001923 switch (DeclType.Kind) {
1924 default: assert(0 && "Unknown decltype!");
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001925 case DeclaratorChunk::Paren:
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001926 T = S.BuildParenType(T);
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001927 break;
Steve Naroff5618bd42008-08-27 16:04:49 +00001928 case DeclaratorChunk::BlockPointer:
Chris Lattner9af55002009-03-27 04:18:06 +00001929 // If blocks are disabled, emit an error.
1930 if (!LangOpts.Blocks)
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001931 S.Diag(DeclType.Loc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +00001932
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001933 T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name);
John McCall28654742010-06-05 06:41:15 +00001934 if (DeclType.Cls.TypeQuals)
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001935 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals);
Steve Naroff5618bd42008-08-27 16:04:49 +00001936 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001937 case DeclaratorChunk::Pointer:
Sebastian Redl6a7330c2009-05-29 15:01:05 +00001938 // Verify that we're not building a pointer to pointer to function with
1939 // exception specification.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001940 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
1941 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
Sebastian Redl6a7330c2009-05-29 15:01:05 +00001942 D.setInvalidType(true);
1943 // Build the type anyway.
1944 }
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001945 if (LangOpts.ObjC1 && T->getAs<ObjCObjectType>()) {
John McCallc12c5bb2010-05-15 11:32:37 +00001946 T = Context.getObjCObjectPointerType(T);
John McCall28654742010-06-05 06:41:15 +00001947 if (DeclType.Ptr.TypeQuals)
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001948 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
Steve Naroff14108da2009-07-10 23:34:53 +00001949 break;
1950 }
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001951 T = S.BuildPointerType(T, DeclType.Loc, Name);
John McCall28654742010-06-05 06:41:15 +00001952 if (DeclType.Ptr.TypeQuals)
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001953 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
John McCall711c52b2011-01-05 12:14:39 +00001954
Reid Spencer5f016e22007-07-11 17:01:13 +00001955 break;
John McCall0953e762009-09-24 19:53:00 +00001956 case DeclaratorChunk::Reference: {
Sebastian Redl6a7330c2009-05-29 15:01:05 +00001957 // Verify that we're not building a reference to pointer to function with
1958 // exception specification.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001959 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
1960 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
Sebastian Redl6a7330c2009-05-29 15:01:05 +00001961 D.setInvalidType(true);
1962 // Build the type anyway.
1963 }
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001964 T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name);
John McCall28654742010-06-05 06:41:15 +00001965
1966 Qualifiers Quals;
1967 if (DeclType.Ref.HasRestrict)
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001968 T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict);
Reid Spencer5f016e22007-07-11 17:01:13 +00001969 break;
John McCall0953e762009-09-24 19:53:00 +00001970 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001971 case DeclaratorChunk::Array: {
Sebastian Redl6a7330c2009-05-29 15:01:05 +00001972 // Verify that we're not building an array of pointers to function with
1973 // exception specification.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001974 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
1975 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
Sebastian Redl6a7330c2009-05-29 15:01:05 +00001976 D.setInvalidType(true);
1977 // Build the type anyway.
1978 }
Chris Lattnerfd89bc82008-04-02 01:05:10 +00001979 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
Chris Lattner94f81fd2007-08-28 16:54:00 +00001980 Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
Reid Spencer5f016e22007-07-11 17:01:13 +00001981 ArrayType::ArraySizeModifier ASM;
1982 if (ATI.isStar)
1983 ASM = ArrayType::Star;
1984 else if (ATI.hasStatic)
1985 ASM = ArrayType::Static;
1986 else
1987 ASM = ArrayType::Normal;
John McCallc05a94b2011-03-23 23:43:04 +00001988 if (ASM == ArrayType::Star && !D.isPrototypeContext()) {
Eli Friedmanf91f5c82009-04-26 21:57:51 +00001989 // FIXME: This check isn't quite right: it allows star in prototypes
1990 // for function definitions, and disallows some edge cases detailed
1991 // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001992 S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
Eli Friedmanf91f5c82009-04-26 21:57:51 +00001993 ASM = ArrayType::Normal;
1994 D.setInvalidType(true);
1995 }
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001996 T = S.BuildArrayType(T, ASM, ArraySize,
1997 Qualifiers::fromCVRMask(ATI.TypeQuals),
1998 SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
Reid Spencer5f016e22007-07-11 17:01:13 +00001999 break;
2000 }
Sebastian Redlf30208a2009-01-24 21:16:55 +00002001 case DeclaratorChunk::Function: {
Reid Spencer5f016e22007-07-11 17:01:13 +00002002 // If the function declarator has a prototype (i.e. it is not () and
2003 // does not have a K&R-style identifier list), then the arguments are part
2004 // of the type, otherwise the argument list is ().
2005 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
Sebastian Redl3cc97262009-05-31 11:47:27 +00002006
Richard Smithe7397c62011-02-22 00:36:53 +00002007 // Check for auto functions and trailing return type and adjust the
2008 // return type accordingly.
2009 if (!D.isInvalidType()) {
2010 // trailing-return-type is only required if we're declaring a function,
2011 // and not, for instance, a pointer to a function.
2012 if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto &&
2013 !FTI.TrailingReturnType && chunkIndex == 0) {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002014 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
Richard Smithe7397c62011-02-22 00:36:53 +00002015 diag::err_auto_missing_trailing_return);
2016 T = Context.IntTy;
2017 D.setInvalidType(true);
2018 } else if (FTI.TrailingReturnType) {
2019 // T must be exactly 'auto' at this point. See CWG issue 681.
2020 if (isa<ParenType>(T)) {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002021 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
Richard Smithe7397c62011-02-22 00:36:53 +00002022 diag::err_trailing_return_in_parens)
2023 << T << D.getDeclSpec().getSourceRange();
2024 D.setInvalidType(true);
2025 } else if (T.hasQualifiers() || !isa<AutoType>(T)) {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002026 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
Richard Smithe7397c62011-02-22 00:36:53 +00002027 diag::err_trailing_return_without_auto)
2028 << T << D.getDeclSpec().getSourceRange();
2029 D.setInvalidType(true);
2030 }
2031
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002032 T = S.GetTypeFromParser(
Richard Smithe7397c62011-02-22 00:36:53 +00002033 ParsedType::getFromOpaquePtr(FTI.TrailingReturnType),
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002034 &TInfo);
Richard Smithe7397c62011-02-22 00:36:53 +00002035 }
2036 }
2037
Chris Lattnercd881292007-12-19 05:31:29 +00002038 // C99 6.7.5.3p1: The return type may not be a function or array type.
Douglas Gregor58408bc2010-01-11 18:46:21 +00002039 // For conversion functions, we'll diagnose this particular error later.
Douglas Gregor48026d22010-01-11 18:40:55 +00002040 if ((T->isArrayType() || T->isFunctionType()) &&
2041 (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId)) {
Argyrios Kyrtzidis98650442011-01-25 23:16:33 +00002042 unsigned diagID = diag::err_func_returning_array_function;
Argyrios Kyrtzidisa4356ad2011-01-26 01:26:44 +00002043 // Last processing chunk in block context means this function chunk
2044 // represents the block.
2045 if (chunkIndex == 0 &&
2046 D.getContext() == Declarator::BlockLiteralContext)
Argyrios Kyrtzidis98650442011-01-25 23:16:33 +00002047 diagID = diag::err_block_returning_array_function;
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002048 S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T;
Chris Lattnercd881292007-12-19 05:31:29 +00002049 T = Context.IntTy;
2050 D.setInvalidType(true);
2051 }
Sebastian Redl465226e2009-05-27 22:11:52 +00002052
Douglas Gregor5291c3c2010-07-13 08:18:22 +00002053 // cv-qualifiers on return types are pointless except when the type is a
2054 // class type in C++.
Douglas Gregorfff95132011-03-01 17:04:42 +00002055 if (isa<PointerType>(T) && T.getLocalCVRQualifiers() &&
Rafael Espindola1e153942011-03-11 04:56:58 +00002056 (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId) &&
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002057 (!LangOpts.CPlusPlus || !T->isDependentType())) {
Chandler Carruthd067c072011-02-23 18:51:59 +00002058 assert(chunkIndex + 1 < e && "No DeclaratorChunk for the return type?");
2059 DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1);
2060 assert(ReturnTypeChunk.Kind == DeclaratorChunk::Pointer);
2061
2062 DeclaratorChunk::PointerTypeInfo &PTI = ReturnTypeChunk.Ptr;
2063
2064 DiagnoseIgnoredQualifiers(PTI.TypeQuals,
2065 SourceLocation::getFromRawEncoding(PTI.ConstQualLoc),
2066 SourceLocation::getFromRawEncoding(PTI.VolatileQualLoc),
2067 SourceLocation::getFromRawEncoding(PTI.RestrictQualLoc),
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002068 S);
Chandler Carruthd067c072011-02-23 18:51:59 +00002069
2070 } else if (T.getCVRQualifiers() && D.getDeclSpec().getTypeQualifiers() &&
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002071 (!LangOpts.CPlusPlus ||
Douglas Gregor5291c3c2010-07-13 08:18:22 +00002072 (!T->isDependentType() && !T->isRecordType()))) {
Chandler Carruthd067c072011-02-23 18:51:59 +00002073
2074 DiagnoseIgnoredQualifiers(D.getDeclSpec().getTypeQualifiers(),
2075 D.getDeclSpec().getConstSpecLoc(),
2076 D.getDeclSpec().getVolatileSpecLoc(),
2077 D.getDeclSpec().getRestrictSpecLoc(),
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002078 S);
Douglas Gregor5291c3c2010-07-13 08:18:22 +00002079 }
Chandler Carruthd067c072011-02-23 18:51:59 +00002080
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002081 if (LangOpts.CPlusPlus && D.getDeclSpec().isTypeSpecOwned()) {
Douglas Gregor402abb52009-05-28 23:31:59 +00002082 // C++ [dcl.fct]p6:
2083 // Types shall not be defined in return or parameter types.
John McCallb3d87482010-08-24 05:47:05 +00002084 TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
Douglas Gregor402abb52009-05-28 23:31:59 +00002085 if (Tag->isDefinition())
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002086 S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
Douglas Gregor402abb52009-05-28 23:31:59 +00002087 << Context.getTypeDeclType(Tag);
2088 }
2089
Sebastian Redl3cc97262009-05-31 11:47:27 +00002090 // Exception specs are not allowed in typedefs. Complain, but add it
2091 // anyway.
Richard Smith162e1c12011-04-15 14:24:37 +00002092 if (IsTypedefName && FTI.getExceptionSpecType())
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002093 S.Diag(FTI.getExceptionSpecLoc(), diag::err_exception_spec_in_typedef)
Richard Smith3e4c6c42011-05-05 21:57:07 +00002094 << (D.getContext() == Declarator::AliasDeclContext ||
2095 D.getContext() == Declarator::AliasTemplateContext);
Sebastian Redl3cc97262009-05-31 11:47:27 +00002096
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002097 if (!FTI.NumArgs && !FTI.isVariadic && !LangOpts.CPlusPlus) {
John McCall28654742010-06-05 06:41:15 +00002098 // Simple void foo(), where the incoming T is the result type.
2099 T = Context.getFunctionNoProtoType(T);
2100 } else {
2101 // We allow a zero-parameter variadic function in C if the
2102 // function is marked with the "overloadable" attribute. Scan
2103 // for this attribute now.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002104 if (!FTI.NumArgs && FTI.isVariadic && !LangOpts.CPlusPlus) {
Douglas Gregor965acbb2009-02-18 07:07:28 +00002105 bool Overloadable = false;
2106 for (const AttributeList *Attrs = D.getAttributes();
2107 Attrs; Attrs = Attrs->getNext()) {
2108 if (Attrs->getKind() == AttributeList::AT_overloadable) {
2109 Overloadable = true;
2110 break;
2111 }
2112 }
2113
2114 if (!Overloadable)
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002115 S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_arg);
Argyrios Kyrtzidisc6f73452008-10-16 17:31:08 +00002116 }
John McCall28654742010-06-05 06:41:15 +00002117
2118 if (FTI.NumArgs && FTI.ArgInfo[0].Param == 0) {
Chris Lattner788b0fd2010-06-23 06:00:24 +00002119 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function
2120 // definition.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002121 S.Diag(FTI.ArgInfo[0].IdentLoc, diag::err_ident_list_in_fn_declaration);
John McCall28654742010-06-05 06:41:15 +00002122 D.setInvalidType(true);
2123 break;
2124 }
2125
John McCalle23cf432010-12-14 08:05:40 +00002126 FunctionProtoType::ExtProtoInfo EPI;
2127 EPI.Variadic = FTI.isVariadic;
2128 EPI.TypeQuals = FTI.TypeQuals;
Douglas Gregorc938c162011-01-26 05:01:58 +00002129 EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None
2130 : FTI.RefQualifierIsLValueRef? RQ_LValue
2131 : RQ_RValue;
2132
Reid Spencer5f016e22007-07-11 17:01:13 +00002133 // Otherwise, we have a function with an argument list that is
2134 // potentially variadic.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002135 SmallVector<QualType, 16> ArgTys;
John McCall28654742010-06-05 06:41:15 +00002136 ArgTys.reserve(FTI.NumArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002137
Chris Lattner5f9e2722011-07-23 10:55:15 +00002138 SmallVector<bool, 16> ConsumedArguments;
John McCallf85e1932011-06-15 23:02:42 +00002139 ConsumedArguments.reserve(FTI.NumArgs);
2140 bool HasAnyConsumedArguments = false;
2141
Reid Spencer5f016e22007-07-11 17:01:13 +00002142 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
John McCalld226f652010-08-21 09:40:31 +00002143 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
Chris Lattner8123a952008-04-10 02:22:51 +00002144 QualType ArgTy = Param->getType();
Chris Lattner78c75fb2007-07-21 05:30:18 +00002145 assert(!ArgTy.isNull() && "Couldn't parse type?");
Douglas Gregor2dc0e642009-03-23 23:06:20 +00002146
2147 // Adjust the parameter type.
Douglas Gregor79e6bd32011-07-12 04:42:08 +00002148 assert((ArgTy == Context.getAdjustedParameterType(ArgTy)) &&
2149 "Unadjusted type?");
Douglas Gregor2dc0e642009-03-23 23:06:20 +00002150
Reid Spencer5f016e22007-07-11 17:01:13 +00002151 // Look for 'void'. void is allowed only as a single argument to a
2152 // function with no other parameters (C99 6.7.5.3p10). We record
Douglas Gregor72564e72009-02-26 23:50:07 +00002153 // int(void) as a FunctionProtoType with an empty argument list.
Douglas Gregor2dc0e642009-03-23 23:06:20 +00002154 if (ArgTy->isVoidType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002155 // If this is something like 'float(int, void)', reject it. 'void'
2156 // is an incomplete type (C99 6.2.5p19) and function decls cannot
2157 // have arguments of incomplete type.
2158 if (FTI.NumArgs != 1 || FTI.isVariadic) {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002159 S.Diag(DeclType.Loc, diag::err_void_only_param);
Chris Lattner2ff54262007-07-21 05:18:12 +00002160 ArgTy = Context.IntTy;
Chris Lattner8123a952008-04-10 02:22:51 +00002161 Param->setType(ArgTy);
Chris Lattner2ff54262007-07-21 05:18:12 +00002162 } else if (FTI.ArgInfo[i].Ident) {
2163 // Reject, but continue to parse 'int(void abc)'.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002164 S.Diag(FTI.ArgInfo[i].IdentLoc,
Chris Lattner4565d4e2007-07-21 05:26:43 +00002165 diag::err_param_with_void_type);
Chris Lattner2ff54262007-07-21 05:18:12 +00002166 ArgTy = Context.IntTy;
Chris Lattner8123a952008-04-10 02:22:51 +00002167 Param->setType(ArgTy);
Chris Lattner2ff54262007-07-21 05:18:12 +00002168 } else {
2169 // Reject, but continue to parse 'float(const void)'.
John McCall0953e762009-09-24 19:53:00 +00002170 if (ArgTy.hasQualifiers())
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002171 S.Diag(DeclType.Loc, diag::err_void_param_qualified);
Mike Stump1eb44332009-09-09 15:08:12 +00002172
Chris Lattner2ff54262007-07-21 05:18:12 +00002173 // Do not add 'void' to the ArgTys list.
2174 break;
2175 }
Eli Friedmaneb4b7052008-08-25 21:31:01 +00002176 } else if (!FTI.hasPrototype) {
2177 if (ArgTy->isPromotableIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00002178 ArgTy = Context.getPromotedIntegerType(ArgTy);
John McCalleecf5fa2011-03-09 04:22:44 +00002179 Param->setKNRPromoted(true);
John McCall183700f2009-09-21 23:43:11 +00002180 } else if (const BuiltinType* BTy = ArgTy->getAs<BuiltinType>()) {
John McCalleecf5fa2011-03-09 04:22:44 +00002181 if (BTy->getKind() == BuiltinType::Float) {
Eli Friedmaneb4b7052008-08-25 21:31:01 +00002182 ArgTy = Context.DoubleTy;
John McCalleecf5fa2011-03-09 04:22:44 +00002183 Param->setKNRPromoted(true);
2184 }
Eli Friedmaneb4b7052008-08-25 21:31:01 +00002185 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002186 }
Fariborz Jahanian56a965c2010-09-08 21:36:35 +00002187
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002188 if (LangOpts.ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00002189 bool Consumed = Param->hasAttr<NSConsumedAttr>();
2190 ConsumedArguments.push_back(Consumed);
2191 HasAnyConsumedArguments |= Consumed;
2192 }
2193
John McCall54e14c42009-10-22 22:37:11 +00002194 ArgTys.push_back(ArgTy);
Reid Spencer5f016e22007-07-11 17:01:13 +00002195 }
Sebastian Redl465226e2009-05-27 22:11:52 +00002196
John McCallf85e1932011-06-15 23:02:42 +00002197 if (HasAnyConsumedArguments)
2198 EPI.ConsumedArguments = ConsumedArguments.data();
2199
Chris Lattner5f9e2722011-07-23 10:55:15 +00002200 SmallVector<QualType, 4> Exceptions;
Sebastian Redl8b5b4092011-03-06 10:52:04 +00002201 EPI.ExceptionSpecType = FTI.getExceptionSpecType();
2202 if (FTI.getExceptionSpecType() == EST_Dynamic) {
John McCalle23cf432010-12-14 08:05:40 +00002203 Exceptions.reserve(FTI.NumExceptions);
2204 for (unsigned ei = 0, ee = FTI.NumExceptions; ei != ee; ++ei) {
2205 // FIXME: Preserve type source info.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002206 QualType ET = S.GetTypeFromParser(FTI.Exceptions[ei].Ty);
John McCalle23cf432010-12-14 08:05:40 +00002207 // Check that the type is valid for an exception spec, and
2208 // drop it if not.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002209 if (!S.CheckSpecifiedExceptionType(ET, FTI.Exceptions[ei].Range))
John McCalle23cf432010-12-14 08:05:40 +00002210 Exceptions.push_back(ET);
2211 }
John McCall373920b2010-12-14 16:45:57 +00002212 EPI.NumExceptions = Exceptions.size();
John McCalle23cf432010-12-14 08:05:40 +00002213 EPI.Exceptions = Exceptions.data();
Sebastian Redl8b5b4092011-03-06 10:52:04 +00002214 } else if (FTI.getExceptionSpecType() == EST_ComputedNoexcept) {
Sebastian Redl60618fa2011-03-12 11:50:43 +00002215 // If an error occurred, there's no expression here.
2216 if (Expr *NoexceptExpr = FTI.NoexceptExpr) {
2217 assert((NoexceptExpr->isTypeDependent() ||
2218 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
2219 Context.BoolTy) &&
2220 "Parser should have made sure that the expression is boolean");
2221 SourceLocation ErrLoc;
2222 llvm::APSInt Dummy;
2223 if (!NoexceptExpr->isValueDependent() &&
2224 !NoexceptExpr->isIntegerConstantExpr(Dummy, Context, &ErrLoc,
2225 /*evaluated*/false))
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002226 S.Diag(ErrLoc, diag::err_noexcept_needs_constant_expression)
Sebastian Redl60618fa2011-03-12 11:50:43 +00002227 << NoexceptExpr->getSourceRange();
2228 else
2229 EPI.NoexceptExpr = NoexceptExpr;
2230 }
Sebastian Redl8999fe12011-03-14 18:08:30 +00002231 } else if (FTI.getExceptionSpecType() == EST_None &&
2232 ImplicitlyNoexcept && chunkIndex == 0) {
2233 // Only the outermost chunk is marked noexcept, of course.
2234 EPI.ExceptionSpecType = EST_BasicNoexcept;
Sebastian Redlef65f062009-05-29 18:02:33 +00002235 }
Sebastian Redl465226e2009-05-27 22:11:52 +00002236
John McCalle23cf432010-12-14 08:05:40 +00002237 T = Context.getFunctionType(T, ArgTys.data(), ArgTys.size(), EPI);
Reid Spencer5f016e22007-07-11 17:01:13 +00002238 }
John McCall04a67a62010-02-05 21:31:56 +00002239
Reid Spencer5f016e22007-07-11 17:01:13 +00002240 break;
2241 }
Sebastian Redlf30208a2009-01-24 21:16:55 +00002242 case DeclaratorChunk::MemberPointer:
2243 // The scope spec must refer to a class, or be dependent.
Abramo Bagnara7bd06762010-08-13 12:56:25 +00002244 CXXScopeSpec &SS = DeclType.Mem.Scope();
Sebastian Redlf30208a2009-01-24 21:16:55 +00002245 QualType ClsType;
Abramo Bagnara7bd06762010-08-13 12:56:25 +00002246 if (SS.isInvalid()) {
Jeffrey Yasskinedc28772010-04-07 23:29:58 +00002247 // Avoid emitting extra errors if we already errored on the scope.
2248 D.setInvalidType(true);
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002249 } else if (S.isDependentScopeSpecifier(SS) ||
2250 dyn_cast_or_null<CXXRecordDecl>(S.computeDeclContext(SS))) {
Mike Stump1eb44332009-09-09 15:08:12 +00002251 NestedNameSpecifier *NNS
Abramo Bagnara7bd06762010-08-13 12:56:25 +00002252 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
Douglas Gregor87c12c42009-11-04 16:49:01 +00002253 NestedNameSpecifier *NNSPrefix = NNS->getPrefix();
2254 switch (NNS->getKind()) {
2255 case NestedNameSpecifier::Identifier:
Abramo Bagnara7bd06762010-08-13 12:56:25 +00002256 ClsType = Context.getDependentNameType(ETK_None, NNSPrefix,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002257 NNS->getAsIdentifier());
Douglas Gregor87c12c42009-11-04 16:49:01 +00002258 break;
2259
2260 case NestedNameSpecifier::Namespace:
Douglas Gregor14aba762011-02-24 02:36:08 +00002261 case NestedNameSpecifier::NamespaceAlias:
Douglas Gregor87c12c42009-11-04 16:49:01 +00002262 case NestedNameSpecifier::Global:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002263 llvm_unreachable("Nested-name-specifier must name a type");
Douglas Gregor87c12c42009-11-04 16:49:01 +00002264 break;
Abramo Bagnara7bd06762010-08-13 12:56:25 +00002265
Douglas Gregor87c12c42009-11-04 16:49:01 +00002266 case NestedNameSpecifier::TypeSpec:
2267 case NestedNameSpecifier::TypeSpecWithTemplate:
2268 ClsType = QualType(NNS->getAsType(), 0);
Abramo Bagnara91ce2c42011-03-10 10:18:27 +00002269 // Note: if the NNS has a prefix and ClsType is a nondependent
2270 // TemplateSpecializationType, then the NNS prefix is NOT included
2271 // in ClsType; hence we wrap ClsType into an ElaboratedType.
2272 // NOTE: in particular, no wrap occurs if ClsType already is an
2273 // Elaborated, DependentName, or DependentTemplateSpecialization.
2274 if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType()))
Abramo Bagnara7bd06762010-08-13 12:56:25 +00002275 ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType);
Douglas Gregor87c12c42009-11-04 16:49:01 +00002276 break;
2277 }
Sebastian Redlf30208a2009-01-24 21:16:55 +00002278 } else {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002279 S.Diag(DeclType.Mem.Scope().getBeginLoc(),
Douglas Gregor949bf692009-06-09 22:17:39 +00002280 diag::err_illegal_decl_mempointer_in_nonclass)
2281 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
2282 << DeclType.Mem.Scope().getRange();
Sebastian Redlf30208a2009-01-24 21:16:55 +00002283 D.setInvalidType(true);
Sebastian Redlf30208a2009-01-24 21:16:55 +00002284 }
2285
Douglas Gregor949bf692009-06-09 22:17:39 +00002286 if (!ClsType.isNull())
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002287 T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc, D.getIdentifier());
Douglas Gregor949bf692009-06-09 22:17:39 +00002288 if (T.isNull()) {
2289 T = Context.IntTy;
Sebastian Redlf30208a2009-01-24 21:16:55 +00002290 D.setInvalidType(true);
John McCall28654742010-06-05 06:41:15 +00002291 } else if (DeclType.Mem.TypeQuals) {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002292 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals);
Sebastian Redlf30208a2009-01-24 21:16:55 +00002293 }
Sebastian Redlf30208a2009-01-24 21:16:55 +00002294 break;
2295 }
2296
Douglas Gregorcd281c32009-02-28 00:25:32 +00002297 if (T.isNull()) {
2298 D.setInvalidType(true);
2299 T = Context.IntTy;
2300 }
2301
Chris Lattnerc9b346d2008-06-29 00:50:08 +00002302 // See if there are any attributes on this declarator chunk.
John McCall711c52b2011-01-05 12:14:39 +00002303 if (AttributeList *attrs = const_cast<AttributeList*>(DeclType.getAttrs()))
2304 processTypeAttrs(state, T, false, attrs);
Reid Spencer5f016e22007-07-11 17:01:13 +00002305 }
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00002306
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002307 if (LangOpts.CPlusPlus && T->isFunctionType()) {
John McCall183700f2009-09-21 23:43:11 +00002308 const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
Chris Lattner778ed742009-10-25 17:36:50 +00002309 assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00002310
Douglas Gregor708f3b82010-10-14 22:03:51 +00002311 // C++ 8.3.5p4:
2312 // A cv-qualifier-seq shall only be part of the function type
2313 // for a nonstatic member function, the function type to which a pointer
2314 // to member refers, or the top-level function type of a function typedef
2315 // declaration.
Douglas Gregor683a81f2011-01-31 16:09:46 +00002316 //
2317 // Core issue 547 also allows cv-qualifiers on function types that are
2318 // top-level template type arguments.
John McCall613ef3d2010-10-19 01:54:45 +00002319 bool FreeFunction;
2320 if (!D.getCXXScopeSpec().isSet()) {
2321 FreeFunction = (D.getContext() != Declarator::MemberContext ||
2322 D.getDeclSpec().isFriendSpecified());
2323 } else {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002324 DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec());
John McCall613ef3d2010-10-19 01:54:45 +00002325 FreeFunction = (DC && !DC->isRecord());
2326 }
2327
Douglas Gregorc938c162011-01-26 05:01:58 +00002328 // C++0x [dcl.fct]p6:
2329 // A ref-qualifier shall only be part of the function type for a
2330 // non-static member function, the function type to which a pointer to
2331 // member refers, or the top-level function type of a function typedef
2332 // declaration.
2333 if ((FnTy->getTypeQuals() != 0 || FnTy->getRefQualifier()) &&
Douglas Gregor683a81f2011-01-31 16:09:46 +00002334 !(D.getContext() == Declarator::TemplateTypeArgContext &&
Richard Smith162e1c12011-04-15 14:24:37 +00002335 !D.isFunctionDeclarator()) && !IsTypedefName &&
Sebastian Redlc61bb202010-07-09 21:26:08 +00002336 (FreeFunction ||
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00002337 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)) {
Douglas Gregor683a81f2011-01-31 16:09:46 +00002338 if (D.getContext() == Declarator::TemplateTypeArgContext) {
2339 // Accept qualified function types as template type arguments as a GNU
2340 // extension. This is also the subject of C++ core issue 547.
2341 std::string Quals;
2342 if (FnTy->getTypeQuals() != 0)
2343 Quals = Qualifiers::fromCVRMask(FnTy->getTypeQuals()).getAsString();
2344
2345 switch (FnTy->getRefQualifier()) {
2346 case RQ_None:
2347 break;
2348
2349 case RQ_LValue:
2350 if (!Quals.empty())
2351 Quals += ' ';
2352 Quals += '&';
2353 break;
Douglas Gregorc938c162011-01-26 05:01:58 +00002354
Douglas Gregor683a81f2011-01-31 16:09:46 +00002355 case RQ_RValue:
2356 if (!Quals.empty())
2357 Quals += ' ';
2358 Quals += "&&";
2359 break;
Douglas Gregorc938c162011-01-26 05:01:58 +00002360 }
Douglas Gregor683a81f2011-01-31 16:09:46 +00002361
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002362 S.Diag(D.getIdentifierLoc(),
Douglas Gregor683a81f2011-01-31 16:09:46 +00002363 diag::ext_qualified_function_type_template_arg)
2364 << Quals;
2365 } else {
2366 if (FnTy->getTypeQuals() != 0) {
2367 if (D.isFunctionDeclarator())
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002368 S.Diag(D.getIdentifierLoc(),
Douglas Gregor683a81f2011-01-31 16:09:46 +00002369 diag::err_invalid_qualified_function_type);
2370 else
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002371 S.Diag(D.getIdentifierLoc(),
Douglas Gregor683a81f2011-01-31 16:09:46 +00002372 diag::err_invalid_qualified_typedef_function_type_use)
2373 << FreeFunction;
2374 }
2375
2376 if (FnTy->getRefQualifier()) {
2377 if (D.isFunctionDeclarator()) {
2378 SourceLocation Loc = D.getIdentifierLoc();
2379 for (unsigned I = 0, N = D.getNumTypeObjects(); I != N; ++I) {
2380 const DeclaratorChunk &Chunk = D.getTypeObject(N-I-1);
2381 if (Chunk.Kind == DeclaratorChunk::Function &&
2382 Chunk.Fun.hasRefQualifier()) {
2383 Loc = Chunk.Fun.getRefQualifierLoc();
2384 break;
2385 }
2386 }
2387
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002388 S.Diag(Loc, diag::err_invalid_ref_qualifier_function_type)
Douglas Gregor683a81f2011-01-31 16:09:46 +00002389 << (FnTy->getRefQualifier() == RQ_LValue)
2390 << FixItHint::CreateRemoval(Loc);
2391 } else {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002392 S.Diag(D.getIdentifierLoc(),
Douglas Gregor683a81f2011-01-31 16:09:46 +00002393 diag::err_invalid_ref_qualifier_typedef_function_type_use)
2394 << FreeFunction
2395 << (FnTy->getRefQualifier() == RQ_LValue);
2396 }
2397 }
2398
2399 // Strip the cv-qualifiers and ref-qualifiers from the type.
2400 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
2401 EPI.TypeQuals = 0;
2402 EPI.RefQualifier = RQ_None;
2403
2404 T = Context.getFunctionType(FnTy->getResultType(),
2405 FnTy->arg_type_begin(),
2406 FnTy->getNumArgs(), EPI);
Douglas Gregorc938c162011-01-26 05:01:58 +00002407 }
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00002408 }
2409 }
Mike Stump1eb44332009-09-09 15:08:12 +00002410
John McCall711c52b2011-01-05 12:14:39 +00002411 // Apply any undistributed attributes from the declarator.
2412 if (!T.isNull())
2413 if (AttributeList *attrs = D.getAttributes())
2414 processTypeAttrs(state, T, false, attrs);
2415
2416 // Diagnose any ignored type attributes.
2417 if (!T.isNull()) state.diagnoseIgnoredTypeAttrs(T);
2418
Peter Collingbourne148f1f72011-03-20 08:06:45 +00002419 // C++0x [dcl.constexpr]p9:
2420 // A constexpr specifier used in an object declaration declares the object
2421 // as const.
2422 if (D.getDeclSpec().isConstexprSpecified() && T->isObjectType()) {
Sebastian Redl73780122010-06-09 21:19:43 +00002423 T.addConst();
2424 }
2425
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002426 // If there was an ellipsis in the declarator, the declaration declares a
2427 // parameter pack whose type may be a pack expansion type.
2428 if (D.hasEllipsis() && !T.isNull()) {
2429 // C++0x [dcl.fct]p13:
2430 // A declarator-id or abstract-declarator containing an ellipsis shall
2431 // only be used in a parameter-declaration. Such a parameter-declaration
2432 // is a parameter pack (14.5.3). [...]
2433 switch (D.getContext()) {
2434 case Declarator::PrototypeContext:
2435 // C++0x [dcl.fct]p13:
2436 // [...] When it is part of a parameter-declaration-clause, the
2437 // parameter pack is a function parameter pack (14.5.3). The type T
2438 // of the declarator-id of the function parameter pack shall contain
2439 // a template parameter pack; each template parameter pack in T is
2440 // expanded by the function parameter pack.
2441 //
2442 // We represent function parameter packs as function parameters whose
2443 // type is a pack expansion.
2444 if (!T->containsUnexpandedParameterPack()) {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002445 S.Diag(D.getEllipsisLoc(),
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002446 diag::err_function_parameter_pack_without_parameter_packs)
2447 << T << D.getSourceRange();
2448 D.setEllipsisLoc(SourceLocation());
2449 } else {
Douglas Gregorcded4f62011-01-14 17:04:44 +00002450 T = Context.getPackExpansionType(T, llvm::Optional<unsigned>());
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002451 }
2452 break;
2453
2454 case Declarator::TemplateParamContext:
2455 // C++0x [temp.param]p15:
2456 // If a template-parameter is a [...] is a parameter-declaration that
2457 // declares a parameter pack (8.3.5), then the template-parameter is a
2458 // template parameter pack (14.5.3).
2459 //
2460 // Note: core issue 778 clarifies that, if there are any unexpanded
2461 // parameter packs in the type of the non-type template parameter, then
2462 // it expands those parameter packs.
2463 if (T->containsUnexpandedParameterPack())
Douglas Gregorcded4f62011-01-14 17:04:44 +00002464 T = Context.getPackExpansionType(T, llvm::Optional<unsigned>());
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002465 else if (!LangOpts.CPlusPlus0x)
2466 S.Diag(D.getEllipsisLoc(), diag::ext_variadic_templates);
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002467 break;
2468
2469 case Declarator::FileContext:
2470 case Declarator::KNRTypeListContext:
John McCallc05a94b2011-03-23 23:43:04 +00002471 case Declarator::ObjCPrototypeContext: // FIXME: special diagnostic here?
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002472 case Declarator::TypeNameContext:
Argyrios Kyrtzidis0b8c98f2011-06-28 03:01:23 +00002473 case Declarator::CXXNewContext:
Richard Smith162e1c12011-04-15 14:24:37 +00002474 case Declarator::AliasDeclContext:
Richard Smith3e4c6c42011-05-05 21:57:07 +00002475 case Declarator::AliasTemplateContext:
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002476 case Declarator::MemberContext:
2477 case Declarator::BlockContext:
2478 case Declarator::ForContext:
2479 case Declarator::ConditionContext:
2480 case Declarator::CXXCatchContext:
Argyrios Kyrtzidis17b63992011-07-01 22:22:40 +00002481 case Declarator::ObjCCatchContext:
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002482 case Declarator::BlockLiteralContext:
Douglas Gregor683a81f2011-01-31 16:09:46 +00002483 case Declarator::TemplateTypeArgContext:
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002484 // FIXME: We may want to allow parameter packs in block-literal contexts
2485 // in the future.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002486 S.Diag(D.getEllipsisLoc(), diag::err_ellipsis_in_declarator_not_parameter);
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002487 D.setEllipsisLoc(SourceLocation());
2488 break;
2489 }
2490 }
Richard Smithe7397c62011-02-22 00:36:53 +00002491
John McCallbf1a0282010-06-04 23:28:52 +00002492 if (T.isNull())
2493 return Context.getNullTypeSourceInfo();
2494 else if (D.isInvalidType())
2495 return Context.getTrivialTypeSourceInfo(T);
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +00002496
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002497 return S.GetTypeSourceInfoForDeclarator(D, T, TInfo);
2498}
2499
2500/// GetTypeForDeclarator - Convert the type for the specified
2501/// declarator to Type instances.
2502///
2503/// The result of this call will never be null, but the associated
2504/// type may be a null type if there's an unrecoverable error.
2505TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) {
2506 // Determine the type of the declarator. Not all forms of declarator
2507 // have a type.
2508
2509 TypeProcessingState state(*this, D);
2510
2511 TypeSourceInfo *ReturnTypeInfo = 0;
2512 QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
2513 if (T.isNull())
2514 return Context.getNullTypeSourceInfo();
2515
2516 if (D.isPrototypeContext() && getLangOptions().ObjCAutoRefCount)
2517 inferARCWriteback(state, T);
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +00002518
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002519 return GetFullTypeForDeclarator(state, T, ReturnTypeInfo);
Reid Spencer5f016e22007-07-11 17:01:13 +00002520}
2521
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00002522static void transferARCOwnershipToDeclSpec(Sema &S,
2523 QualType &declSpecTy,
2524 Qualifiers::ObjCLifetime ownership) {
2525 if (declSpecTy->isObjCRetainableType() &&
2526 declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) {
2527 Qualifiers qs;
2528 qs.addObjCLifetime(ownership);
2529 declSpecTy = S.Context.getQualifiedType(declSpecTy, qs);
2530 }
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00002531}
2532
2533static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
2534 Qualifiers::ObjCLifetime ownership,
2535 unsigned chunkIndex) {
2536 Sema &S = state.getSema();
2537 Declarator &D = state.getDeclarator();
2538
2539 // Look for an explicit lifetime attribute.
2540 DeclaratorChunk &chunk = D.getTypeObject(chunkIndex);
2541 for (const AttributeList *attr = chunk.getAttrs(); attr;
2542 attr = attr->getNext())
2543 if (attr->getKind() == AttributeList::AT_objc_ownership)
2544 return;
2545
2546 const char *attrStr = 0;
2547 switch (ownership) {
2548 case Qualifiers::OCL_None: llvm_unreachable("no ownership!"); break;
2549 case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break;
2550 case Qualifiers::OCL_Strong: attrStr = "strong"; break;
2551 case Qualifiers::OCL_Weak: attrStr = "weak"; break;
2552 case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break;
2553 }
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00002554
2555 // If there wasn't one, add one (with an invalid source location
2556 // so that we don't make an AttributedType for it).
2557 AttributeList *attr = D.getAttributePool()
2558 .create(&S.Context.Idents.get("objc_ownership"), SourceLocation(),
2559 /*scope*/ 0, SourceLocation(),
2560 &S.Context.Idents.get(attrStr), SourceLocation(),
2561 /*args*/ 0, 0,
2562 /*declspec*/ false, /*C++0x*/ false);
2563 spliceAttrIntoList(*attr, chunk.getAttrListRef());
2564
2565 // TODO: mark whether we did this inference?
2566}
2567
2568static void transferARCOwnership(TypeProcessingState &state,
2569 QualType &declSpecTy,
2570 Qualifiers::ObjCLifetime ownership) {
2571 Sema &S = state.getSema();
2572 Declarator &D = state.getDeclarator();
2573
2574 int inner = -1;
2575 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
2576 DeclaratorChunk &chunk = D.getTypeObject(i);
2577 switch (chunk.Kind) {
2578 case DeclaratorChunk::Paren:
2579 // Ignore parens.
2580 break;
2581
2582 case DeclaratorChunk::Array:
2583 case DeclaratorChunk::Reference:
2584 case DeclaratorChunk::Pointer:
2585 inner = i;
2586 break;
2587
2588 case DeclaratorChunk::BlockPointer:
2589 return transferARCOwnershipToDeclaratorChunk(state, ownership, i);
2590
2591 case DeclaratorChunk::Function:
2592 case DeclaratorChunk::MemberPointer:
2593 return;
2594 }
2595 }
2596
2597 if (inner == -1)
2598 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
2599
2600 DeclaratorChunk &chunk = D.getTypeObject(inner);
2601 if (chunk.Kind == DeclaratorChunk::Pointer) {
2602 if (declSpecTy->isObjCRetainableType())
2603 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
2604 if (declSpecTy->isObjCObjectType())
2605 return transferARCOwnershipToDeclaratorChunk(state, ownership, inner);
2606 } else {
2607 assert(chunk.Kind == DeclaratorChunk::Array ||
2608 chunk.Kind == DeclaratorChunk::Reference);
2609 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
2610 }
2611}
2612
2613TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) {
2614 TypeProcessingState state(*this, D);
2615
2616 TypeSourceInfo *ReturnTypeInfo = 0;
2617 QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
2618 if (declSpecTy.isNull())
2619 return Context.getNullTypeSourceInfo();
2620
2621 if (getLangOptions().ObjCAutoRefCount) {
2622 Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy);
2623 if (ownership != Qualifiers::OCL_None)
2624 transferARCOwnership(state, declSpecTy, ownership);
2625 }
2626
2627 return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo);
2628}
2629
John McCall14aa2172011-03-04 04:00:19 +00002630/// Map an AttributedType::Kind to an AttributeList::Kind.
2631static AttributeList::Kind getAttrListKind(AttributedType::Kind kind) {
2632 switch (kind) {
2633 case AttributedType::attr_address_space:
2634 return AttributeList::AT_address_space;
2635 case AttributedType::attr_regparm:
2636 return AttributeList::AT_regparm;
2637 case AttributedType::attr_vector_size:
2638 return AttributeList::AT_vector_size;
2639 case AttributedType::attr_neon_vector_type:
2640 return AttributeList::AT_neon_vector_type;
2641 case AttributedType::attr_neon_polyvector_type:
2642 return AttributeList::AT_neon_polyvector_type;
2643 case AttributedType::attr_objc_gc:
2644 return AttributeList::AT_objc_gc;
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00002645 case AttributedType::attr_objc_ownership:
2646 return AttributeList::AT_objc_ownership;
John McCall14aa2172011-03-04 04:00:19 +00002647 case AttributedType::attr_noreturn:
2648 return AttributeList::AT_noreturn;
2649 case AttributedType::attr_cdecl:
2650 return AttributeList::AT_cdecl;
2651 case AttributedType::attr_fastcall:
2652 return AttributeList::AT_fastcall;
2653 case AttributedType::attr_stdcall:
2654 return AttributeList::AT_stdcall;
2655 case AttributedType::attr_thiscall:
2656 return AttributeList::AT_thiscall;
2657 case AttributedType::attr_pascal:
2658 return AttributeList::AT_pascal;
Anton Korobeynikov414d8962011-04-14 20:06:49 +00002659 case AttributedType::attr_pcs:
2660 return AttributeList::AT_pcs;
John McCall14aa2172011-03-04 04:00:19 +00002661 }
2662 llvm_unreachable("unexpected attribute kind!");
2663 return AttributeList::Kind();
2664}
2665
2666static void fillAttributedTypeLoc(AttributedTypeLoc TL,
2667 const AttributeList *attrs) {
2668 AttributedType::Kind kind = TL.getAttrKind();
2669
2670 assert(attrs && "no type attributes in the expected location!");
2671 AttributeList::Kind parsedKind = getAttrListKind(kind);
2672 while (attrs->getKind() != parsedKind) {
2673 attrs = attrs->getNext();
2674 assert(attrs && "no matching attribute in expected location!");
2675 }
2676
2677 TL.setAttrNameLoc(attrs->getLoc());
2678 if (TL.hasAttrExprOperand())
2679 TL.setAttrExprOperand(attrs->getArg(0));
2680 else if (TL.hasAttrEnumOperand())
2681 TL.setAttrEnumOperandLoc(attrs->getParameterLoc());
2682
2683 // FIXME: preserve this information to here.
2684 if (TL.hasAttrOperand())
2685 TL.setAttrOperandParensRange(SourceRange());
2686}
2687
John McCall51bd8032009-10-18 01:05:36 +00002688namespace {
2689 class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
Douglas Gregorc21c7e92011-01-25 19:13:18 +00002690 ASTContext &Context;
John McCall51bd8032009-10-18 01:05:36 +00002691 const DeclSpec &DS;
Argyrios Kyrtzidisf352bdd2009-09-29 19:43:35 +00002692
John McCall51bd8032009-10-18 01:05:36 +00002693 public:
Douglas Gregorc21c7e92011-01-25 19:13:18 +00002694 TypeSpecLocFiller(ASTContext &Context, const DeclSpec &DS)
2695 : Context(Context), DS(DS) {}
Argyrios Kyrtzidisf352bdd2009-09-29 19:43:35 +00002696
John McCall14aa2172011-03-04 04:00:19 +00002697 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
2698 fillAttributedTypeLoc(TL, DS.getAttributes().getList());
2699 Visit(TL.getModifiedLoc());
2700 }
John McCall51bd8032009-10-18 01:05:36 +00002701 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
2702 Visit(TL.getUnqualifiedLoc());
2703 }
2704 void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
2705 TL.setNameLoc(DS.getTypeSpecTypeLoc());
2706 }
2707 void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
2708 TL.setNameLoc(DS.getTypeSpecTypeLoc());
John McCallc12c5bb2010-05-15 11:32:37 +00002709 }
2710 void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
2711 // Handle the base type, which might not have been written explicitly.
2712 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
2713 TL.setHasBaseTypeAsWritten(false);
Douglas Gregorc21c7e92011-01-25 19:13:18 +00002714 TL.getBaseLoc().initialize(Context, SourceLocation());
John McCallc12c5bb2010-05-15 11:32:37 +00002715 } else {
2716 TL.setHasBaseTypeAsWritten(true);
2717 Visit(TL.getBaseLoc());
2718 }
Argyrios Kyrtzidiseb667592009-09-29 19:45:22 +00002719
John McCallc12c5bb2010-05-15 11:32:37 +00002720 // Protocol qualifiers.
John McCall54e14c42009-10-22 22:37:11 +00002721 if (DS.getProtocolQualifiers()) {
2722 assert(TL.getNumProtocols() > 0);
2723 assert(TL.getNumProtocols() == DS.getNumProtocolQualifiers());
2724 TL.setLAngleLoc(DS.getProtocolLAngleLoc());
2725 TL.setRAngleLoc(DS.getSourceRange().getEnd());
2726 for (unsigned i = 0, e = DS.getNumProtocolQualifiers(); i != e; ++i)
2727 TL.setProtocolLoc(i, DS.getProtocolLocs()[i]);
2728 } else {
2729 assert(TL.getNumProtocols() == 0);
2730 TL.setLAngleLoc(SourceLocation());
2731 TL.setRAngleLoc(SourceLocation());
2732 }
2733 }
2734 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCall54e14c42009-10-22 22:37:11 +00002735 TL.setStarLoc(SourceLocation());
John McCallc12c5bb2010-05-15 11:32:37 +00002736 Visit(TL.getPointeeLoc());
John McCall51bd8032009-10-18 01:05:36 +00002737 }
John McCall833ca992009-10-29 08:12:44 +00002738 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
John McCalla93c9342009-12-07 02:54:59 +00002739 TypeSourceInfo *TInfo = 0;
John McCallb3d87482010-08-24 05:47:05 +00002740 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
John McCall833ca992009-10-29 08:12:44 +00002741
2742 // If we got no declarator info from previous Sema routines,
2743 // just fill with the typespec loc.
John McCalla93c9342009-12-07 02:54:59 +00002744 if (!TInfo) {
Abramo Bagnara0daaf322011-03-16 20:16:18 +00002745 TL.initialize(Context, DS.getTypeSpecTypeNameLoc());
John McCall833ca992009-10-29 08:12:44 +00002746 return;
2747 }
2748
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00002749 TypeLoc OldTL = TInfo->getTypeLoc();
2750 if (TInfo->getType()->getAs<ElaboratedType>()) {
2751 ElaboratedTypeLoc ElabTL = cast<ElaboratedTypeLoc>(OldTL);
2752 TemplateSpecializationTypeLoc NamedTL =
2753 cast<TemplateSpecializationTypeLoc>(ElabTL.getNamedTypeLoc());
2754 TL.copy(NamedTL);
2755 }
2756 else
2757 TL.copy(cast<TemplateSpecializationTypeLoc>(OldTL));
John McCall833ca992009-10-29 08:12:44 +00002758 }
John McCallcfb708c2010-01-13 20:03:27 +00002759 void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
2760 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr);
2761 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
2762 TL.setParensRange(DS.getTypeofParensRange());
2763 }
2764 void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
2765 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType);
2766 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
2767 TL.setParensRange(DS.getTypeofParensRange());
John McCallb3d87482010-08-24 05:47:05 +00002768 assert(DS.getRepAsType());
John McCallcfb708c2010-01-13 20:03:27 +00002769 TypeSourceInfo *TInfo = 0;
John McCallb3d87482010-08-24 05:47:05 +00002770 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
John McCallcfb708c2010-01-13 20:03:27 +00002771 TL.setUnderlyingTInfo(TInfo);
2772 }
Sean Huntca63c202011-05-24 22:41:36 +00002773 void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
2774 // FIXME: This holds only because we only have one unary transform.
2775 assert(DS.getTypeSpecType() == DeclSpec::TST_underlyingType);
2776 TL.setKWLoc(DS.getTypeSpecTypeLoc());
2777 TL.setParensRange(DS.getTypeofParensRange());
2778 assert(DS.getRepAsType());
2779 TypeSourceInfo *TInfo = 0;
2780 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
2781 TL.setUnderlyingTInfo(TInfo);
2782 }
Douglas Gregorddf889a2010-01-18 18:04:31 +00002783 void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
2784 // By default, use the source location of the type specifier.
2785 TL.setBuiltinLoc(DS.getTypeSpecTypeLoc());
2786 if (TL.needsExtraLocalData()) {
2787 // Set info for the written builtin specifiers.
2788 TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs();
2789 // Try to have a meaningful source location.
2790 if (TL.getWrittenSignSpec() != TSS_unspecified)
2791 // Sign spec loc overrides the others (e.g., 'unsigned long').
2792 TL.setBuiltinLoc(DS.getTypeSpecSignLoc());
2793 else if (TL.getWrittenWidthSpec() != TSW_unspecified)
2794 // Width spec loc overrides type spec loc (e.g., 'short int').
2795 TL.setBuiltinLoc(DS.getTypeSpecWidthLoc());
2796 }
2797 }
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00002798 void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
2799 ElaboratedTypeKeyword Keyword
2800 = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
Nico Weber253e80b2010-11-22 10:30:56 +00002801 if (DS.getTypeSpecType() == TST_typename) {
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00002802 TypeSourceInfo *TInfo = 0;
John McCallb3d87482010-08-24 05:47:05 +00002803 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00002804 if (TInfo) {
2805 TL.copy(cast<ElaboratedTypeLoc>(TInfo->getTypeLoc()));
2806 return;
2807 }
2808 }
2809 TL.setKeywordLoc(Keyword != ETK_None
2810 ? DS.getTypeSpecTypeLoc()
2811 : SourceLocation());
2812 const CXXScopeSpec& SS = DS.getTypeSpecScope();
Douglas Gregor9e876872011-03-01 18:12:44 +00002813 TL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00002814 Visit(TL.getNextTypeLoc().getUnqualifiedLoc());
2815 }
2816 void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
2817 ElaboratedTypeKeyword Keyword
2818 = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
Nico Weber253e80b2010-11-22 10:30:56 +00002819 if (DS.getTypeSpecType() == TST_typename) {
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00002820 TypeSourceInfo *TInfo = 0;
John McCallb3d87482010-08-24 05:47:05 +00002821 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00002822 if (TInfo) {
2823 TL.copy(cast<DependentNameTypeLoc>(TInfo->getTypeLoc()));
2824 return;
2825 }
2826 }
2827 TL.setKeywordLoc(Keyword != ETK_None
2828 ? DS.getTypeSpecTypeLoc()
2829 : SourceLocation());
2830 const CXXScopeSpec& SS = DS.getTypeSpecScope();
Douglas Gregor2494dd02011-03-01 01:34:45 +00002831 TL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnara0daaf322011-03-16 20:16:18 +00002832 TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00002833 }
John McCall33500952010-06-11 00:33:02 +00002834 void VisitDependentTemplateSpecializationTypeLoc(
2835 DependentTemplateSpecializationTypeLoc TL) {
2836 ElaboratedTypeKeyword Keyword
2837 = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
2838 if (Keyword == ETK_Typename) {
2839 TypeSourceInfo *TInfo = 0;
John McCallb3d87482010-08-24 05:47:05 +00002840 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
John McCall33500952010-06-11 00:33:02 +00002841 if (TInfo) {
2842 TL.copy(cast<DependentTemplateSpecializationTypeLoc>(
2843 TInfo->getTypeLoc()));
2844 return;
2845 }
2846 }
Douglas Gregorc21c7e92011-01-25 19:13:18 +00002847 TL.initializeLocal(Context, SourceLocation());
John McCall33500952010-06-11 00:33:02 +00002848 TL.setKeywordLoc(Keyword != ETK_None
2849 ? DS.getTypeSpecTypeLoc()
2850 : SourceLocation());
2851 const CXXScopeSpec& SS = DS.getTypeSpecScope();
Douglas Gregor94fdffa2011-03-01 20:11:18 +00002852 TL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnara0daaf322011-03-16 20:16:18 +00002853 TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
2854 }
2855 void VisitTagTypeLoc(TagTypeLoc TL) {
2856 TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
John McCall33500952010-06-11 00:33:02 +00002857 }
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00002858
John McCall51bd8032009-10-18 01:05:36 +00002859 void VisitTypeLoc(TypeLoc TL) {
2860 // FIXME: add other typespec types and change this to an assert.
Douglas Gregorc21c7e92011-01-25 19:13:18 +00002861 TL.initialize(Context, DS.getTypeSpecTypeLoc());
John McCall51bd8032009-10-18 01:05:36 +00002862 }
2863 };
Argyrios Kyrtzidisf352bdd2009-09-29 19:43:35 +00002864
John McCall51bd8032009-10-18 01:05:36 +00002865 class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
Abramo Bagnarab6ab6c12011-03-05 14:42:21 +00002866 ASTContext &Context;
John McCall51bd8032009-10-18 01:05:36 +00002867 const DeclaratorChunk &Chunk;
2868
2869 public:
Abramo Bagnarab6ab6c12011-03-05 14:42:21 +00002870 DeclaratorLocFiller(ASTContext &Context, const DeclaratorChunk &Chunk)
2871 : Context(Context), Chunk(Chunk) {}
John McCall51bd8032009-10-18 01:05:36 +00002872
2873 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002874 llvm_unreachable("qualified type locs not expected here!");
John McCall51bd8032009-10-18 01:05:36 +00002875 }
2876
John McCallf85e1932011-06-15 23:02:42 +00002877 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
2878 fillAttributedTypeLoc(TL, Chunk.getAttrs());
2879 }
John McCall51bd8032009-10-18 01:05:36 +00002880 void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
2881 assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
2882 TL.setCaretLoc(Chunk.Loc);
2883 }
2884 void VisitPointerTypeLoc(PointerTypeLoc TL) {
2885 assert(Chunk.Kind == DeclaratorChunk::Pointer);
2886 TL.setStarLoc(Chunk.Loc);
2887 }
2888 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
2889 assert(Chunk.Kind == DeclaratorChunk::Pointer);
2890 TL.setStarLoc(Chunk.Loc);
2891 }
2892 void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
2893 assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
Abramo Bagnarab6ab6c12011-03-05 14:42:21 +00002894 const CXXScopeSpec& SS = Chunk.Mem.Scope();
2895 NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context);
2896
2897 const Type* ClsTy = TL.getClass();
2898 QualType ClsQT = QualType(ClsTy, 0);
2899 TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0);
2900 // Now copy source location info into the type loc component.
2901 TypeLoc ClsTL = ClsTInfo->getTypeLoc();
2902 switch (NNSLoc.getNestedNameSpecifier()->getKind()) {
2903 case NestedNameSpecifier::Identifier:
2904 assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc");
2905 {
Abramo Bagnarafd9c42e2011-03-06 22:48:24 +00002906 DependentNameTypeLoc DNTLoc = cast<DependentNameTypeLoc>(ClsTL);
Abramo Bagnarab6ab6c12011-03-05 14:42:21 +00002907 DNTLoc.setKeywordLoc(SourceLocation());
2908 DNTLoc.setQualifierLoc(NNSLoc.getPrefix());
2909 DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc());
2910 }
2911 break;
2912
2913 case NestedNameSpecifier::TypeSpec:
2914 case NestedNameSpecifier::TypeSpecWithTemplate:
2915 if (isa<ElaboratedType>(ClsTy)) {
2916 ElaboratedTypeLoc ETLoc = *cast<ElaboratedTypeLoc>(&ClsTL);
2917 ETLoc.setKeywordLoc(SourceLocation());
2918 ETLoc.setQualifierLoc(NNSLoc.getPrefix());
2919 TypeLoc NamedTL = ETLoc.getNamedTypeLoc();
2920 NamedTL.initializeFullCopy(NNSLoc.getTypeLoc());
2921 } else {
2922 ClsTL.initializeFullCopy(NNSLoc.getTypeLoc());
2923 }
2924 break;
2925
2926 case NestedNameSpecifier::Namespace:
2927 case NestedNameSpecifier::NamespaceAlias:
2928 case NestedNameSpecifier::Global:
2929 llvm_unreachable("Nested-name-specifier must name a type");
2930 break;
2931 }
2932
2933 // Finally fill in MemberPointerLocInfo fields.
John McCall51bd8032009-10-18 01:05:36 +00002934 TL.setStarLoc(Chunk.Loc);
Abramo Bagnarab6ab6c12011-03-05 14:42:21 +00002935 TL.setClassTInfo(ClsTInfo);
John McCall51bd8032009-10-18 01:05:36 +00002936 }
2937 void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
2938 assert(Chunk.Kind == DeclaratorChunk::Reference);
John McCall54e14c42009-10-22 22:37:11 +00002939 // 'Amp' is misleading: this might have been originally
2940 /// spelled with AmpAmp.
John McCall51bd8032009-10-18 01:05:36 +00002941 TL.setAmpLoc(Chunk.Loc);
2942 }
2943 void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
2944 assert(Chunk.Kind == DeclaratorChunk::Reference);
2945 assert(!Chunk.Ref.LValueRef);
2946 TL.setAmpAmpLoc(Chunk.Loc);
2947 }
2948 void VisitArrayTypeLoc(ArrayTypeLoc TL) {
2949 assert(Chunk.Kind == DeclaratorChunk::Array);
2950 TL.setLBracketLoc(Chunk.Loc);
2951 TL.setRBracketLoc(Chunk.EndLoc);
2952 TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
2953 }
2954 void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
2955 assert(Chunk.Kind == DeclaratorChunk::Function);
Abramo Bagnara796aa442011-03-12 11:17:06 +00002956 TL.setLocalRangeBegin(Chunk.Loc);
2957 TL.setLocalRangeEnd(Chunk.EndLoc);
Douglas Gregordab60ad2010-10-01 18:44:50 +00002958 TL.setTrailingReturn(!!Chunk.Fun.TrailingReturnType);
John McCall51bd8032009-10-18 01:05:36 +00002959
2960 const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
John McCall54e14c42009-10-22 22:37:11 +00002961 for (unsigned i = 0, e = TL.getNumArgs(), tpi = 0; i != e; ++i) {
John McCalld226f652010-08-21 09:40:31 +00002962 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
John McCall54e14c42009-10-22 22:37:11 +00002963 TL.setArg(tpi++, Param);
John McCall51bd8032009-10-18 01:05:36 +00002964 }
2965 // FIXME: exception specs
2966 }
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002967 void VisitParenTypeLoc(ParenTypeLoc TL) {
2968 assert(Chunk.Kind == DeclaratorChunk::Paren);
2969 TL.setLParenLoc(Chunk.Loc);
2970 TL.setRParenLoc(Chunk.EndLoc);
2971 }
John McCall51bd8032009-10-18 01:05:36 +00002972
2973 void VisitTypeLoc(TypeLoc TL) {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002974 llvm_unreachable("unsupported TypeLoc kind in declarator!");
John McCall51bd8032009-10-18 01:05:36 +00002975 }
2976 };
Argyrios Kyrtzidisf352bdd2009-09-29 19:43:35 +00002977}
2978
John McCalla93c9342009-12-07 02:54:59 +00002979/// \brief Create and instantiate a TypeSourceInfo with type source information.
Argyrios Kyrtzidis4adab7f2009-08-19 01:28:06 +00002980///
2981/// \param T QualType referring to the type as written in source code.
Douglas Gregor05baacb2010-04-12 23:19:01 +00002982///
2983/// \param ReturnTypeInfo For declarators whose return type does not show
2984/// up in the normal place in the declaration specifiers (such as a C++
2985/// conversion function), this pointer will refer to a type source information
2986/// for that return type.
John McCalla93c9342009-12-07 02:54:59 +00002987TypeSourceInfo *
Douglas Gregor05baacb2010-04-12 23:19:01 +00002988Sema::GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
2989 TypeSourceInfo *ReturnTypeInfo) {
John McCalla93c9342009-12-07 02:54:59 +00002990 TypeSourceInfo *TInfo = Context.CreateTypeSourceInfo(T);
2991 UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc();
Argyrios Kyrtzidis4adab7f2009-08-19 01:28:06 +00002992
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002993 // Handle parameter packs whose type is a pack expansion.
2994 if (isa<PackExpansionType>(T)) {
2995 cast<PackExpansionTypeLoc>(CurrTL).setEllipsisLoc(D.getEllipsisLoc());
2996 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
2997 }
2998
Sebastian Redl8ce35b02009-10-25 21:45:37 +00002999 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
John McCall14aa2172011-03-04 04:00:19 +00003000 while (isa<AttributedTypeLoc>(CurrTL)) {
3001 AttributedTypeLoc TL = cast<AttributedTypeLoc>(CurrTL);
3002 fillAttributedTypeLoc(TL, D.getTypeObject(i).getAttrs());
3003 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
3004 }
3005
Abramo Bagnarab6ab6c12011-03-05 14:42:21 +00003006 DeclaratorLocFiller(Context, D.getTypeObject(i)).Visit(CurrTL);
John McCall51bd8032009-10-18 01:05:36 +00003007 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
Argyrios Kyrtzidis4adab7f2009-08-19 01:28:06 +00003008 }
Argyrios Kyrtzidisf352bdd2009-09-29 19:43:35 +00003009
John McCallb3d87482010-08-24 05:47:05 +00003010 // If we have different source information for the return type, use
3011 // that. This really only applies to C++ conversion functions.
3012 if (ReturnTypeInfo) {
Douglas Gregor05baacb2010-04-12 23:19:01 +00003013 TypeLoc TL = ReturnTypeInfo->getTypeLoc();
3014 assert(TL.getFullDataSize() == CurrTL.getFullDataSize());
3015 memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize());
John McCallb3d87482010-08-24 05:47:05 +00003016 } else {
Douglas Gregorc21c7e92011-01-25 19:13:18 +00003017 TypeSpecLocFiller(Context, D.getDeclSpec()).Visit(CurrTL);
Douglas Gregor05baacb2010-04-12 23:19:01 +00003018 }
3019
John McCalla93c9342009-12-07 02:54:59 +00003020 return TInfo;
Argyrios Kyrtzidis4adab7f2009-08-19 01:28:06 +00003021}
3022
John McCalla93c9342009-12-07 02:54:59 +00003023/// \brief Create a LocInfoType to hold the given QualType and TypeSourceInfo.
John McCallb3d87482010-08-24 05:47:05 +00003024ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) {
Argyrios Kyrtzidis1bb8a452009-08-19 01:28:17 +00003025 // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
3026 // and Sema during declaration parsing. Try deallocating/caching them when
3027 // it's appropriate, instead of allocating them and keeping them around.
Douglas Gregoreb0eb492010-12-10 08:12:03 +00003028 LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType),
3029 TypeAlignment);
John McCalla93c9342009-12-07 02:54:59 +00003030 new (LocT) LocInfoType(T, TInfo);
Argyrios Kyrtzidis1bb8a452009-08-19 01:28:17 +00003031 assert(LocT->getTypeClass() != T->getTypeClass() &&
3032 "LocInfoType's TypeClass conflicts with an existing Type class");
John McCallb3d87482010-08-24 05:47:05 +00003033 return ParsedType::make(QualType(LocT, 0));
Argyrios Kyrtzidis1bb8a452009-08-19 01:28:17 +00003034}
3035
3036void LocInfoType::getAsStringInternal(std::string &Str,
3037 const PrintingPolicy &Policy) const {
Argyrios Kyrtzidis35d44e52009-08-19 01:46:06 +00003038 assert(false && "LocInfoType leaked into the type system; an opaque TypeTy*"
3039 " was used directly instead of getting the QualType through"
3040 " GetTypeFromParser");
Argyrios Kyrtzidis1bb8a452009-08-19 01:28:17 +00003041}
3042
John McCallf312b1e2010-08-26 23:41:50 +00003043TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003044 // C99 6.7.6: Type names have no identifier. This is already validated by
3045 // the parser.
3046 assert(D.getIdentifier() == 0 && "Type name should have no identifier!");
Mike Stump1eb44332009-09-09 15:08:12 +00003047
Argyrios Kyrtzidisd3880f82011-06-28 03:01:18 +00003048 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCallbf1a0282010-06-04 23:28:52 +00003049 QualType T = TInfo->getType();
Chris Lattner5153ee62009-04-25 08:47:54 +00003050 if (D.isInvalidType())
Douglas Gregor809070a2009-02-18 17:45:20 +00003051 return true;
Steve Naroff5912a352007-08-28 20:14:24 +00003052
Douglas Gregor402abb52009-05-28 23:31:59 +00003053 if (getLangOptions().CPlusPlus) {
3054 // Check that there are no default arguments (C++ only).
Douglas Gregor6d6eb572008-05-07 04:49:29 +00003055 CheckExtraCXXDefaultArguments(D);
Douglas Gregor402abb52009-05-28 23:31:59 +00003056 }
3057
John McCallb3d87482010-08-24 05:47:05 +00003058 return CreateParsedType(T, TInfo);
Reid Spencer5f016e22007-07-11 17:01:13 +00003059}
3060
Douglas Gregore97179c2011-09-08 01:46:34 +00003061ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) {
3062 QualType T = Context.getObjCInstanceType();
3063 TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
3064 return CreateParsedType(T, TInfo);
3065}
3066
3067
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003068//===----------------------------------------------------------------------===//
3069// Type Attribute Processing
3070//===----------------------------------------------------------------------===//
3071
3072/// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
3073/// specified type. The attribute contains 1 argument, the id of the address
3074/// space for the type.
Mike Stump1eb44332009-09-09 15:08:12 +00003075static void HandleAddressSpaceTypeAttribute(QualType &Type,
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003076 const AttributeList &Attr, Sema &S){
John McCall0953e762009-09-24 19:53:00 +00003077
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003078 // If this type is already address space qualified, reject it.
Peter Collingbourne29e3ef82011-07-27 20:29:53 +00003079 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified by
3080 // qualifiers for two or more different address spaces."
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003081 if (Type.getAddressSpace()) {
3082 S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers);
Abramo Bagnarae215f722010-04-30 13:10:51 +00003083 Attr.setInvalid();
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003084 return;
3085 }
Mike Stump1eb44332009-09-09 15:08:12 +00003086
Peter Collingbourne020972d2011-07-27 20:30:05 +00003087 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be
3088 // qualified by an address-space qualifier."
3089 if (Type->isFunctionType()) {
3090 S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type);
3091 Attr.setInvalid();
3092 return;
3093 }
3094
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003095 // Check the attribute arguments.
3096 if (Attr.getNumArgs() != 1) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003097 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
Abramo Bagnarae215f722010-04-30 13:10:51 +00003098 Attr.setInvalid();
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003099 return;
3100 }
3101 Expr *ASArgExpr = static_cast<Expr *>(Attr.getArg(0));
3102 llvm::APSInt addrSpace(32);
Douglas Gregorac06a0e2010-05-18 23:01:22 +00003103 if (ASArgExpr->isTypeDependent() || ASArgExpr->isValueDependent() ||
3104 !ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003105 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_not_int)
3106 << ASArgExpr->getSourceRange();
Abramo Bagnarae215f722010-04-30 13:10:51 +00003107 Attr.setInvalid();
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003108 return;
3109 }
3110
John McCallefadb772009-07-28 06:52:18 +00003111 // Bounds checking.
3112 if (addrSpace.isSigned()) {
3113 if (addrSpace.isNegative()) {
3114 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_negative)
3115 << ASArgExpr->getSourceRange();
Abramo Bagnarae215f722010-04-30 13:10:51 +00003116 Attr.setInvalid();
John McCallefadb772009-07-28 06:52:18 +00003117 return;
3118 }
3119 addrSpace.setIsSigned(false);
3120 }
3121 llvm::APSInt max(addrSpace.getBitWidth());
John McCall0953e762009-09-24 19:53:00 +00003122 max = Qualifiers::MaxAddressSpace;
John McCallefadb772009-07-28 06:52:18 +00003123 if (addrSpace > max) {
3124 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_too_high)
John McCall0953e762009-09-24 19:53:00 +00003125 << Qualifiers::MaxAddressSpace << ASArgExpr->getSourceRange();
Abramo Bagnarae215f722010-04-30 13:10:51 +00003126 Attr.setInvalid();
John McCallefadb772009-07-28 06:52:18 +00003127 return;
3128 }
3129
Mike Stump1eb44332009-09-09 15:08:12 +00003130 unsigned ASIdx = static_cast<unsigned>(addrSpace.getZExtValue());
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00003131 Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003132}
3133
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00003134/// handleObjCOwnershipTypeAttr - Process an objc_ownership
John McCallf85e1932011-06-15 23:02:42 +00003135/// attribute on the specified type.
3136///
3137/// Returns 'true' if the attribute was handled.
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00003138static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
John McCallf85e1932011-06-15 23:02:42 +00003139 AttributeList &attr,
3140 QualType &type) {
3141 if (!type->isObjCRetainableType() && !type->isDependentType())
3142 return false;
3143
3144 Sema &S = state.getSema();
3145
3146 if (type.getQualifiers().getObjCLifetime()) {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00003147 S.Diag(attr.getLoc(), diag::err_attr_objc_ownership_redundant)
John McCallf85e1932011-06-15 23:02:42 +00003148 << type;
3149 return true;
3150 }
3151
3152 if (!attr.getParameterName()) {
3153 S.Diag(attr.getLoc(), diag::err_attribute_argument_n_not_string)
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00003154 << "objc_ownership" << 1;
John McCallf85e1932011-06-15 23:02:42 +00003155 attr.setInvalid();
3156 return true;
3157 }
3158
3159 Qualifiers::ObjCLifetime lifetime;
3160 if (attr.getParameterName()->isStr("none"))
3161 lifetime = Qualifiers::OCL_ExplicitNone;
3162 else if (attr.getParameterName()->isStr("strong"))
3163 lifetime = Qualifiers::OCL_Strong;
3164 else if (attr.getParameterName()->isStr("weak"))
3165 lifetime = Qualifiers::OCL_Weak;
3166 else if (attr.getParameterName()->isStr("autoreleasing"))
3167 lifetime = Qualifiers::OCL_Autoreleasing;
3168 else {
3169 S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported)
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00003170 << "objc_ownership" << attr.getParameterName();
John McCallf85e1932011-06-15 23:02:42 +00003171 attr.setInvalid();
3172 return true;
3173 }
3174
3175 // Consume lifetime attributes without further comment outside of
3176 // ARC mode.
3177 if (!S.getLangOptions().ObjCAutoRefCount)
3178 return true;
3179
3180 Qualifiers qs;
3181 qs.setObjCLifetime(lifetime);
3182 QualType origType = type;
3183 type = S.Context.getQualifiedType(type, qs);
3184
3185 // If we have a valid source location for the attribute, use an
3186 // AttributedType instead.
3187 if (attr.getLoc().isValid())
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00003188 type = S.Context.getAttributedType(AttributedType::attr_objc_ownership,
John McCallf85e1932011-06-15 23:02:42 +00003189 origType, type);
3190
John McCall9f084a32011-07-06 00:26:06 +00003191 // Forbid __weak if the runtime doesn't support it.
John McCallf85e1932011-06-15 23:02:42 +00003192 if (lifetime == Qualifiers::OCL_Weak &&
John McCall9f084a32011-07-06 00:26:06 +00003193 !S.getLangOptions().ObjCRuntimeHasWeak) {
John McCallf85e1932011-06-15 23:02:42 +00003194
3195 // Actually, delay this until we know what we're parsing.
3196 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
3197 S.DelayedDiagnostics.add(
3198 sema::DelayedDiagnostic::makeForbiddenType(attr.getLoc(),
3199 diag::err_arc_weak_no_runtime, type, /*ignored*/ 0));
3200 } else {
3201 S.Diag(attr.getLoc(), diag::err_arc_weak_no_runtime);
3202 }
3203
3204 attr.setInvalid();
3205 return true;
3206 }
Fariborz Jahanian742352a2011-07-06 19:24:05 +00003207
3208 // Forbid __weak for class objects marked as
3209 // objc_arc_weak_reference_unavailable
3210 if (lifetime == Qualifiers::OCL_Weak) {
3211 QualType T = type;
Fariborz Jahanian742352a2011-07-06 19:24:05 +00003212 while (const PointerType *ptr = T->getAs<PointerType>())
3213 T = ptr->getPointeeType();
3214 if (const ObjCObjectPointerType *ObjT = T->getAs<ObjCObjectPointerType>()) {
3215 ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl();
Fariborz Jahanian7263fee2011-07-06 20:48:48 +00003216 if (Class->isArcWeakrefUnavailable()) {
Fariborz Jahanian742352a2011-07-06 19:24:05 +00003217 S.Diag(attr.getLoc(), diag::err_arc_unsupported_weak_class);
3218 S.Diag(ObjT->getInterfaceDecl()->getLocation(),
3219 diag::note_class_declared);
Fariborz Jahanian742352a2011-07-06 19:24:05 +00003220 }
3221 }
3222 }
3223
John McCallf85e1932011-06-15 23:02:42 +00003224 return true;
3225}
3226
John McCall711c52b2011-01-05 12:14:39 +00003227/// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type
3228/// attribute on the specified type. Returns true to indicate that
3229/// the attribute was handled, false to indicate that the type does
3230/// not permit the attribute.
3231static bool handleObjCGCTypeAttr(TypeProcessingState &state,
3232 AttributeList &attr,
3233 QualType &type) {
3234 Sema &S = state.getSema();
3235
3236 // Delay if this isn't some kind of pointer.
3237 if (!type->isPointerType() &&
3238 !type->isObjCObjectPointerType() &&
3239 !type->isBlockPointerType())
3240 return false;
3241
3242 if (type.getObjCGCAttr() != Qualifiers::GCNone) {
3243 S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc);
3244 attr.setInvalid();
3245 return true;
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00003246 }
Mike Stump1eb44332009-09-09 15:08:12 +00003247
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00003248 // Check the attribute arguments.
John McCall711c52b2011-01-05 12:14:39 +00003249 if (!attr.getParameterName()) {
3250 S.Diag(attr.getLoc(), diag::err_attribute_argument_n_not_string)
Fariborz Jahanianba372b82009-02-18 17:52:36 +00003251 << "objc_gc" << 1;
John McCall711c52b2011-01-05 12:14:39 +00003252 attr.setInvalid();
3253 return true;
Fariborz Jahanianba372b82009-02-18 17:52:36 +00003254 }
John McCall0953e762009-09-24 19:53:00 +00003255 Qualifiers::GC GCAttr;
John McCall711c52b2011-01-05 12:14:39 +00003256 if (attr.getNumArgs() != 0) {
3257 S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
3258 attr.setInvalid();
3259 return true;
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00003260 }
John McCall711c52b2011-01-05 12:14:39 +00003261 if (attr.getParameterName()->isStr("weak"))
John McCall0953e762009-09-24 19:53:00 +00003262 GCAttr = Qualifiers::Weak;
John McCall711c52b2011-01-05 12:14:39 +00003263 else if (attr.getParameterName()->isStr("strong"))
John McCall0953e762009-09-24 19:53:00 +00003264 GCAttr = Qualifiers::Strong;
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00003265 else {
John McCall711c52b2011-01-05 12:14:39 +00003266 S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported)
3267 << "objc_gc" << attr.getParameterName();
3268 attr.setInvalid();
3269 return true;
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00003270 }
Mike Stump1eb44332009-09-09 15:08:12 +00003271
John McCall14aa2172011-03-04 04:00:19 +00003272 QualType origType = type;
3273 type = S.Context.getObjCGCQualType(origType, GCAttr);
3274
3275 // Make an attributed type to preserve the source information.
3276 if (attr.getLoc().isValid())
3277 type = S.Context.getAttributedType(AttributedType::attr_objc_gc,
3278 origType, type);
3279
John McCall711c52b2011-01-05 12:14:39 +00003280 return true;
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00003281}
3282
John McCalle6a365d2010-12-19 02:44:49 +00003283namespace {
3284 /// A helper class to unwrap a type down to a function for the
3285 /// purposes of applying attributes there.
3286 ///
3287 /// Use:
3288 /// FunctionTypeUnwrapper unwrapped(SemaRef, T);
3289 /// if (unwrapped.isFunctionType()) {
3290 /// const FunctionType *fn = unwrapped.get();
3291 /// // change fn somehow
3292 /// T = unwrapped.wrap(fn);
3293 /// }
3294 struct FunctionTypeUnwrapper {
3295 enum WrapKind {
3296 Desugar,
3297 Parens,
3298 Pointer,
3299 BlockPointer,
3300 Reference,
3301 MemberPointer
3302 };
3303
3304 QualType Original;
3305 const FunctionType *Fn;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003306 SmallVector<unsigned char /*WrapKind*/, 8> Stack;
John McCalle6a365d2010-12-19 02:44:49 +00003307
3308 FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) {
3309 while (true) {
3310 const Type *Ty = T.getTypePtr();
3311 if (isa<FunctionType>(Ty)) {
3312 Fn = cast<FunctionType>(Ty);
3313 return;
3314 } else if (isa<ParenType>(Ty)) {
3315 T = cast<ParenType>(Ty)->getInnerType();
3316 Stack.push_back(Parens);
3317 } else if (isa<PointerType>(Ty)) {
3318 T = cast<PointerType>(Ty)->getPointeeType();
3319 Stack.push_back(Pointer);
3320 } else if (isa<BlockPointerType>(Ty)) {
3321 T = cast<BlockPointerType>(Ty)->getPointeeType();
3322 Stack.push_back(BlockPointer);
3323 } else if (isa<MemberPointerType>(Ty)) {
3324 T = cast<MemberPointerType>(Ty)->getPointeeType();
3325 Stack.push_back(MemberPointer);
3326 } else if (isa<ReferenceType>(Ty)) {
3327 T = cast<ReferenceType>(Ty)->getPointeeType();
3328 Stack.push_back(Reference);
3329 } else {
3330 const Type *DTy = Ty->getUnqualifiedDesugaredType();
3331 if (Ty == DTy) {
3332 Fn = 0;
3333 return;
3334 }
3335
3336 T = QualType(DTy, 0);
3337 Stack.push_back(Desugar);
3338 }
3339 }
3340 }
3341
3342 bool isFunctionType() const { return (Fn != 0); }
3343 const FunctionType *get() const { return Fn; }
3344
3345 QualType wrap(Sema &S, const FunctionType *New) {
3346 // If T wasn't modified from the unwrapped type, do nothing.
3347 if (New == get()) return Original;
3348
3349 Fn = New;
3350 return wrap(S.Context, Original, 0);
3351 }
3352
3353 private:
3354 QualType wrap(ASTContext &C, QualType Old, unsigned I) {
3355 if (I == Stack.size())
3356 return C.getQualifiedType(Fn, Old.getQualifiers());
3357
3358 // Build up the inner type, applying the qualifiers from the old
3359 // type to the new type.
3360 SplitQualType SplitOld = Old.split();
3361
3362 // As a special case, tail-recurse if there are no qualifiers.
3363 if (SplitOld.second.empty())
3364 return wrap(C, SplitOld.first, I);
3365 return C.getQualifiedType(wrap(C, SplitOld.first, I), SplitOld.second);
3366 }
3367
3368 QualType wrap(ASTContext &C, const Type *Old, unsigned I) {
3369 if (I == Stack.size()) return QualType(Fn, 0);
3370
3371 switch (static_cast<WrapKind>(Stack[I++])) {
3372 case Desugar:
3373 // This is the point at which we potentially lose source
3374 // information.
3375 return wrap(C, Old->getUnqualifiedDesugaredType(), I);
3376
3377 case Parens: {
3378 QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I);
3379 return C.getParenType(New);
3380 }
3381
3382 case Pointer: {
3383 QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I);
3384 return C.getPointerType(New);
3385 }
3386
3387 case BlockPointer: {
3388 QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I);
3389 return C.getBlockPointerType(New);
3390 }
3391
3392 case MemberPointer: {
3393 const MemberPointerType *OldMPT = cast<MemberPointerType>(Old);
3394 QualType New = wrap(C, OldMPT->getPointeeType(), I);
3395 return C.getMemberPointerType(New, OldMPT->getClass());
3396 }
3397
3398 case Reference: {
3399 const ReferenceType *OldRef = cast<ReferenceType>(Old);
3400 QualType New = wrap(C, OldRef->getPointeeType(), I);
3401 if (isa<LValueReferenceType>(OldRef))
3402 return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue());
3403 else
3404 return C.getRValueReferenceType(New);
3405 }
3406 }
3407
3408 llvm_unreachable("unknown wrapping kind");
3409 return QualType();
3410 }
3411 };
3412}
3413
John McCall711c52b2011-01-05 12:14:39 +00003414/// Process an individual function attribute. Returns true to
3415/// indicate that the attribute was handled, false if it wasn't.
3416static bool handleFunctionTypeAttr(TypeProcessingState &state,
3417 AttributeList &attr,
3418 QualType &type) {
3419 Sema &S = state.getSema();
John McCalle6a365d2010-12-19 02:44:49 +00003420
John McCall711c52b2011-01-05 12:14:39 +00003421 FunctionTypeUnwrapper unwrapped(S, type);
Mike Stump24556362009-07-25 21:26:53 +00003422
John McCall711c52b2011-01-05 12:14:39 +00003423 if (attr.getKind() == AttributeList::AT_noreturn) {
3424 if (S.CheckNoReturnAttr(attr))
John McCall04a67a62010-02-05 21:31:56 +00003425 return true;
John McCalle6a365d2010-12-19 02:44:49 +00003426
John McCall711c52b2011-01-05 12:14:39 +00003427 // Delay if this is not a function type.
3428 if (!unwrapped.isFunctionType())
3429 return false;
3430
John McCall04a67a62010-02-05 21:31:56 +00003431 // Otherwise we can process right away.
John McCall711c52b2011-01-05 12:14:39 +00003432 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true);
3433 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
3434 return true;
John McCall04a67a62010-02-05 21:31:56 +00003435 }
Mike Stump24556362009-07-25 21:26:53 +00003436
John McCallf85e1932011-06-15 23:02:42 +00003437 // ns_returns_retained is not always a type attribute, but if we got
3438 // here, we're treating it as one right now.
3439 if (attr.getKind() == AttributeList::AT_ns_returns_retained) {
3440 assert(S.getLangOptions().ObjCAutoRefCount &&
3441 "ns_returns_retained treated as type attribute in non-ARC");
3442 if (attr.getNumArgs()) return true;
3443
3444 // Delay if this is not a function type.
3445 if (!unwrapped.isFunctionType())
3446 return false;
3447
3448 FunctionType::ExtInfo EI
3449 = unwrapped.get()->getExtInfo().withProducesResult(true);
3450 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
3451 return true;
3452 }
3453
John McCall711c52b2011-01-05 12:14:39 +00003454 if (attr.getKind() == AttributeList::AT_regparm) {
3455 unsigned value;
3456 if (S.CheckRegparmAttr(attr, value))
Rafael Espindola425ef722010-03-30 22:15:11 +00003457 return true;
3458
John McCall711c52b2011-01-05 12:14:39 +00003459 // Delay if this is not a function type.
3460 if (!unwrapped.isFunctionType())
Rafael Espindola425ef722010-03-30 22:15:11 +00003461 return false;
3462
Argyrios Kyrtzidisce955662011-01-25 23:16:40 +00003463 // Diagnose regparm with fastcall.
3464 const FunctionType *fn = unwrapped.get();
3465 CallingConv CC = fn->getCallConv();
3466 if (CC == CC_X86FastCall) {
3467 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
3468 << FunctionType::getNameForCallConv(CC)
3469 << "regparm";
3470 attr.setInvalid();
3471 return true;
3472 }
3473
John McCalle6a365d2010-12-19 02:44:49 +00003474 FunctionType::ExtInfo EI =
John McCall711c52b2011-01-05 12:14:39 +00003475 unwrapped.get()->getExtInfo().withRegParm(value);
3476 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
3477 return true;
Rafael Espindola425ef722010-03-30 22:15:11 +00003478 }
3479
John McCall04a67a62010-02-05 21:31:56 +00003480 // Otherwise, a calling convention.
John McCall711c52b2011-01-05 12:14:39 +00003481 CallingConv CC;
3482 if (S.CheckCallingConvAttr(attr, CC))
3483 return true;
John McCallf82b4e82010-02-04 05:44:44 +00003484
John McCall04a67a62010-02-05 21:31:56 +00003485 // Delay if the type didn't work out to a function.
John McCall711c52b2011-01-05 12:14:39 +00003486 if (!unwrapped.isFunctionType()) return false;
John McCall04a67a62010-02-05 21:31:56 +00003487
John McCall711c52b2011-01-05 12:14:39 +00003488 const FunctionType *fn = unwrapped.get();
3489 CallingConv CCOld = fn->getCallConv();
Charles Davis064f7db2010-02-23 06:13:55 +00003490 if (S.Context.getCanonicalCallConv(CC) ==
Abramo Bagnarae215f722010-04-30 13:10:51 +00003491 S.Context.getCanonicalCallConv(CCOld)) {
Argyrios Kyrtzidisce955662011-01-25 23:16:40 +00003492 FunctionType::ExtInfo EI= unwrapped.get()->getExtInfo().withCallingConv(CC);
3493 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
John McCall711c52b2011-01-05 12:14:39 +00003494 return true;
Abramo Bagnarae215f722010-04-30 13:10:51 +00003495 }
John McCall04a67a62010-02-05 21:31:56 +00003496
Roman Divacky8e68f1c2011-08-05 16:37:22 +00003497 if (CCOld != (S.LangOpts.MRTD ? CC_X86StdCall : CC_Default)) {
John McCall04a67a62010-02-05 21:31:56 +00003498 // Should we diagnose reapplications of the same convention?
John McCall711c52b2011-01-05 12:14:39 +00003499 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
John McCall04a67a62010-02-05 21:31:56 +00003500 << FunctionType::getNameForCallConv(CC)
3501 << FunctionType::getNameForCallConv(CCOld);
John McCall711c52b2011-01-05 12:14:39 +00003502 attr.setInvalid();
3503 return true;
John McCall04a67a62010-02-05 21:31:56 +00003504 }
3505
3506 // Diagnose the use of X86 fastcall on varargs or unprototyped functions.
3507 if (CC == CC_X86FastCall) {
John McCall711c52b2011-01-05 12:14:39 +00003508 if (isa<FunctionNoProtoType>(fn)) {
3509 S.Diag(attr.getLoc(), diag::err_cconv_knr)
John McCall04a67a62010-02-05 21:31:56 +00003510 << FunctionType::getNameForCallConv(CC);
John McCall711c52b2011-01-05 12:14:39 +00003511 attr.setInvalid();
3512 return true;
John McCall04a67a62010-02-05 21:31:56 +00003513 }
3514
John McCall711c52b2011-01-05 12:14:39 +00003515 const FunctionProtoType *FnP = cast<FunctionProtoType>(fn);
John McCall04a67a62010-02-05 21:31:56 +00003516 if (FnP->isVariadic()) {
John McCall711c52b2011-01-05 12:14:39 +00003517 S.Diag(attr.getLoc(), diag::err_cconv_varargs)
John McCall04a67a62010-02-05 21:31:56 +00003518 << FunctionType::getNameForCallConv(CC);
John McCall711c52b2011-01-05 12:14:39 +00003519 attr.setInvalid();
3520 return true;
John McCall04a67a62010-02-05 21:31:56 +00003521 }
Argyrios Kyrtzidisce955662011-01-25 23:16:40 +00003522
3523 // Also diagnose fastcall with regparm.
Eli Friedmana49218e2011-04-09 08:18:08 +00003524 if (fn->getHasRegParm()) {
Argyrios Kyrtzidisce955662011-01-25 23:16:40 +00003525 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
3526 << "regparm"
3527 << FunctionType::getNameForCallConv(CC);
3528 attr.setInvalid();
3529 return true;
3530 }
John McCall04a67a62010-02-05 21:31:56 +00003531 }
3532
John McCall711c52b2011-01-05 12:14:39 +00003533 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withCallingConv(CC);
3534 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
3535 return true;
John McCallf82b4e82010-02-04 05:44:44 +00003536}
3537
Peter Collingbourne207f4d82011-03-18 22:38:29 +00003538/// Handle OpenCL image access qualifiers: read_only, write_only, read_write
3539static void HandleOpenCLImageAccessAttribute(QualType& CurType,
3540 const AttributeList &Attr,
3541 Sema &S) {
3542 // Check the attribute arguments.
3543 if (Attr.getNumArgs() != 1) {
3544 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
3545 Attr.setInvalid();
3546 return;
3547 }
3548 Expr *sizeExpr = static_cast<Expr *>(Attr.getArg(0));
3549 llvm::APSInt arg(32);
3550 if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() ||
3551 !sizeExpr->isIntegerConstantExpr(arg, S.Context)) {
3552 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
3553 << "opencl_image_access" << sizeExpr->getSourceRange();
3554 Attr.setInvalid();
3555 return;
3556 }
3557 unsigned iarg = static_cast<unsigned>(arg.getZExtValue());
3558 switch (iarg) {
3559 case CLIA_read_only:
3560 case CLIA_write_only:
3561 case CLIA_read_write:
3562 // Implemented in a separate patch
3563 break;
3564 default:
3565 // Implemented in a separate patch
3566 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
3567 << sizeExpr->getSourceRange();
3568 Attr.setInvalid();
3569 break;
3570 }
3571}
3572
John Thompson6e132aa2009-12-04 21:51:28 +00003573/// HandleVectorSizeAttribute - this attribute is only applicable to integral
3574/// and float scalars, although arrays, pointers, and function return values are
3575/// allowed in conjunction with this construct. Aggregates with this attribute
3576/// are invalid, even if they are of the same size as a corresponding scalar.
3577/// The raw attribute should contain precisely 1 argument, the vector size for
3578/// the variable, measured in bytes. If curType and rawAttr are well formed,
3579/// this routine will return a new vector type.
Chris Lattner788b0fd2010-06-23 06:00:24 +00003580static void HandleVectorSizeAttr(QualType& CurType, const AttributeList &Attr,
3581 Sema &S) {
Bob Wilson56affbc2010-11-16 00:32:16 +00003582 // Check the attribute arguments.
John Thompson6e132aa2009-12-04 21:51:28 +00003583 if (Attr.getNumArgs() != 1) {
3584 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
Abramo Bagnarae215f722010-04-30 13:10:51 +00003585 Attr.setInvalid();
John Thompson6e132aa2009-12-04 21:51:28 +00003586 return;
3587 }
3588 Expr *sizeExpr = static_cast<Expr *>(Attr.getArg(0));
3589 llvm::APSInt vecSize(32);
Douglas Gregorac06a0e2010-05-18 23:01:22 +00003590 if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() ||
3591 !sizeExpr->isIntegerConstantExpr(vecSize, S.Context)) {
John Thompson6e132aa2009-12-04 21:51:28 +00003592 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
3593 << "vector_size" << sizeExpr->getSourceRange();
Abramo Bagnarae215f722010-04-30 13:10:51 +00003594 Attr.setInvalid();
John Thompson6e132aa2009-12-04 21:51:28 +00003595 return;
3596 }
3597 // the base type must be integer or float, and can't already be a vector.
Douglas Gregorf6094622010-07-23 15:58:24 +00003598 if (!CurType->isIntegerType() && !CurType->isRealFloatingType()) {
John Thompson6e132aa2009-12-04 21:51:28 +00003599 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
Abramo Bagnarae215f722010-04-30 13:10:51 +00003600 Attr.setInvalid();
John Thompson6e132aa2009-12-04 21:51:28 +00003601 return;
3602 }
3603 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
3604 // vecSize is specified in bytes - convert to bits.
3605 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
3606
3607 // the vector size needs to be an integral multiple of the type size.
3608 if (vectorSize % typeSize) {
3609 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
3610 << sizeExpr->getSourceRange();
Abramo Bagnarae215f722010-04-30 13:10:51 +00003611 Attr.setInvalid();
John Thompson6e132aa2009-12-04 21:51:28 +00003612 return;
3613 }
3614 if (vectorSize == 0) {
3615 S.Diag(Attr.getLoc(), diag::err_attribute_zero_size)
3616 << sizeExpr->getSourceRange();
Abramo Bagnarae215f722010-04-30 13:10:51 +00003617 Attr.setInvalid();
John Thompson6e132aa2009-12-04 21:51:28 +00003618 return;
3619 }
3620
3621 // Success! Instantiate the vector type, the number of elements is > 0, and
3622 // not required to be a power of 2, unlike GCC.
Chris Lattner788b0fd2010-06-23 06:00:24 +00003623 CurType = S.Context.getVectorType(CurType, vectorSize/typeSize,
Bob Wilsone86d78c2010-11-10 21:56:12 +00003624 VectorType::GenericVector);
John Thompson6e132aa2009-12-04 21:51:28 +00003625}
3626
Douglas Gregor4ac01402011-06-15 16:02:29 +00003627/// \brief Process the OpenCL-like ext_vector_type attribute when it occurs on
3628/// a type.
3629static void HandleExtVectorTypeAttr(QualType &CurType,
3630 const AttributeList &Attr,
3631 Sema &S) {
3632 Expr *sizeExpr;
3633
3634 // Special case where the argument is a template id.
3635 if (Attr.getParameterName()) {
3636 CXXScopeSpec SS;
3637 UnqualifiedId id;
3638 id.setIdentifier(Attr.getParameterName(), Attr.getLoc());
3639
3640 ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, id, false,
3641 false);
3642 if (Size.isInvalid())
3643 return;
3644
3645 sizeExpr = Size.get();
3646 } else {
3647 // check the attribute arguments.
3648 if (Attr.getNumArgs() != 1) {
3649 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
3650 return;
3651 }
3652 sizeExpr = Attr.getArg(0);
3653 }
3654
3655 // Create the vector type.
3656 QualType T = S.BuildExtVectorType(CurType, sizeExpr, Attr.getLoc());
3657 if (!T.isNull())
3658 CurType = T;
3659}
3660
Bob Wilson4211bb62010-11-16 00:32:24 +00003661/// HandleNeonVectorTypeAttr - The "neon_vector_type" and
3662/// "neon_polyvector_type" attributes are used to create vector types that
3663/// are mangled according to ARM's ABI. Otherwise, these types are identical
3664/// to those created with the "vector_size" attribute. Unlike "vector_size"
3665/// the argument to these Neon attributes is the number of vector elements,
3666/// not the vector size in bytes. The vector width and element type must
3667/// match one of the standard Neon vector types.
3668static void HandleNeonVectorTypeAttr(QualType& CurType,
3669 const AttributeList &Attr, Sema &S,
3670 VectorType::VectorKind VecKind,
3671 const char *AttrName) {
3672 // Check the attribute arguments.
3673 if (Attr.getNumArgs() != 1) {
3674 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
3675 Attr.setInvalid();
3676 return;
3677 }
3678 // The number of elements must be an ICE.
3679 Expr *numEltsExpr = static_cast<Expr *>(Attr.getArg(0));
3680 llvm::APSInt numEltsInt(32);
3681 if (numEltsExpr->isTypeDependent() || numEltsExpr->isValueDependent() ||
3682 !numEltsExpr->isIntegerConstantExpr(numEltsInt, S.Context)) {
3683 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
3684 << AttrName << numEltsExpr->getSourceRange();
3685 Attr.setInvalid();
3686 return;
3687 }
3688 // Only certain element types are supported for Neon vectors.
3689 const BuiltinType* BTy = CurType->getAs<BuiltinType>();
3690 if (!BTy ||
3691 (VecKind == VectorType::NeonPolyVector &&
3692 BTy->getKind() != BuiltinType::SChar &&
3693 BTy->getKind() != BuiltinType::Short) ||
3694 (BTy->getKind() != BuiltinType::SChar &&
3695 BTy->getKind() != BuiltinType::UChar &&
3696 BTy->getKind() != BuiltinType::Short &&
3697 BTy->getKind() != BuiltinType::UShort &&
3698 BTy->getKind() != BuiltinType::Int &&
3699 BTy->getKind() != BuiltinType::UInt &&
3700 BTy->getKind() != BuiltinType::LongLong &&
3701 BTy->getKind() != BuiltinType::ULongLong &&
3702 BTy->getKind() != BuiltinType::Float)) {
3703 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) <<CurType;
3704 Attr.setInvalid();
3705 return;
3706 }
3707 // The total size of the vector must be 64 or 128 bits.
3708 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
3709 unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue());
3710 unsigned vecSize = typeSize * numElts;
3711 if (vecSize != 64 && vecSize != 128) {
3712 S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType;
3713 Attr.setInvalid();
3714 return;
3715 }
3716
3717 CurType = S.Context.getVectorType(CurType, numElts, VecKind);
3718}
3719
John McCall711c52b2011-01-05 12:14:39 +00003720static void processTypeAttrs(TypeProcessingState &state, QualType &type,
3721 bool isDeclSpec, AttributeList *attrs) {
Chris Lattner232e8822008-02-21 01:08:11 +00003722 // Scan through and apply attributes to this type where it makes sense. Some
3723 // attributes (such as __address_space__, __vector_size__, etc) apply to the
3724 // type, but others can be present in the type specifiers even though they
Chris Lattnerfca0ddd2008-06-26 06:27:57 +00003725 // apply to the decl. Here we apply type attributes and ignore the rest.
John McCall711c52b2011-01-05 12:14:39 +00003726
3727 AttributeList *next;
3728 do {
3729 AttributeList &attr = *attrs;
3730 next = attr.getNext();
3731
Abramo Bagnarae215f722010-04-30 13:10:51 +00003732 // Skip attributes that were marked to be invalid.
John McCall711c52b2011-01-05 12:14:39 +00003733 if (attr.isInvalid())
Abramo Bagnarae215f722010-04-30 13:10:51 +00003734 continue;
3735
Abramo Bagnarab1f1b262010-04-30 09:13:03 +00003736 // If this is an attribute we can handle, do so now,
3737 // otherwise, add it to the FnAttrs list for rechaining.
John McCall711c52b2011-01-05 12:14:39 +00003738 switch (attr.getKind()) {
Chris Lattner232e8822008-02-21 01:08:11 +00003739 default: break;
John McCall04a67a62010-02-05 21:31:56 +00003740
Chris Lattner232e8822008-02-21 01:08:11 +00003741 case AttributeList::AT_address_space:
John McCall711c52b2011-01-05 12:14:39 +00003742 HandleAddressSpaceTypeAttribute(type, attr, state.getSema());
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003743 break;
John McCall711c52b2011-01-05 12:14:39 +00003744 OBJC_POINTER_TYPE_ATTRS_CASELIST:
3745 if (!handleObjCPointerTypeAttr(state, attr, type))
3746 distributeObjCPointerTypeAttr(state, attr, type);
Mike Stump24556362009-07-25 21:26:53 +00003747 break;
John Thompson6e132aa2009-12-04 21:51:28 +00003748 case AttributeList::AT_vector_size:
John McCall711c52b2011-01-05 12:14:39 +00003749 HandleVectorSizeAttr(type, attr, state.getSema());
John McCall04a67a62010-02-05 21:31:56 +00003750 break;
Douglas Gregor4ac01402011-06-15 16:02:29 +00003751 case AttributeList::AT_ext_vector_type:
3752 if (state.getDeclarator().getDeclSpec().getStorageClassSpec()
3753 != DeclSpec::SCS_typedef)
3754 HandleExtVectorTypeAttr(type, attr, state.getSema());
3755 break;
Bob Wilson4211bb62010-11-16 00:32:24 +00003756 case AttributeList::AT_neon_vector_type:
John McCall711c52b2011-01-05 12:14:39 +00003757 HandleNeonVectorTypeAttr(type, attr, state.getSema(),
3758 VectorType::NeonVector, "neon_vector_type");
Bob Wilson4211bb62010-11-16 00:32:24 +00003759 break;
3760 case AttributeList::AT_neon_polyvector_type:
John McCall711c52b2011-01-05 12:14:39 +00003761 HandleNeonVectorTypeAttr(type, attr, state.getSema(),
3762 VectorType::NeonPolyVector,
Bob Wilson4211bb62010-11-16 00:32:24 +00003763 "neon_polyvector_type");
3764 break;
Peter Collingbourne207f4d82011-03-18 22:38:29 +00003765 case AttributeList::AT_opencl_image_access:
3766 HandleOpenCLImageAccessAttribute(type, attr, state.getSema());
3767 break;
3768
John McCallf85e1932011-06-15 23:02:42 +00003769 case AttributeList::AT_ns_returns_retained:
3770 if (!state.getSema().getLangOptions().ObjCAutoRefCount)
3771 break;
3772 // fallthrough into the function attrs
3773
John McCall711c52b2011-01-05 12:14:39 +00003774 FUNCTION_TYPE_ATTRS_CASELIST:
3775 // Never process function type attributes as part of the
3776 // declaration-specifiers.
3777 if (isDeclSpec)
3778 distributeFunctionTypeAttrFromDeclSpec(state, attr, type);
3779
3780 // Otherwise, handle the possible delays.
3781 else if (!handleFunctionTypeAttr(state, attr, type))
3782 distributeFunctionTypeAttr(state, attr, type);
John Thompson6e132aa2009-12-04 21:51:28 +00003783 break;
Chris Lattner232e8822008-02-21 01:08:11 +00003784 }
John McCall711c52b2011-01-05 12:14:39 +00003785 } while ((attrs = next));
Chris Lattner232e8822008-02-21 01:08:11 +00003786}
3787
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003788/// \brief Ensure that the type of the given expression is complete.
3789///
3790/// This routine checks whether the expression \p E has a complete type. If the
3791/// expression refers to an instantiable construct, that instantiation is
3792/// performed as needed to complete its type. Furthermore
3793/// Sema::RequireCompleteType is called for the expression's type (or in the
3794/// case of a reference type, the referred-to type).
3795///
3796/// \param E The expression whose type is required to be complete.
3797/// \param PD The partial diagnostic that will be printed out if the type cannot
3798/// be completed.
3799///
3800/// \returns \c true if the type of \p E is incomplete and diagnosed, \c false
3801/// otherwise.
3802bool Sema::RequireCompleteExprType(Expr *E, const PartialDiagnostic &PD,
3803 std::pair<SourceLocation,
3804 PartialDiagnostic> Note) {
3805 QualType T = E->getType();
3806
3807 // Fast path the case where the type is already complete.
3808 if (!T->isIncompleteType())
3809 return false;
3810
3811 // Incomplete array types may be completed by the initializer attached to
3812 // their definitions. For static data members of class templates we need to
3813 // instantiate the definition to get this initializer and complete the type.
3814 if (T->isIncompleteArrayType()) {
3815 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3816 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
3817 if (Var->isStaticDataMember() &&
3818 Var->getInstantiatedFromStaticDataMember()) {
Douglas Gregor36f255c2011-06-03 14:28:43 +00003819
3820 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
3821 assert(MSInfo && "Missing member specialization information?");
3822 if (MSInfo->getTemplateSpecializationKind()
3823 != TSK_ExplicitSpecialization) {
3824 // If we don't already have a point of instantiation, this is it.
3825 if (MSInfo->getPointOfInstantiation().isInvalid()) {
3826 MSInfo->setPointOfInstantiation(E->getLocStart());
3827
3828 // This is a modification of an existing AST node. Notify
3829 // listeners.
3830 if (ASTMutationListener *L = getASTMutationListener())
3831 L->StaticDataMemberInstantiated(Var);
3832 }
3833
3834 InstantiateStaticDataMemberDefinition(E->getExprLoc(), Var);
3835
3836 // Update the type to the newly instantiated definition's type both
3837 // here and within the expression.
3838 if (VarDecl *Def = Var->getDefinition()) {
3839 DRE->setDecl(Def);
3840 T = Def->getType();
3841 DRE->setType(T);
3842 E->setType(T);
3843 }
Douglas Gregorf15748a2011-06-03 03:35:07 +00003844 }
3845
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003846 // We still go on to try to complete the type independently, as it
3847 // may also require instantiations or diagnostics if it remains
3848 // incomplete.
3849 }
3850 }
3851 }
3852 }
3853
3854 // FIXME: Are there other cases which require instantiating something other
3855 // than the type to complete the type of an expression?
3856
3857 // Look through reference types and complete the referred type.
3858 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
3859 T = Ref->getPointeeType();
3860
3861 return RequireCompleteType(E->getExprLoc(), T, PD, Note);
3862}
3863
Mike Stump1eb44332009-09-09 15:08:12 +00003864/// @brief Ensure that the type T is a complete type.
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003865///
3866/// This routine checks whether the type @p T is complete in any
3867/// context where a complete type is required. If @p T is a complete
Douglas Gregor86447ec2009-03-09 16:13:40 +00003868/// type, returns false. If @p T is a class template specialization,
3869/// this routine then attempts to perform class template
3870/// instantiation. If instantiation fails, or if @p T is incomplete
3871/// and cannot be completed, issues the diagnostic @p diag (giving it
3872/// the type @p T) and returns true.
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003873///
3874/// @param Loc The location in the source that the incomplete type
3875/// diagnostic should refer to.
3876///
3877/// @param T The type that this routine is examining for completeness.
3878///
Mike Stump1eb44332009-09-09 15:08:12 +00003879/// @param PD The partial diagnostic that will be printed out if T is not a
Anders Carlssonb7906612009-08-26 23:45:07 +00003880/// complete type.
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003881///
3882/// @returns @c true if @p T is incomplete and a diagnostic was emitted,
3883/// @c false otherwise.
Anders Carlsson91a0cc92009-08-26 22:33:56 +00003884bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
Anders Carlsson8c8d9192009-10-09 23:51:55 +00003885 const PartialDiagnostic &PD,
3886 std::pair<SourceLocation,
3887 PartialDiagnostic> Note) {
Anders Carlsson91a0cc92009-08-26 22:33:56 +00003888 unsigned diag = PD.getDiagID();
Mike Stump1eb44332009-09-09 15:08:12 +00003889
Douglas Gregor573d9c32009-10-21 23:19:44 +00003890 // FIXME: Add this assertion to make sure we always get instantiation points.
3891 // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
Douglas Gregor690dc7f2009-05-21 23:48:18 +00003892 // FIXME: Add this assertion to help us flush out problems with
3893 // checking for dependent types and type-dependent expressions.
3894 //
Mike Stump1eb44332009-09-09 15:08:12 +00003895 // assert(!T->isDependentType() &&
Douglas Gregor690dc7f2009-05-21 23:48:18 +00003896 // "Can't ask whether a dependent type is complete");
3897
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003898 // If we have a complete type, we're done.
3899 if (!T->isIncompleteType())
3900 return false;
Eli Friedman3c0eb162008-05-27 03:33:27 +00003901
Douglas Gregord475b8d2009-03-25 21:17:03 +00003902 // If we have a class template specialization or a class member of a
Sebastian Redl923d56d2009-11-05 15:52:31 +00003903 // class template specialization, or an array with known size of such,
3904 // try to instantiate it.
3905 QualType MaybeTemplate = T;
Douglas Gregor89c49f02009-11-09 22:08:55 +00003906 if (const ConstantArrayType *Array = Context.getAsConstantArrayType(T))
Sebastian Redl923d56d2009-11-05 15:52:31 +00003907 MaybeTemplate = Array->getElementType();
3908 if (const RecordType *Record = MaybeTemplate->getAs<RecordType>()) {
Douglas Gregor2943aed2009-03-03 04:44:36 +00003909 if (ClassTemplateSpecializationDecl *ClassTemplateSpec
Douglas Gregord475b8d2009-03-25 21:17:03 +00003910 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
Douglas Gregor972e6ce2009-10-27 06:26:26 +00003911 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared)
3912 return InstantiateClassTemplateSpecialization(Loc, ClassTemplateSpec,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00003913 TSK_ImplicitInstantiation,
Douglas Gregor5842ba92009-08-24 15:23:48 +00003914 /*Complain=*/diag != 0);
Mike Stump1eb44332009-09-09 15:08:12 +00003915 } else if (CXXRecordDecl *Rec
Douglas Gregord475b8d2009-03-25 21:17:03 +00003916 = dyn_cast<CXXRecordDecl>(Record->getDecl())) {
3917 if (CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass()) {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003918 MemberSpecializationInfo *MSInfo = Rec->getMemberSpecializationInfo();
3919 assert(MSInfo && "Missing member specialization information?");
Douglas Gregor357bbd02009-08-28 20:50:45 +00003920 // This record was instantiated from a class within a template.
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003921 if (MSInfo->getTemplateSpecializationKind()
Douglas Gregor972e6ce2009-10-27 06:26:26 +00003922 != TSK_ExplicitSpecialization)
Douglas Gregorf6b11852009-10-08 15:14:33 +00003923 return InstantiateClass(Loc, Rec, Pattern,
3924 getTemplateInstantiationArgs(Rec),
3925 TSK_ImplicitInstantiation,
3926 /*Complain=*/diag != 0);
Douglas Gregord475b8d2009-03-25 21:17:03 +00003927 }
3928 }
3929 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00003930
Douglas Gregor5842ba92009-08-24 15:23:48 +00003931 if (diag == 0)
3932 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003933
John McCall916c8702010-11-16 01:44:35 +00003934 const TagType *Tag = T->getAs<TagType>();
Rafael Espindola01620702010-03-21 22:56:43 +00003935
3936 // Avoid diagnosing invalid decls as incomplete.
3937 if (Tag && Tag->getDecl()->isInvalidDecl())
3938 return true;
3939
John McCall916c8702010-11-16 01:44:35 +00003940 // Give the external AST source a chance to complete the type.
3941 if (Tag && Tag->getDecl()->hasExternalLexicalStorage()) {
3942 Context.getExternalSource()->CompleteType(Tag->getDecl());
3943 if (!Tag->isIncompleteType())
3944 return false;
3945 }
3946
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003947 // We have an incomplete type. Produce a diagnostic.
Anders Carlsson91a0cc92009-08-26 22:33:56 +00003948 Diag(Loc, PD) << T;
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003949
Anders Carlsson8c8d9192009-10-09 23:51:55 +00003950 // If we have a note, produce it.
3951 if (!Note.first.isInvalid())
3952 Diag(Note.first, Note.second);
3953
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003954 // If the type was a forward declaration of a class/struct/union
Rafael Espindola01620702010-03-21 22:56:43 +00003955 // type, produce a note.
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003956 if (Tag && !Tag->getDecl()->isInvalidDecl())
Mike Stump1eb44332009-09-09 15:08:12 +00003957 Diag(Tag->getDecl()->getLocation(),
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003958 Tag->isBeingDefined() ? diag::note_type_being_defined
3959 : diag::note_forward_declaration)
3960 << QualType(Tag, 0);
3961
3962 return true;
3963}
Douglas Gregore6258932009-03-19 00:39:20 +00003964
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003965bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
3966 const PartialDiagnostic &PD) {
3967 return RequireCompleteType(Loc, T, PD,
3968 std::make_pair(SourceLocation(), PDiag(0)));
3969}
3970
3971bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
3972 unsigned DiagID) {
3973 return RequireCompleteType(Loc, T, PDiag(DiagID),
3974 std::make_pair(SourceLocation(), PDiag(0)));
3975}
3976
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003977/// \brief Retrieve a version of the type 'T' that is elaborated by Keyword
3978/// and qualified by the nested-name-specifier contained in SS.
3979QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword,
3980 const CXXScopeSpec &SS, QualType T) {
3981 if (T.isNull())
Douglas Gregore6258932009-03-19 00:39:20 +00003982 return T;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003983 NestedNameSpecifier *NNS;
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00003984 if (SS.isValid())
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003985 NNS = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3986 else {
3987 if (Keyword == ETK_None)
3988 return T;
3989 NNS = 0;
3990 }
3991 return Context.getElaboratedType(Keyword, NNS, T);
Douglas Gregore6258932009-03-19 00:39:20 +00003992}
Anders Carlssonaf017e62009-06-29 22:58:55 +00003993
John McCall2a984ca2010-10-12 00:20:44 +00003994QualType Sema::BuildTypeofExprType(Expr *E, SourceLocation Loc) {
John McCallfb8721c2011-04-10 19:13:55 +00003995 ExprResult ER = CheckPlaceholderExpr(E);
John McCall2a984ca2010-10-12 00:20:44 +00003996 if (ER.isInvalid()) return QualType();
3997 E = ER.take();
3998
Fariborz Jahanian2b1d51b2010-10-05 23:24:00 +00003999 if (!E->isTypeDependent()) {
4000 QualType T = E->getType();
Fariborz Jahanianaca7f7b2010-10-06 00:23:25 +00004001 if (const TagType *TT = T->getAs<TagType>())
4002 DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc());
Fariborz Jahanian2b1d51b2010-10-05 23:24:00 +00004003 }
Anders Carlssonaf017e62009-06-29 22:58:55 +00004004 return Context.getTypeOfExprType(E);
4005}
4006
John McCall2a984ca2010-10-12 00:20:44 +00004007QualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc) {
John McCallfb8721c2011-04-10 19:13:55 +00004008 ExprResult ER = CheckPlaceholderExpr(E);
John McCall2a984ca2010-10-12 00:20:44 +00004009 if (ER.isInvalid()) return QualType();
4010 E = ER.take();
Douglas Gregor4b52e252009-12-21 23:17:24 +00004011
Anders Carlssonaf017e62009-06-29 22:58:55 +00004012 return Context.getDecltypeType(E);
4013}
Sean Huntca63c202011-05-24 22:41:36 +00004014
4015QualType Sema::BuildUnaryTransformType(QualType BaseType,
4016 UnaryTransformType::UTTKind UKind,
4017 SourceLocation Loc) {
4018 switch (UKind) {
4019 case UnaryTransformType::EnumUnderlyingType:
4020 if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) {
4021 Diag(Loc, diag::err_only_enums_have_underlying_types);
4022 return QualType();
4023 } else {
4024 QualType Underlying = BaseType;
4025 if (!BaseType->isDependentType()) {
4026 EnumDecl *ED = BaseType->getAs<EnumType>()->getDecl();
4027 assert(ED && "EnumType has no EnumDecl");
4028 DiagnoseUseOfDecl(ED, Loc);
4029 Underlying = ED->getIntegerType();
4030 }
4031 assert(!Underlying.isNull());
4032 return Context.getUnaryTransformType(BaseType, Underlying,
4033 UnaryTransformType::EnumUnderlyingType);
4034 }
4035 }
4036 llvm_unreachable("unknown unary transform type");
4037}