blob: e44c6c8b4190135ef963c7e375390fc61de1b62d [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 &&
667 !S.getLangOptions().Microsoft) {
668 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
1041 // If that failed, give an error and recover using __autoreleasing.
1042 } else {
1043 // These types can show up in private ivars in system headers, so
1044 // we need this to not be an error in those cases. Instead we
1045 // want to delay.
1046 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
1047 S.DelayedDiagnostics.add(
1048 sema::DelayedDiagnostic::makeForbiddenType(loc,
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00001049 diag::err_arc_indirect_no_ownership, type, isReference));
John McCallf85e1932011-06-15 23:02:42 +00001050 } else {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00001051 S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference;
John McCallf85e1932011-06-15 23:02:42 +00001052 }
1053 implicitLifetime = Qualifiers::OCL_Autoreleasing;
1054 }
1055 assert(implicitLifetime && "didn't infer any lifetime!");
1056
1057 Qualifiers qs;
1058 qs.addObjCLifetime(implicitLifetime);
1059 return S.Context.getQualifiedType(type, qs);
1060}
1061
Douglas Gregorcd281c32009-02-28 00:25:32 +00001062/// \brief Build a pointer type.
1063///
1064/// \param T The type to which we'll be building a pointer.
1065///
Douglas Gregorcd281c32009-02-28 00:25:32 +00001066/// \param Loc The location of the entity whose type involves this
1067/// pointer type or, if there is no such entity, the location of the
1068/// type that will have pointer type.
1069///
1070/// \param Entity The name of the entity that involves the pointer
1071/// type, if known.
1072///
1073/// \returns A suitable pointer type, if there are no
1074/// errors. Otherwise, returns a NULL type.
John McCall28654742010-06-05 06:41:15 +00001075QualType Sema::BuildPointerType(QualType T,
Douglas Gregorcd281c32009-02-28 00:25:32 +00001076 SourceLocation Loc, DeclarationName Entity) {
1077 if (T->isReferenceType()) {
1078 // C++ 8.3.2p4: There shall be no ... pointers to references ...
1079 Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
John McCallac406052009-10-30 00:37:20 +00001080 << getPrintableNameForEntity(Entity) << T;
Douglas Gregorcd281c32009-02-28 00:25:32 +00001081 return QualType();
1082 }
1083
John McCallc12c5bb2010-05-15 11:32:37 +00001084 assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType");
Douglas Gregor92e986e2010-04-22 16:44:27 +00001085
John McCallf85e1932011-06-15 23:02:42 +00001086 // In ARC, it is forbidden to build pointers to unqualified pointers.
1087 if (getLangOptions().ObjCAutoRefCount)
1088 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false);
1089
Douglas Gregorcd281c32009-02-28 00:25:32 +00001090 // Build the pointer type.
John McCall28654742010-06-05 06:41:15 +00001091 return Context.getPointerType(T);
Douglas Gregorcd281c32009-02-28 00:25:32 +00001092}
1093
1094/// \brief Build a reference type.
1095///
1096/// \param T The type to which we'll be building a reference.
1097///
Douglas Gregorcd281c32009-02-28 00:25:32 +00001098/// \param Loc The location of the entity whose type involves this
1099/// reference type or, if there is no such entity, the location of the
1100/// type that will have reference type.
1101///
1102/// \param Entity The name of the entity that involves the reference
1103/// type, if known.
1104///
1105/// \returns A suitable reference type, if there are no
1106/// errors. Otherwise, returns a NULL type.
John McCall54e14c42009-10-22 22:37:11 +00001107QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue,
John McCall28654742010-06-05 06:41:15 +00001108 SourceLocation Loc,
John McCall54e14c42009-10-22 22:37:11 +00001109 DeclarationName Entity) {
Douglas Gregor9625e442011-05-21 22:16:50 +00001110 assert(Context.getCanonicalType(T) != Context.OverloadTy &&
1111 "Unresolved overloaded function type");
1112
Douglas Gregor69d83162011-01-20 16:08:06 +00001113 // C++0x [dcl.ref]p6:
1114 // If a typedef (7.1.3), a type template-parameter (14.3.1), or a
1115 // decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a
1116 // type T, an attempt to create the type "lvalue reference to cv TR" creates
1117 // the type "lvalue reference to T", while an attempt to create the type
1118 // "rvalue reference to cv TR" creates the type TR.
John McCall54e14c42009-10-22 22:37:11 +00001119 bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
1120
John McCall54e14c42009-10-22 22:37:11 +00001121 // C++ [dcl.ref]p4: There shall be no references to references.
1122 //
1123 // According to C++ DR 106, references to references are only
1124 // diagnosed when they are written directly (e.g., "int & &"),
1125 // but not when they happen via a typedef:
1126 //
1127 // typedef int& intref;
1128 // typedef intref& intref2;
1129 //
1130 // Parser::ParseDeclaratorInternal diagnoses the case where
1131 // references are written directly; here, we handle the
Douglas Gregor69d83162011-01-20 16:08:06 +00001132 // collapsing of references-to-references as described in C++0x.
1133 // DR 106 and 540 introduce reference-collapsing into C++98/03.
Douglas Gregorcd281c32009-02-28 00:25:32 +00001134
1135 // C++ [dcl.ref]p1:
Eli Friedman33a31382009-08-05 19:21:58 +00001136 // A declarator that specifies the type "reference to cv void"
Douglas Gregorcd281c32009-02-28 00:25:32 +00001137 // is ill-formed.
1138 if (T->isVoidType()) {
1139 Diag(Loc, diag::err_reference_to_void);
1140 return QualType();
1141 }
1142
John McCallf85e1932011-06-15 23:02:42 +00001143 // In ARC, it is forbidden to build references to unqualified pointers.
1144 if (getLangOptions().ObjCAutoRefCount)
1145 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true);
1146
Douglas Gregorcd281c32009-02-28 00:25:32 +00001147 // Handle restrict on references.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001148 if (LValueRef)
John McCall28654742010-06-05 06:41:15 +00001149 return Context.getLValueReferenceType(T, SpelledAsLValue);
1150 return Context.getRValueReferenceType(T);
Douglas Gregorcd281c32009-02-28 00:25:32 +00001151}
1152
Chris Lattnere1eed382011-06-14 06:38:10 +00001153/// Check whether the specified array size makes the array type a VLA. If so,
1154/// return true, if not, return the size of the array in SizeVal.
1155static bool isArraySizeVLA(Expr *ArraySize, llvm::APSInt &SizeVal, Sema &S) {
1156 // If the size is an ICE, it certainly isn't a VLA.
1157 if (ArraySize->isIntegerConstantExpr(SizeVal, S.Context))
1158 return false;
1159
1160 // If we're in a GNU mode (like gnu99, but not c99) accept any evaluatable
1161 // value as an extension.
1162 Expr::EvalResult Result;
1163 if (S.LangOpts.GNUMode && ArraySize->Evaluate(Result, S.Context)) {
1164 if (!Result.hasSideEffects() && Result.Val.isInt()) {
1165 SizeVal = Result.Val.getInt();
1166 S.Diag(ArraySize->getLocStart(), diag::ext_vla_folded_to_constant);
1167 return false;
1168 }
1169 }
1170
1171 return true;
1172}
1173
1174
Douglas Gregorcd281c32009-02-28 00:25:32 +00001175/// \brief Build an array type.
1176///
1177/// \param T The type of each element in the array.
1178///
1179/// \param ASM C99 array size modifier (e.g., '*', 'static').
Mike Stump1eb44332009-09-09 15:08:12 +00001180///
1181/// \param ArraySize Expression describing the size of the array.
Douglas Gregorcd281c32009-02-28 00:25:32 +00001182///
Douglas Gregorcd281c32009-02-28 00:25:32 +00001183/// \param Loc The location of the entity whose type involves this
1184/// array type or, if there is no such entity, the location of the
1185/// type that will have array type.
1186///
1187/// \param Entity The name of the entity that involves the array
1188/// type, if known.
1189///
1190/// \returns A suitable array type, if there are no errors. Otherwise,
1191/// returns a NULL type.
1192QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1193 Expr *ArraySize, unsigned Quals,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001194 SourceRange Brackets, DeclarationName Entity) {
John McCall0953e762009-09-24 19:53:00 +00001195
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001196 SourceLocation Loc = Brackets.getBegin();
Sebastian Redl923d56d2009-11-05 15:52:31 +00001197 if (getLangOptions().CPlusPlus) {
Douglas Gregor138bb232010-04-27 19:38:14 +00001198 // C++ [dcl.array]p1:
1199 // T is called the array element type; this type shall not be a reference
1200 // type, the (possibly cv-qualified) type void, a function type or an
1201 // abstract class type.
1202 //
1203 // Note: function types are handled in the common path with C.
1204 if (T->isReferenceType()) {
1205 Diag(Loc, diag::err_illegal_decl_array_of_references)
1206 << getPrintableNameForEntity(Entity) << T;
1207 return QualType();
1208 }
1209
Sebastian Redl923d56d2009-11-05 15:52:31 +00001210 if (T->isVoidType()) {
1211 Diag(Loc, diag::err_illegal_decl_array_incomplete_type) << T;
1212 return QualType();
1213 }
Douglas Gregor138bb232010-04-27 19:38:14 +00001214
1215 if (RequireNonAbstractType(Brackets.getBegin(), T,
1216 diag::err_array_of_abstract_type))
1217 return QualType();
1218
Sebastian Redl923d56d2009-11-05 15:52:31 +00001219 } else {
Douglas Gregor138bb232010-04-27 19:38:14 +00001220 // C99 6.7.5.2p1: If the element type is an incomplete or function type,
1221 // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
Sebastian Redl923d56d2009-11-05 15:52:31 +00001222 if (RequireCompleteType(Loc, T,
1223 diag::err_illegal_decl_array_incomplete_type))
1224 return QualType();
1225 }
Douglas Gregorcd281c32009-02-28 00:25:32 +00001226
1227 if (T->isFunctionType()) {
1228 Diag(Loc, diag::err_illegal_decl_array_of_functions)
John McCallac406052009-10-30 00:37:20 +00001229 << getPrintableNameForEntity(Entity) << T;
Douglas Gregorcd281c32009-02-28 00:25:32 +00001230 return QualType();
1231 }
Mike Stump1eb44332009-09-09 15:08:12 +00001232
Richard Smith34b41d92011-02-20 03:19:35 +00001233 if (T->getContainedAutoType()) {
1234 Diag(Loc, diag::err_illegal_decl_array_of_auto)
1235 << getPrintableNameForEntity(Entity) << T;
Anders Carlssone7cf07d2009-06-26 19:33:28 +00001236 return QualType();
1237 }
Mike Stump1eb44332009-09-09 15:08:12 +00001238
Ted Kremenek6217b802009-07-29 21:53:49 +00001239 if (const RecordType *EltTy = T->getAs<RecordType>()) {
Douglas Gregorcd281c32009-02-28 00:25:32 +00001240 // If the element type is a struct or union that contains a variadic
1241 // array, accept it as a GNU extension: C99 6.7.2.1p2.
1242 if (EltTy->getDecl()->hasFlexibleArrayMember())
1243 Diag(Loc, diag::ext_flexible_array_in_array) << T;
John McCallc12c5bb2010-05-15 11:32:37 +00001244 } else if (T->isObjCObjectType()) {
Chris Lattnerc7c11b12009-04-27 01:55:56 +00001245 Diag(Loc, diag::err_objc_array_of_interfaces) << T;
1246 return QualType();
Douglas Gregorcd281c32009-02-28 00:25:32 +00001247 }
Mike Stump1eb44332009-09-09 15:08:12 +00001248
John McCall5e3c67b2010-12-15 04:42:30 +00001249 // Do lvalue-to-rvalue conversions on the array size expression.
John Wiegley429bb272011-04-08 18:41:53 +00001250 if (ArraySize && !ArraySize->isRValue()) {
1251 ExprResult Result = DefaultLvalueConversion(ArraySize);
1252 if (Result.isInvalid())
1253 return QualType();
1254
1255 ArraySize = Result.take();
1256 }
John McCall5e3c67b2010-12-15 04:42:30 +00001257
Douglas Gregorcd281c32009-02-28 00:25:32 +00001258 // C99 6.7.5.2p1: The size expression shall have integer type.
John McCall5e3c67b2010-12-15 04:42:30 +00001259 // TODO: in theory, if we were insane, we could allow contextual
1260 // conversions to integer type here.
Douglas Gregorcd281c32009-02-28 00:25:32 +00001261 if (ArraySize && !ArraySize->isTypeDependent() &&
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001262 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
Douglas Gregorcd281c32009-02-28 00:25:32 +00001263 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
1264 << ArraySize->getType() << ArraySize->getSourceRange();
Douglas Gregorcd281c32009-02-28 00:25:32 +00001265 return QualType();
1266 }
Douglas Gregor2767ce22010-08-18 00:39:00 +00001267 llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType()));
Douglas Gregorcd281c32009-02-28 00:25:32 +00001268 if (!ArraySize) {
Eli Friedmanf91f5c82009-04-26 21:57:51 +00001269 if (ASM == ArrayType::Star)
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001270 T = Context.getVariableArrayType(T, 0, ASM, Quals, Brackets);
Eli Friedmanf91f5c82009-04-26 21:57:51 +00001271 else
1272 T = Context.getIncompleteArrayType(T, ASM, Quals);
Douglas Gregorac06a0e2010-05-18 23:01:22 +00001273 } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) {
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001274 T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets);
Chris Lattnere1eed382011-06-14 06:38:10 +00001275 } else if (!T->isDependentType() && !T->isIncompleteType() &&
1276 !T->isConstantSizeType()) {
1277 // C99: an array with an element type that has a non-constant-size is a VLA.
1278 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
1279 } else if (isArraySizeVLA(ArraySize, ConstVal, *this)) {
1280 // C99: an array with a non-ICE size is a VLA. We accept any expression
1281 // that we can fold to a non-zero positive value as an extension.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001282 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
Douglas Gregorcd281c32009-02-28 00:25:32 +00001283 } else {
1284 // C99 6.7.5.2p1: If the expression is a constant expression, it shall
1285 // have a value greater than zero.
Sebastian Redl923d56d2009-11-05 15:52:31 +00001286 if (ConstVal.isSigned() && ConstVal.isNegative()) {
Chandler Carruthb2b5cc02011-01-04 04:44:35 +00001287 if (Entity)
1288 Diag(ArraySize->getLocStart(), diag::err_decl_negative_array_size)
1289 << getPrintableNameForEntity(Entity) << ArraySize->getSourceRange();
1290 else
1291 Diag(ArraySize->getLocStart(), diag::err_typecheck_negative_array_size)
1292 << ArraySize->getSourceRange();
Sebastian Redl923d56d2009-11-05 15:52:31 +00001293 return QualType();
1294 }
1295 if (ConstVal == 0) {
Douglas Gregor02024a92010-03-28 02:42:43 +00001296 // GCC accepts zero sized static arrays. We allow them when
1297 // we're not in a SFINAE context.
1298 Diag(ArraySize->getLocStart(),
1299 isSFINAEContext()? diag::err_typecheck_zero_array_size
1300 : diag::ext_typecheck_zero_array_size)
Sebastian Redl923d56d2009-11-05 15:52:31 +00001301 << ArraySize->getSourceRange();
Douglas Gregor2767ce22010-08-18 00:39:00 +00001302 } else if (!T->isDependentType() && !T->isVariablyModifiedType() &&
1303 !T->isIncompleteType()) {
1304 // Is the array too large?
1305 unsigned ActiveSizeBits
1306 = ConstantArrayType::getNumAddressingBits(Context, T, ConstVal);
1307 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
1308 Diag(ArraySize->getLocStart(), diag::err_array_too_large)
1309 << ConstVal.toString(10)
1310 << ArraySize->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001311 }
Douglas Gregor2767ce22010-08-18 00:39:00 +00001312
John McCall46a617a2009-10-16 00:14:28 +00001313 T = Context.getConstantArrayType(T, ConstVal, ASM, Quals);
Douglas Gregorcd281c32009-02-28 00:25:32 +00001314 }
David Chisnallaf407762010-01-11 23:08:08 +00001315 // If this is not C99, extwarn about VLA's and C99 array size modifiers.
1316 if (!getLangOptions().C99) {
Douglas Gregor0fddb972010-05-22 16:17:30 +00001317 if (T->isVariableArrayType()) {
1318 // Prohibit the use of non-POD types in VLAs.
John McCallf85e1932011-06-15 23:02:42 +00001319 QualType BaseT = Context.getBaseElementType(T);
Douglas Gregor204ce172010-05-24 20:42:30 +00001320 if (!T->isDependentType() &&
John McCallf85e1932011-06-15 23:02:42 +00001321 !BaseT.isPODType(Context) &&
1322 !BaseT->isObjCLifetimeType()) {
Douglas Gregor0fddb972010-05-22 16:17:30 +00001323 Diag(Loc, diag::err_vla_non_pod)
John McCallf85e1932011-06-15 23:02:42 +00001324 << BaseT;
Douglas Gregor0fddb972010-05-22 16:17:30 +00001325 return QualType();
1326 }
Douglas Gregora481ec42010-05-23 19:57:01 +00001327 // Prohibit the use of VLAs during template argument deduction.
1328 else if (isSFINAEContext()) {
1329 Diag(Loc, diag::err_vla_in_sfinae);
1330 return QualType();
1331 }
Douglas Gregor0fddb972010-05-22 16:17:30 +00001332 // Just extwarn about VLAs.
1333 else
1334 Diag(Loc, diag::ext_vla);
1335 } else if (ASM != ArrayType::Normal || Quals != 0)
Douglas Gregor043cad22009-09-11 00:18:58 +00001336 Diag(Loc,
1337 getLangOptions().CPlusPlus? diag::err_c99_array_usage_cxx
1338 : diag::ext_c99_array_usage);
Douglas Gregorcd281c32009-02-28 00:25:32 +00001339 }
1340
1341 return T;
1342}
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001343
1344/// \brief Build an ext-vector type.
1345///
1346/// Run the required checks for the extended vector type.
John McCall9ae2f072010-08-23 23:25:46 +00001347QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize,
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001348 SourceLocation AttrLoc) {
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001349 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1350 // in conjunction with complex types (pointers, arrays, functions, etc.).
Mike Stump1eb44332009-09-09 15:08:12 +00001351 if (!T->isDependentType() &&
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001352 !T->isIntegerType() && !T->isRealFloatingType()) {
1353 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
1354 return QualType();
1355 }
1356
John McCall9ae2f072010-08-23 23:25:46 +00001357 if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) {
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001358 llvm::APSInt vecSize(32);
John McCall9ae2f072010-08-23 23:25:46 +00001359 if (!ArraySize->isIntegerConstantExpr(vecSize, Context)) {
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001360 Diag(AttrLoc, diag::err_attribute_argument_not_int)
John McCall9ae2f072010-08-23 23:25:46 +00001361 << "ext_vector_type" << ArraySize->getSourceRange();
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001362 return QualType();
1363 }
Mike Stump1eb44332009-09-09 15:08:12 +00001364
1365 // unlike gcc's vector_size attribute, the size is specified as the
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001366 // number of elements, not the number of bytes.
Mike Stump1eb44332009-09-09 15:08:12 +00001367 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
1368
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001369 if (vectorSize == 0) {
1370 Diag(AttrLoc, diag::err_attribute_zero_size)
John McCall9ae2f072010-08-23 23:25:46 +00001371 << ArraySize->getSourceRange();
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001372 return QualType();
1373 }
Mike Stump1eb44332009-09-09 15:08:12 +00001374
Douglas Gregor4ac01402011-06-15 16:02:29 +00001375 return Context.getExtVectorType(T, vectorSize);
Mike Stump1eb44332009-09-09 15:08:12 +00001376 }
1377
John McCall9ae2f072010-08-23 23:25:46 +00001378 return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc);
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001379}
Mike Stump1eb44332009-09-09 15:08:12 +00001380
Douglas Gregor724651c2009-02-28 01:04:19 +00001381/// \brief Build a function type.
1382///
1383/// This routine checks the function type according to C++ rules and
1384/// under the assumption that the result type and parameter types have
1385/// just been instantiated from a template. It therefore duplicates
Douglas Gregor2943aed2009-03-03 04:44:36 +00001386/// some of the behavior of GetTypeForDeclarator, but in a much
Douglas Gregor724651c2009-02-28 01:04:19 +00001387/// simpler form that is only suitable for this narrow use case.
1388///
1389/// \param T The return type of the function.
1390///
1391/// \param ParamTypes The parameter types of the function. This array
1392/// will be modified to account for adjustments to the types of the
1393/// function parameters.
1394///
1395/// \param NumParamTypes The number of parameter types in ParamTypes.
1396///
1397/// \param Variadic Whether this is a variadic function type.
1398///
1399/// \param Quals The cvr-qualifiers to be applied to the function type.
1400///
1401/// \param Loc The location of the entity whose type involves this
1402/// function type or, if there is no such entity, the location of the
1403/// type that will have function type.
1404///
1405/// \param Entity The name of the entity that involves the function
1406/// type, if known.
1407///
1408/// \returns A suitable function type, if there are no
1409/// errors. Otherwise, returns a NULL type.
1410QualType Sema::BuildFunctionType(QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00001411 QualType *ParamTypes,
Douglas Gregor724651c2009-02-28 01:04:19 +00001412 unsigned NumParamTypes,
1413 bool Variadic, unsigned Quals,
Douglas Gregorc938c162011-01-26 05:01:58 +00001414 RefQualifierKind RefQualifier,
Eli Friedmanfa869542010-08-05 02:54:05 +00001415 SourceLocation Loc, DeclarationName Entity,
John McCalle23cf432010-12-14 08:05:40 +00001416 FunctionType::ExtInfo Info) {
Douglas Gregor724651c2009-02-28 01:04:19 +00001417 if (T->isArrayType() || T->isFunctionType()) {
Douglas Gregor58408bc2010-01-11 18:46:21 +00001418 Diag(Loc, diag::err_func_returning_array_function)
1419 << T->isFunctionType() << T;
Douglas Gregor724651c2009-02-28 01:04:19 +00001420 return QualType();
1421 }
Douglas Gregor5291c3c2010-07-13 08:18:22 +00001422
Douglas Gregor724651c2009-02-28 01:04:19 +00001423 bool Invalid = false;
1424 for (unsigned Idx = 0; Idx < NumParamTypes; ++Idx) {
Douglas Gregor79e6bd32011-07-12 04:42:08 +00001425 QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001426 if (ParamType->isVoidType()) {
Douglas Gregor724651c2009-02-28 01:04:19 +00001427 Diag(Loc, diag::err_param_with_void_type);
1428 Invalid = true;
1429 }
Douglas Gregorcd281c32009-02-28 00:25:32 +00001430
John McCall54e14c42009-10-22 22:37:11 +00001431 ParamTypes[Idx] = ParamType;
Douglas Gregor724651c2009-02-28 01:04:19 +00001432 }
1433
1434 if (Invalid)
1435 return QualType();
1436
John McCalle23cf432010-12-14 08:05:40 +00001437 FunctionProtoType::ExtProtoInfo EPI;
1438 EPI.Variadic = Variadic;
1439 EPI.TypeQuals = Quals;
Douglas Gregorc938c162011-01-26 05:01:58 +00001440 EPI.RefQualifier = RefQualifier;
John McCalle23cf432010-12-14 08:05:40 +00001441 EPI.ExtInfo = Info;
1442
1443 return Context.getFunctionType(T, ParamTypes, NumParamTypes, EPI);
Douglas Gregor724651c2009-02-28 01:04:19 +00001444}
Mike Stump1eb44332009-09-09 15:08:12 +00001445
Douglas Gregor949bf692009-06-09 22:17:39 +00001446/// \brief Build a member pointer type \c T Class::*.
1447///
1448/// \param T the type to which the member pointer refers.
1449/// \param Class the class type into which the member pointer points.
John McCall0953e762009-09-24 19:53:00 +00001450/// \param CVR Qualifiers applied to the member pointer type
Douglas Gregor949bf692009-06-09 22:17:39 +00001451/// \param Loc the location where this type begins
1452/// \param Entity the name of the entity that will have this member pointer type
1453///
1454/// \returns a member pointer type, if successful, or a NULL type if there was
1455/// an error.
Mike Stump1eb44332009-09-09 15:08:12 +00001456QualType Sema::BuildMemberPointerType(QualType T, QualType Class,
John McCall28654742010-06-05 06:41:15 +00001457 SourceLocation Loc,
Douglas Gregor949bf692009-06-09 22:17:39 +00001458 DeclarationName Entity) {
1459 // Verify that we're not building a pointer to pointer to function with
1460 // exception specification.
1461 if (CheckDistantExceptionSpec(T)) {
1462 Diag(Loc, diag::err_distant_exception_spec);
1463
1464 // FIXME: If we're doing this as part of template instantiation,
1465 // we should return immediately.
1466
1467 // Build the type anyway, but use the canonical type so that the
1468 // exception specifiers are stripped off.
1469 T = Context.getCanonicalType(T);
1470 }
1471
Sebastian Redl73780122010-06-09 21:19:43 +00001472 // C++ 8.3.3p3: A pointer to member shall not point to ... a member
Douglas Gregor949bf692009-06-09 22:17:39 +00001473 // with reference type, or "cv void."
1474 if (T->isReferenceType()) {
Anders Carlsson8d4655d2009-06-30 00:06:57 +00001475 Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
John McCallac406052009-10-30 00:37:20 +00001476 << (Entity? Entity.getAsString() : "type name") << T;
Douglas Gregor949bf692009-06-09 22:17:39 +00001477 return QualType();
1478 }
1479
1480 if (T->isVoidType()) {
1481 Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
1482 << (Entity? Entity.getAsString() : "type name");
1483 return QualType();
1484 }
1485
Douglas Gregor949bf692009-06-09 22:17:39 +00001486 if (!Class->isDependentType() && !Class->isRecordType()) {
1487 Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
1488 return QualType();
1489 }
1490
Charles Davisd18f9f92010-08-16 04:01:50 +00001491 // In the Microsoft ABI, the class is allowed to be an incomplete
1492 // type. In such cases, the compiler makes a worst-case assumption.
1493 // We make no such assumption right now, so emit an error if the
1494 // class isn't a complete type.
Charles Davis20cf7172010-08-19 02:18:14 +00001495 if (Context.Target.getCXXABI() == CXXABI_Microsoft &&
Charles Davisd18f9f92010-08-16 04:01:50 +00001496 RequireCompleteType(Loc, Class, diag::err_incomplete_type))
1497 return QualType();
1498
John McCall28654742010-06-05 06:41:15 +00001499 return Context.getMemberPointerType(T, Class.getTypePtr());
Douglas Gregor949bf692009-06-09 22:17:39 +00001500}
Mike Stump1eb44332009-09-09 15:08:12 +00001501
Anders Carlsson9a917e42009-06-12 22:56:54 +00001502/// \brief Build a block pointer type.
1503///
1504/// \param T The type to which we'll be building a block pointer.
1505///
John McCall0953e762009-09-24 19:53:00 +00001506/// \param CVR The cvr-qualifiers to be applied to the block pointer type.
Anders Carlsson9a917e42009-06-12 22:56:54 +00001507///
1508/// \param Loc The location of the entity whose type involves this
1509/// block pointer type or, if there is no such entity, the location of the
1510/// type that will have block pointer type.
1511///
1512/// \param Entity The name of the entity that involves the block pointer
1513/// type, if known.
1514///
1515/// \returns A suitable block pointer type, if there are no
1516/// errors. Otherwise, returns a NULL type.
John McCall28654742010-06-05 06:41:15 +00001517QualType Sema::BuildBlockPointerType(QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00001518 SourceLocation Loc,
Anders Carlsson9a917e42009-06-12 22:56:54 +00001519 DeclarationName Entity) {
John McCall0953e762009-09-24 19:53:00 +00001520 if (!T->isFunctionType()) {
Anders Carlsson9a917e42009-06-12 22:56:54 +00001521 Diag(Loc, diag::err_nonfunction_block_type);
1522 return QualType();
1523 }
Mike Stump1eb44332009-09-09 15:08:12 +00001524
John McCall28654742010-06-05 06:41:15 +00001525 return Context.getBlockPointerType(T);
Anders Carlsson9a917e42009-06-12 22:56:54 +00001526}
1527
John McCallb3d87482010-08-24 05:47:05 +00001528QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) {
1529 QualType QT = Ty.get();
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001530 if (QT.isNull()) {
John McCalla93c9342009-12-07 02:54:59 +00001531 if (TInfo) *TInfo = 0;
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001532 return QualType();
1533 }
1534
John McCalla93c9342009-12-07 02:54:59 +00001535 TypeSourceInfo *DI = 0;
John McCallf4c73712011-01-19 06:33:43 +00001536 if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001537 QT = LIT->getType();
John McCalla93c9342009-12-07 02:54:59 +00001538 DI = LIT->getTypeSourceInfo();
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001539 }
Mike Stump1eb44332009-09-09 15:08:12 +00001540
John McCalla93c9342009-12-07 02:54:59 +00001541 if (TInfo) *TInfo = DI;
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001542 return QT;
1543}
1544
Argyrios Kyrtzidisa8349f52011-07-01 22:23:05 +00001545static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
1546 Qualifiers::ObjCLifetime ownership,
1547 unsigned chunkIndex);
1548
John McCallf85e1932011-06-15 23:02:42 +00001549/// Given that this is the declaration of a parameter under ARC,
1550/// attempt to infer attributes and such for pointer-to-whatever
1551/// types.
1552static void inferARCWriteback(TypeProcessingState &state,
1553 QualType &declSpecType) {
1554 Sema &S = state.getSema();
1555 Declarator &declarator = state.getDeclarator();
1556
1557 // TODO: should we care about decl qualifiers?
1558
1559 // Check whether the declarator has the expected form. We walk
1560 // from the inside out in order to make the block logic work.
1561 unsigned outermostPointerIndex = 0;
1562 bool isBlockPointer = false;
1563 unsigned numPointers = 0;
1564 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
1565 unsigned chunkIndex = i;
1566 DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex);
1567 switch (chunk.Kind) {
1568 case DeclaratorChunk::Paren:
1569 // Ignore parens.
1570 break;
1571
1572 case DeclaratorChunk::Reference:
1573 case DeclaratorChunk::Pointer:
1574 // Count the number of pointers. Treat references
1575 // interchangeably as pointers; if they're mis-ordered, normal
1576 // type building will discover that.
1577 outermostPointerIndex = chunkIndex;
1578 numPointers++;
1579 break;
1580
1581 case DeclaratorChunk::BlockPointer:
1582 // If we have a pointer to block pointer, that's an acceptable
1583 // indirect reference; anything else is not an application of
1584 // the rules.
1585 if (numPointers != 1) return;
1586 numPointers++;
1587 outermostPointerIndex = chunkIndex;
1588 isBlockPointer = true;
1589
1590 // We don't care about pointer structure in return values here.
1591 goto done;
1592
1593 case DeclaratorChunk::Array: // suppress if written (id[])?
1594 case DeclaratorChunk::Function:
1595 case DeclaratorChunk::MemberPointer:
1596 return;
1597 }
1598 }
1599 done:
1600
1601 // If we have *one* pointer, then we want to throw the qualifier on
1602 // the declaration-specifiers, which means that it needs to be a
1603 // retainable object type.
1604 if (numPointers == 1) {
1605 // If it's not a retainable object type, the rule doesn't apply.
1606 if (!declSpecType->isObjCRetainableType()) return;
1607
1608 // If it already has lifetime, don't do anything.
1609 if (declSpecType.getObjCLifetime()) return;
1610
1611 // Otherwise, modify the type in-place.
1612 Qualifiers qs;
1613
1614 if (declSpecType->isObjCARCImplicitlyUnretainedType())
1615 qs.addObjCLifetime(Qualifiers::OCL_ExplicitNone);
1616 else
1617 qs.addObjCLifetime(Qualifiers::OCL_Autoreleasing);
1618 declSpecType = S.Context.getQualifiedType(declSpecType, qs);
1619
1620 // If we have *two* pointers, then we want to throw the qualifier on
1621 // the outermost pointer.
1622 } else if (numPointers == 2) {
1623 // If we don't have a block pointer, we need to check whether the
1624 // declaration-specifiers gave us something that will turn into a
1625 // retainable object pointer after we slap the first pointer on it.
1626 if (!isBlockPointer && !declSpecType->isObjCObjectType())
1627 return;
1628
1629 // Look for an explicit lifetime attribute there.
1630 DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex);
Argyrios Kyrtzidis1c73dcb2011-07-01 22:23:03 +00001631 if (chunk.Kind != DeclaratorChunk::Pointer &&
1632 chunk.Kind != DeclaratorChunk::BlockPointer)
1633 return;
John McCallf85e1932011-06-15 23:02:42 +00001634 for (const AttributeList *attr = chunk.getAttrs(); attr;
1635 attr = attr->getNext())
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00001636 if (attr->getKind() == AttributeList::AT_objc_ownership)
John McCallf85e1932011-06-15 23:02:42 +00001637 return;
1638
Argyrios Kyrtzidisa8349f52011-07-01 22:23:05 +00001639 transferARCOwnershipToDeclaratorChunk(state, Qualifiers::OCL_Autoreleasing,
1640 outermostPointerIndex);
John McCallf85e1932011-06-15 23:02:42 +00001641
1642 // Any other number of pointers/references does not trigger the rule.
1643 } else return;
1644
1645 // TODO: mark whether we did this inference?
1646}
1647
Chandler Carruthd067c072011-02-23 18:51:59 +00001648static void DiagnoseIgnoredQualifiers(unsigned Quals,
1649 SourceLocation ConstQualLoc,
1650 SourceLocation VolatileQualLoc,
1651 SourceLocation RestrictQualLoc,
1652 Sema& S) {
1653 std::string QualStr;
1654 unsigned NumQuals = 0;
1655 SourceLocation Loc;
1656
1657 FixItHint ConstFixIt;
1658 FixItHint VolatileFixIt;
1659 FixItHint RestrictFixIt;
1660
Hans Wennborga08fcb82011-06-03 17:37:26 +00001661 const SourceManager &SM = S.getSourceManager();
1662
Chandler Carruthd067c072011-02-23 18:51:59 +00001663 // FIXME: The locations here are set kind of arbitrarily. It'd be nicer to
1664 // find a range and grow it to encompass all the qualifiers, regardless of
1665 // the order in which they textually appear.
1666 if (Quals & Qualifiers::Const) {
1667 ConstFixIt = FixItHint::CreateRemoval(ConstQualLoc);
Chandler Carruthd067c072011-02-23 18:51:59 +00001668 QualStr = "const";
Hans Wennborga08fcb82011-06-03 17:37:26 +00001669 ++NumQuals;
1670 if (!Loc.isValid() || SM.isBeforeInTranslationUnit(ConstQualLoc, Loc))
1671 Loc = ConstQualLoc;
Chandler Carruthd067c072011-02-23 18:51:59 +00001672 }
1673 if (Quals & Qualifiers::Volatile) {
1674 VolatileFixIt = FixItHint::CreateRemoval(VolatileQualLoc);
Hans Wennborga08fcb82011-06-03 17:37:26 +00001675 QualStr += (NumQuals == 0 ? "volatile" : " volatile");
Chandler Carruthd067c072011-02-23 18:51:59 +00001676 ++NumQuals;
Hans Wennborga08fcb82011-06-03 17:37:26 +00001677 if (!Loc.isValid() || SM.isBeforeInTranslationUnit(VolatileQualLoc, Loc))
1678 Loc = VolatileQualLoc;
Chandler Carruthd067c072011-02-23 18:51:59 +00001679 }
1680 if (Quals & Qualifiers::Restrict) {
1681 RestrictFixIt = FixItHint::CreateRemoval(RestrictQualLoc);
Hans Wennborga08fcb82011-06-03 17:37:26 +00001682 QualStr += (NumQuals == 0 ? "restrict" : " restrict");
Chandler Carruthd067c072011-02-23 18:51:59 +00001683 ++NumQuals;
Hans Wennborga08fcb82011-06-03 17:37:26 +00001684 if (!Loc.isValid() || SM.isBeforeInTranslationUnit(RestrictQualLoc, Loc))
1685 Loc = RestrictQualLoc;
Chandler Carruthd067c072011-02-23 18:51:59 +00001686 }
1687
1688 assert(NumQuals > 0 && "No known qualifiers?");
1689
1690 S.Diag(Loc, diag::warn_qual_return_type)
Hans Wennborga08fcb82011-06-03 17:37:26 +00001691 << QualStr << NumQuals << ConstFixIt << VolatileFixIt << RestrictFixIt;
Chandler Carruthd067c072011-02-23 18:51:59 +00001692}
1693
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001694static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state,
1695 TypeSourceInfo *&ReturnTypeInfo) {
1696 Sema &SemaRef = state.getSema();
1697 Declarator &D = state.getDeclarator();
Douglas Gregor930d8b52009-01-30 22:09:00 +00001698 QualType T;
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001699 ReturnTypeInfo = 0;
1700
1701 // The TagDecl owned by the DeclSpec.
Argyrios Kyrtzidisd3880f82011-06-28 03:01:18 +00001702 TagDecl *OwnedTagDecl = 0;
John McCall711c52b2011-01-05 12:14:39 +00001703
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001704 switch (D.getName().getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001705 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001706 case UnqualifiedId::IK_OperatorFunctionId:
Sebastian Redl8999fe12011-03-14 18:08:30 +00001707 case UnqualifiedId::IK_Identifier:
Sean Hunt0486d742009-11-28 04:44:28 +00001708 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001709 case UnqualifiedId::IK_TemplateId:
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001710 T = ConvertDeclSpecToType(state);
Chris Lattner5db2bb12009-10-25 18:21:37 +00001711
Douglas Gregor591bd3c2010-02-08 22:07:33 +00001712 if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) {
Argyrios Kyrtzidisd3880f82011-06-28 03:01:18 +00001713 OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
Abramo Bagnara15987972011-03-08 22:33:38 +00001714 // Owned declaration is embedded in declarator.
Argyrios Kyrtzidisd3880f82011-06-28 03:01:18 +00001715 OwnedTagDecl->setEmbeddedInDeclarator(true);
Douglas Gregor591bd3c2010-02-08 22:07:33 +00001716 }
Douglas Gregor930d8b52009-01-30 22:09:00 +00001717 break;
1718
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001719 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00001720 case UnqualifiedId::IK_ConstructorTemplateId:
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001721 case UnqualifiedId::IK_DestructorName:
Douglas Gregor930d8b52009-01-30 22:09:00 +00001722 // Constructors and destructors don't have return types. Use
Douglas Gregor48026d22010-01-11 18:40:55 +00001723 // "void" instead.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001724 T = SemaRef.Context.VoidTy;
Douglas Gregor930d8b52009-01-30 22:09:00 +00001725 break;
Douglas Gregor48026d22010-01-11 18:40:55 +00001726
1727 case UnqualifiedId::IK_ConversionFunctionId:
1728 // The result type of a conversion function is the type that it
1729 // converts to.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001730 T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId,
1731 &ReturnTypeInfo);
Douglas Gregor48026d22010-01-11 18:40:55 +00001732 break;
Douglas Gregor930d8b52009-01-30 22:09:00 +00001733 }
Douglas Gregordab60ad2010-10-01 18:44:50 +00001734
John McCall711c52b2011-01-05 12:14:39 +00001735 if (D.getAttributes())
1736 distributeTypeAttrsFromDeclarator(state, T);
1737
Richard Smithe7397c62011-02-22 00:36:53 +00001738 // C++0x [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context.
Richard Smith8110f042011-02-22 01:22:29 +00001739 // In C++0x, a function declarator using 'auto' must have a trailing return
1740 // type (this is checked later) and we can skip this. In other languages
1741 // using auto, we need to check regardless.
Richard Smith34b41d92011-02-20 03:19:35 +00001742 if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto &&
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001743 (!SemaRef.getLangOptions().CPlusPlus0x || !D.isFunctionDeclarator())) {
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001744 int Error = -1;
Mike Stump1eb44332009-09-09 15:08:12 +00001745
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001746 switch (D.getContext()) {
1747 case Declarator::KNRTypeListContext:
1748 assert(0 && "K&R type lists aren't allowed in C++");
1749 break;
John McCallc05a94b2011-03-23 23:43:04 +00001750 case Declarator::ObjCPrototypeContext:
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001751 case Declarator::PrototypeContext:
1752 Error = 0; // Function prototype
1753 break;
1754 case Declarator::MemberContext:
Richard Smith7a614d82011-06-11 17:19:42 +00001755 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)
1756 break;
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001757 switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001758 case TTK_Enum: assert(0 && "unhandled tag kind"); break;
1759 case TTK_Struct: Error = 1; /* Struct member */ break;
1760 case TTK_Union: Error = 2; /* Union member */ break;
1761 case TTK_Class: Error = 3; /* Class member */ break;
Mike Stump1eb44332009-09-09 15:08:12 +00001762 }
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001763 break;
1764 case Declarator::CXXCatchContext:
Argyrios Kyrtzidis17b63992011-07-01 22:22:40 +00001765 case Declarator::ObjCCatchContext:
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001766 Error = 4; // Exception declaration
1767 break;
1768 case Declarator::TemplateParamContext:
1769 Error = 5; // Template parameter
1770 break;
1771 case Declarator::BlockLiteralContext:
Richard Smith34b41d92011-02-20 03:19:35 +00001772 Error = 6; // Block literal
1773 break;
1774 case Declarator::TemplateTypeArgContext:
1775 Error = 7; // Template type argument
1776 break;
Richard Smith162e1c12011-04-15 14:24:37 +00001777 case Declarator::AliasDeclContext:
Richard Smith3e4c6c42011-05-05 21:57:07 +00001778 case Declarator::AliasTemplateContext:
Richard Smith162e1c12011-04-15 14:24:37 +00001779 Error = 9; // Type alias
1780 break;
Richard Smith34b41d92011-02-20 03:19:35 +00001781 case Declarator::TypeNameContext:
Argyrios Kyrtzidis0b8c98f2011-06-28 03:01:23 +00001782 Error = 11; // Generic
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001783 break;
1784 case Declarator::FileContext:
1785 case Declarator::BlockContext:
1786 case Declarator::ForContext:
1787 case Declarator::ConditionContext:
Argyrios Kyrtzidis0b8c98f2011-06-28 03:01:23 +00001788 case Declarator::CXXNewContext:
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001789 break;
1790 }
1791
Richard Smithddc83f92011-02-21 23:18:00 +00001792 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
1793 Error = 8;
1794
Richard Smith8110f042011-02-22 01:22:29 +00001795 // In Objective-C it is an error to use 'auto' on a function declarator.
1796 if (D.isFunctionDeclarator())
Richard Smith162e1c12011-04-15 14:24:37 +00001797 Error = 10;
Richard Smith8110f042011-02-22 01:22:29 +00001798
Richard Smithe7397c62011-02-22 00:36:53 +00001799 // C++0x [dcl.spec.auto]p2: 'auto' is always fine if the declarator
1800 // contains a trailing return type. That is only legal at the outermost
1801 // level. Check all declarator chunks (outermost first) anyway, to give
1802 // better diagnostics.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001803 if (SemaRef.getLangOptions().CPlusPlus0x && Error != -1) {
Richard Smithe7397c62011-02-22 00:36:53 +00001804 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
1805 unsigned chunkIndex = e - i - 1;
1806 state.setCurrentChunkIndex(chunkIndex);
1807 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
1808 if (DeclType.Kind == DeclaratorChunk::Function) {
1809 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
1810 if (FTI.TrailingReturnType) {
1811 Error = -1;
1812 break;
1813 }
1814 }
1815 }
1816 }
1817
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001818 if (Error != -1) {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001819 SemaRef.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
1820 diag::err_auto_not_allowed)
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001821 << Error;
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001822 T = SemaRef.Context.IntTy;
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001823 D.setInvalidType(true);
1824 }
1825 }
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001826
1827 if (SemaRef.getLangOptions().CPlusPlus &&
1828 OwnedTagDecl && OwnedTagDecl->isDefinition()) {
1829 // Check the contexts where C++ forbids the declaration of a new class
1830 // or enumeration in a type-specifier-seq.
1831 switch (D.getContext()) {
1832 case Declarator::FileContext:
1833 case Declarator::MemberContext:
1834 case Declarator::BlockContext:
1835 case Declarator::ForContext:
1836 case Declarator::BlockLiteralContext:
1837 // C++0x [dcl.type]p3:
1838 // A type-specifier-seq shall not define a class or enumeration unless
1839 // it appears in the type-id of an alias-declaration (7.1.3) that is not
1840 // the declaration of a template-declaration.
1841 case Declarator::AliasDeclContext:
1842 break;
1843 case Declarator::AliasTemplateContext:
1844 SemaRef.Diag(OwnedTagDecl->getLocation(),
1845 diag::err_type_defined_in_alias_template)
1846 << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
1847 break;
1848 case Declarator::TypeNameContext:
1849 case Declarator::TemplateParamContext:
1850 case Declarator::CXXNewContext:
1851 case Declarator::CXXCatchContext:
1852 case Declarator::ObjCCatchContext:
1853 case Declarator::TemplateTypeArgContext:
1854 SemaRef.Diag(OwnedTagDecl->getLocation(),
1855 diag::err_type_defined_in_type_specifier)
1856 << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
1857 break;
1858 case Declarator::PrototypeContext:
1859 case Declarator::ObjCPrototypeContext:
1860 case Declarator::KNRTypeListContext:
1861 // C++ [dcl.fct]p6:
1862 // Types shall not be defined in return or parameter types.
1863 SemaRef.Diag(OwnedTagDecl->getLocation(),
1864 diag::err_type_defined_in_param_type)
1865 << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
1866 break;
1867 case Declarator::ConditionContext:
1868 // C++ 6.4p2:
1869 // The type-specifier-seq shall not contain typedef and shall not declare
1870 // a new class or enumeration.
1871 SemaRef.Diag(OwnedTagDecl->getLocation(),
1872 diag::err_type_defined_in_condition);
1873 break;
1874 }
1875 }
1876
1877 return T;
1878}
1879
1880static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
1881 QualType declSpecType,
1882 TypeSourceInfo *TInfo) {
1883
1884 QualType T = declSpecType;
1885 Declarator &D = state.getDeclarator();
1886 Sema &S = state.getSema();
1887 ASTContext &Context = S.Context;
1888 const LangOptions &LangOpts = S.getLangOptions();
1889
1890 bool ImplicitlyNoexcept = false;
1891 if (D.getName().getKind() == UnqualifiedId::IK_OperatorFunctionId &&
1892 LangOpts.CPlusPlus0x) {
1893 OverloadedOperatorKind OO = D.getName().OperatorFunctionId.Operator;
1894 /// In C++0x, deallocation functions (normal and array operator delete)
1895 /// are implicitly noexcept.
1896 if (OO == OO_Delete || OO == OO_Array_Delete)
1897 ImplicitlyNoexcept = true;
1898 }
Richard Smith34b41d92011-02-20 03:19:35 +00001899
Douglas Gregorcd281c32009-02-28 00:25:32 +00001900 // The name we're declaring, if any.
1901 DeclarationName Name;
1902 if (D.getIdentifier())
1903 Name = D.getIdentifier();
Mike Stump1eb44332009-09-09 15:08:12 +00001904
Richard Smith162e1c12011-04-15 14:24:37 +00001905 // Does this declaration declare a typedef-name?
1906 bool IsTypedefName =
1907 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef ||
Richard Smith3e4c6c42011-05-05 21:57:07 +00001908 D.getContext() == Declarator::AliasDeclContext ||
1909 D.getContext() == Declarator::AliasTemplateContext;
Richard Smith162e1c12011-04-15 14:24:37 +00001910
Mike Stump98eb8a72009-02-04 22:31:32 +00001911 // Walk the DeclTypeInfo, building the recursive type as we go.
1912 // DeclTypeInfos are ordered from the identifier out, which is
1913 // opposite of what we want :).
Sebastian Redl8ce35b02009-10-25 21:45:37 +00001914 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
John McCall711c52b2011-01-05 12:14:39 +00001915 unsigned chunkIndex = e - i - 1;
1916 state.setCurrentChunkIndex(chunkIndex);
1917 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001918 switch (DeclType.Kind) {
1919 default: assert(0 && "Unknown decltype!");
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001920 case DeclaratorChunk::Paren:
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001921 T = S.BuildParenType(T);
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001922 break;
Steve Naroff5618bd42008-08-27 16:04:49 +00001923 case DeclaratorChunk::BlockPointer:
Chris Lattner9af55002009-03-27 04:18:06 +00001924 // If blocks are disabled, emit an error.
1925 if (!LangOpts.Blocks)
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001926 S.Diag(DeclType.Loc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +00001927
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001928 T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name);
John McCall28654742010-06-05 06:41:15 +00001929 if (DeclType.Cls.TypeQuals)
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001930 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals);
Steve Naroff5618bd42008-08-27 16:04:49 +00001931 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001932 case DeclaratorChunk::Pointer:
Sebastian Redl6a7330c2009-05-29 15:01:05 +00001933 // Verify that we're not building a pointer to pointer to function with
1934 // exception specification.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001935 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
1936 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
Sebastian Redl6a7330c2009-05-29 15:01:05 +00001937 D.setInvalidType(true);
1938 // Build the type anyway.
1939 }
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001940 if (LangOpts.ObjC1 && T->getAs<ObjCObjectType>()) {
John McCallc12c5bb2010-05-15 11:32:37 +00001941 T = Context.getObjCObjectPointerType(T);
John McCall28654742010-06-05 06:41:15 +00001942 if (DeclType.Ptr.TypeQuals)
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001943 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
Steve Naroff14108da2009-07-10 23:34:53 +00001944 break;
1945 }
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001946 T = S.BuildPointerType(T, DeclType.Loc, Name);
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);
John McCall711c52b2011-01-05 12:14:39 +00001949
Reid Spencer5f016e22007-07-11 17:01:13 +00001950 break;
John McCall0953e762009-09-24 19:53:00 +00001951 case DeclaratorChunk::Reference: {
Sebastian Redl6a7330c2009-05-29 15:01:05 +00001952 // Verify that we're not building a reference to pointer to function with
1953 // exception specification.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001954 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
1955 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
Sebastian Redl6a7330c2009-05-29 15:01:05 +00001956 D.setInvalidType(true);
1957 // Build the type anyway.
1958 }
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001959 T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name);
John McCall28654742010-06-05 06:41:15 +00001960
1961 Qualifiers Quals;
1962 if (DeclType.Ref.HasRestrict)
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001963 T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict);
Reid Spencer5f016e22007-07-11 17:01:13 +00001964 break;
John McCall0953e762009-09-24 19:53:00 +00001965 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001966 case DeclaratorChunk::Array: {
Sebastian Redl6a7330c2009-05-29 15:01:05 +00001967 // Verify that we're not building an array of pointers to function with
1968 // exception specification.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001969 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
1970 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
Sebastian Redl6a7330c2009-05-29 15:01:05 +00001971 D.setInvalidType(true);
1972 // Build the type anyway.
1973 }
Chris Lattnerfd89bc82008-04-02 01:05:10 +00001974 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
Chris Lattner94f81fd2007-08-28 16:54:00 +00001975 Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
Reid Spencer5f016e22007-07-11 17:01:13 +00001976 ArrayType::ArraySizeModifier ASM;
1977 if (ATI.isStar)
1978 ASM = ArrayType::Star;
1979 else if (ATI.hasStatic)
1980 ASM = ArrayType::Static;
1981 else
1982 ASM = ArrayType::Normal;
John McCallc05a94b2011-03-23 23:43:04 +00001983 if (ASM == ArrayType::Star && !D.isPrototypeContext()) {
Eli Friedmanf91f5c82009-04-26 21:57:51 +00001984 // FIXME: This check isn't quite right: it allows star in prototypes
1985 // for function definitions, and disallows some edge cases detailed
1986 // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001987 S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
Eli Friedmanf91f5c82009-04-26 21:57:51 +00001988 ASM = ArrayType::Normal;
1989 D.setInvalidType(true);
1990 }
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001991 T = S.BuildArrayType(T, ASM, ArraySize,
1992 Qualifiers::fromCVRMask(ATI.TypeQuals),
1993 SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
Reid Spencer5f016e22007-07-11 17:01:13 +00001994 break;
1995 }
Sebastian Redlf30208a2009-01-24 21:16:55 +00001996 case DeclaratorChunk::Function: {
Reid Spencer5f016e22007-07-11 17:01:13 +00001997 // If the function declarator has a prototype (i.e. it is not () and
1998 // does not have a K&R-style identifier list), then the arguments are part
1999 // of the type, otherwise the argument list is ().
2000 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
Sebastian Redl3cc97262009-05-31 11:47:27 +00002001
Richard Smithe7397c62011-02-22 00:36:53 +00002002 // Check for auto functions and trailing return type and adjust the
2003 // return type accordingly.
2004 if (!D.isInvalidType()) {
2005 // trailing-return-type is only required if we're declaring a function,
2006 // and not, for instance, a pointer to a function.
2007 if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto &&
2008 !FTI.TrailingReturnType && chunkIndex == 0) {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002009 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
Richard Smithe7397c62011-02-22 00:36:53 +00002010 diag::err_auto_missing_trailing_return);
2011 T = Context.IntTy;
2012 D.setInvalidType(true);
2013 } else if (FTI.TrailingReturnType) {
2014 // T must be exactly 'auto' at this point. See CWG issue 681.
2015 if (isa<ParenType>(T)) {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002016 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
Richard Smithe7397c62011-02-22 00:36:53 +00002017 diag::err_trailing_return_in_parens)
2018 << T << D.getDeclSpec().getSourceRange();
2019 D.setInvalidType(true);
2020 } else if (T.hasQualifiers() || !isa<AutoType>(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_without_auto)
2023 << T << D.getDeclSpec().getSourceRange();
2024 D.setInvalidType(true);
2025 }
2026
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002027 T = S.GetTypeFromParser(
Richard Smithe7397c62011-02-22 00:36:53 +00002028 ParsedType::getFromOpaquePtr(FTI.TrailingReturnType),
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002029 &TInfo);
Richard Smithe7397c62011-02-22 00:36:53 +00002030 }
2031 }
2032
Chris Lattnercd881292007-12-19 05:31:29 +00002033 // C99 6.7.5.3p1: The return type may not be a function or array type.
Douglas Gregor58408bc2010-01-11 18:46:21 +00002034 // For conversion functions, we'll diagnose this particular error later.
Douglas Gregor48026d22010-01-11 18:40:55 +00002035 if ((T->isArrayType() || T->isFunctionType()) &&
2036 (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId)) {
Argyrios Kyrtzidis98650442011-01-25 23:16:33 +00002037 unsigned diagID = diag::err_func_returning_array_function;
Argyrios Kyrtzidisa4356ad2011-01-26 01:26:44 +00002038 // Last processing chunk in block context means this function chunk
2039 // represents the block.
2040 if (chunkIndex == 0 &&
2041 D.getContext() == Declarator::BlockLiteralContext)
Argyrios Kyrtzidis98650442011-01-25 23:16:33 +00002042 diagID = diag::err_block_returning_array_function;
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002043 S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T;
Chris Lattnercd881292007-12-19 05:31:29 +00002044 T = Context.IntTy;
2045 D.setInvalidType(true);
2046 }
Sebastian Redl465226e2009-05-27 22:11:52 +00002047
Douglas Gregor5291c3c2010-07-13 08:18:22 +00002048 // cv-qualifiers on return types are pointless except when the type is a
2049 // class type in C++.
Douglas Gregorfff95132011-03-01 17:04:42 +00002050 if (isa<PointerType>(T) && T.getLocalCVRQualifiers() &&
Rafael Espindola1e153942011-03-11 04:56:58 +00002051 (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId) &&
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002052 (!LangOpts.CPlusPlus || !T->isDependentType())) {
Chandler Carruthd067c072011-02-23 18:51:59 +00002053 assert(chunkIndex + 1 < e && "No DeclaratorChunk for the return type?");
2054 DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1);
2055 assert(ReturnTypeChunk.Kind == DeclaratorChunk::Pointer);
2056
2057 DeclaratorChunk::PointerTypeInfo &PTI = ReturnTypeChunk.Ptr;
2058
2059 DiagnoseIgnoredQualifiers(PTI.TypeQuals,
2060 SourceLocation::getFromRawEncoding(PTI.ConstQualLoc),
2061 SourceLocation::getFromRawEncoding(PTI.VolatileQualLoc),
2062 SourceLocation::getFromRawEncoding(PTI.RestrictQualLoc),
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002063 S);
Chandler Carruthd067c072011-02-23 18:51:59 +00002064
2065 } else if (T.getCVRQualifiers() && D.getDeclSpec().getTypeQualifiers() &&
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002066 (!LangOpts.CPlusPlus ||
Douglas Gregor5291c3c2010-07-13 08:18:22 +00002067 (!T->isDependentType() && !T->isRecordType()))) {
Chandler Carruthd067c072011-02-23 18:51:59 +00002068
2069 DiagnoseIgnoredQualifiers(D.getDeclSpec().getTypeQualifiers(),
2070 D.getDeclSpec().getConstSpecLoc(),
2071 D.getDeclSpec().getVolatileSpecLoc(),
2072 D.getDeclSpec().getRestrictSpecLoc(),
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002073 S);
Douglas Gregor5291c3c2010-07-13 08:18:22 +00002074 }
Chandler Carruthd067c072011-02-23 18:51:59 +00002075
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002076 if (LangOpts.CPlusPlus && D.getDeclSpec().isTypeSpecOwned()) {
Douglas Gregor402abb52009-05-28 23:31:59 +00002077 // C++ [dcl.fct]p6:
2078 // Types shall not be defined in return or parameter types.
John McCallb3d87482010-08-24 05:47:05 +00002079 TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
Douglas Gregor402abb52009-05-28 23:31:59 +00002080 if (Tag->isDefinition())
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002081 S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
Douglas Gregor402abb52009-05-28 23:31:59 +00002082 << Context.getTypeDeclType(Tag);
2083 }
2084
Sebastian Redl3cc97262009-05-31 11:47:27 +00002085 // Exception specs are not allowed in typedefs. Complain, but add it
2086 // anyway.
Richard Smith162e1c12011-04-15 14:24:37 +00002087 if (IsTypedefName && FTI.getExceptionSpecType())
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002088 S.Diag(FTI.getExceptionSpecLoc(), diag::err_exception_spec_in_typedef)
Richard Smith3e4c6c42011-05-05 21:57:07 +00002089 << (D.getContext() == Declarator::AliasDeclContext ||
2090 D.getContext() == Declarator::AliasTemplateContext);
Sebastian Redl3cc97262009-05-31 11:47:27 +00002091
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002092 if (!FTI.NumArgs && !FTI.isVariadic && !LangOpts.CPlusPlus) {
John McCall28654742010-06-05 06:41:15 +00002093 // Simple void foo(), where the incoming T is the result type.
2094 T = Context.getFunctionNoProtoType(T);
2095 } else {
2096 // We allow a zero-parameter variadic function in C if the
2097 // function is marked with the "overloadable" attribute. Scan
2098 // for this attribute now.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002099 if (!FTI.NumArgs && FTI.isVariadic && !LangOpts.CPlusPlus) {
Douglas Gregor965acbb2009-02-18 07:07:28 +00002100 bool Overloadable = false;
2101 for (const AttributeList *Attrs = D.getAttributes();
2102 Attrs; Attrs = Attrs->getNext()) {
2103 if (Attrs->getKind() == AttributeList::AT_overloadable) {
2104 Overloadable = true;
2105 break;
2106 }
2107 }
2108
2109 if (!Overloadable)
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002110 S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_arg);
Argyrios Kyrtzidisc6f73452008-10-16 17:31:08 +00002111 }
John McCall28654742010-06-05 06:41:15 +00002112
2113 if (FTI.NumArgs && FTI.ArgInfo[0].Param == 0) {
Chris Lattner788b0fd2010-06-23 06:00:24 +00002114 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function
2115 // definition.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002116 S.Diag(FTI.ArgInfo[0].IdentLoc, diag::err_ident_list_in_fn_declaration);
John McCall28654742010-06-05 06:41:15 +00002117 D.setInvalidType(true);
2118 break;
2119 }
2120
John McCalle23cf432010-12-14 08:05:40 +00002121 FunctionProtoType::ExtProtoInfo EPI;
2122 EPI.Variadic = FTI.isVariadic;
2123 EPI.TypeQuals = FTI.TypeQuals;
Douglas Gregorc938c162011-01-26 05:01:58 +00002124 EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None
2125 : FTI.RefQualifierIsLValueRef? RQ_LValue
2126 : RQ_RValue;
2127
Reid Spencer5f016e22007-07-11 17:01:13 +00002128 // Otherwise, we have a function with an argument list that is
2129 // potentially variadic.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002130 SmallVector<QualType, 16> ArgTys;
John McCall28654742010-06-05 06:41:15 +00002131 ArgTys.reserve(FTI.NumArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002132
Chris Lattner5f9e2722011-07-23 10:55:15 +00002133 SmallVector<bool, 16> ConsumedArguments;
John McCallf85e1932011-06-15 23:02:42 +00002134 ConsumedArguments.reserve(FTI.NumArgs);
2135 bool HasAnyConsumedArguments = false;
2136
Reid Spencer5f016e22007-07-11 17:01:13 +00002137 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
John McCalld226f652010-08-21 09:40:31 +00002138 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
Chris Lattner8123a952008-04-10 02:22:51 +00002139 QualType ArgTy = Param->getType();
Chris Lattner78c75fb2007-07-21 05:30:18 +00002140 assert(!ArgTy.isNull() && "Couldn't parse type?");
Douglas Gregor2dc0e642009-03-23 23:06:20 +00002141
2142 // Adjust the parameter type.
Douglas Gregor79e6bd32011-07-12 04:42:08 +00002143 assert((ArgTy == Context.getAdjustedParameterType(ArgTy)) &&
2144 "Unadjusted type?");
Douglas Gregor2dc0e642009-03-23 23:06:20 +00002145
Reid Spencer5f016e22007-07-11 17:01:13 +00002146 // Look for 'void'. void is allowed only as a single argument to a
2147 // function with no other parameters (C99 6.7.5.3p10). We record
Douglas Gregor72564e72009-02-26 23:50:07 +00002148 // int(void) as a FunctionProtoType with an empty argument list.
Douglas Gregor2dc0e642009-03-23 23:06:20 +00002149 if (ArgTy->isVoidType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002150 // If this is something like 'float(int, void)', reject it. 'void'
2151 // is an incomplete type (C99 6.2.5p19) and function decls cannot
2152 // have arguments of incomplete type.
2153 if (FTI.NumArgs != 1 || FTI.isVariadic) {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002154 S.Diag(DeclType.Loc, diag::err_void_only_param);
Chris Lattner2ff54262007-07-21 05:18:12 +00002155 ArgTy = Context.IntTy;
Chris Lattner8123a952008-04-10 02:22:51 +00002156 Param->setType(ArgTy);
Chris Lattner2ff54262007-07-21 05:18:12 +00002157 } else if (FTI.ArgInfo[i].Ident) {
2158 // Reject, but continue to parse 'int(void abc)'.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002159 S.Diag(FTI.ArgInfo[i].IdentLoc,
Chris Lattner4565d4e2007-07-21 05:26:43 +00002160 diag::err_param_with_void_type);
Chris Lattner2ff54262007-07-21 05:18:12 +00002161 ArgTy = Context.IntTy;
Chris Lattner8123a952008-04-10 02:22:51 +00002162 Param->setType(ArgTy);
Chris Lattner2ff54262007-07-21 05:18:12 +00002163 } else {
2164 // Reject, but continue to parse 'float(const void)'.
John McCall0953e762009-09-24 19:53:00 +00002165 if (ArgTy.hasQualifiers())
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002166 S.Diag(DeclType.Loc, diag::err_void_param_qualified);
Mike Stump1eb44332009-09-09 15:08:12 +00002167
Chris Lattner2ff54262007-07-21 05:18:12 +00002168 // Do not add 'void' to the ArgTys list.
2169 break;
2170 }
Eli Friedmaneb4b7052008-08-25 21:31:01 +00002171 } else if (!FTI.hasPrototype) {
2172 if (ArgTy->isPromotableIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00002173 ArgTy = Context.getPromotedIntegerType(ArgTy);
John McCalleecf5fa2011-03-09 04:22:44 +00002174 Param->setKNRPromoted(true);
John McCall183700f2009-09-21 23:43:11 +00002175 } else if (const BuiltinType* BTy = ArgTy->getAs<BuiltinType>()) {
John McCalleecf5fa2011-03-09 04:22:44 +00002176 if (BTy->getKind() == BuiltinType::Float) {
Eli Friedmaneb4b7052008-08-25 21:31:01 +00002177 ArgTy = Context.DoubleTy;
John McCalleecf5fa2011-03-09 04:22:44 +00002178 Param->setKNRPromoted(true);
2179 }
Eli Friedmaneb4b7052008-08-25 21:31:01 +00002180 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002181 }
Fariborz Jahanian56a965c2010-09-08 21:36:35 +00002182
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002183 if (LangOpts.ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00002184 bool Consumed = Param->hasAttr<NSConsumedAttr>();
2185 ConsumedArguments.push_back(Consumed);
2186 HasAnyConsumedArguments |= Consumed;
2187 }
2188
John McCall54e14c42009-10-22 22:37:11 +00002189 ArgTys.push_back(ArgTy);
Reid Spencer5f016e22007-07-11 17:01:13 +00002190 }
Sebastian Redl465226e2009-05-27 22:11:52 +00002191
John McCallf85e1932011-06-15 23:02:42 +00002192 if (HasAnyConsumedArguments)
2193 EPI.ConsumedArguments = ConsumedArguments.data();
2194
Chris Lattner5f9e2722011-07-23 10:55:15 +00002195 SmallVector<QualType, 4> Exceptions;
Sebastian Redl8b5b4092011-03-06 10:52:04 +00002196 EPI.ExceptionSpecType = FTI.getExceptionSpecType();
2197 if (FTI.getExceptionSpecType() == EST_Dynamic) {
John McCalle23cf432010-12-14 08:05:40 +00002198 Exceptions.reserve(FTI.NumExceptions);
2199 for (unsigned ei = 0, ee = FTI.NumExceptions; ei != ee; ++ei) {
2200 // FIXME: Preserve type source info.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002201 QualType ET = S.GetTypeFromParser(FTI.Exceptions[ei].Ty);
John McCalle23cf432010-12-14 08:05:40 +00002202 // Check that the type is valid for an exception spec, and
2203 // drop it if not.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002204 if (!S.CheckSpecifiedExceptionType(ET, FTI.Exceptions[ei].Range))
John McCalle23cf432010-12-14 08:05:40 +00002205 Exceptions.push_back(ET);
2206 }
John McCall373920b2010-12-14 16:45:57 +00002207 EPI.NumExceptions = Exceptions.size();
John McCalle23cf432010-12-14 08:05:40 +00002208 EPI.Exceptions = Exceptions.data();
Sebastian Redl8b5b4092011-03-06 10:52:04 +00002209 } else if (FTI.getExceptionSpecType() == EST_ComputedNoexcept) {
Sebastian Redl60618fa2011-03-12 11:50:43 +00002210 // If an error occurred, there's no expression here.
2211 if (Expr *NoexceptExpr = FTI.NoexceptExpr) {
2212 assert((NoexceptExpr->isTypeDependent() ||
2213 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
2214 Context.BoolTy) &&
2215 "Parser should have made sure that the expression is boolean");
2216 SourceLocation ErrLoc;
2217 llvm::APSInt Dummy;
2218 if (!NoexceptExpr->isValueDependent() &&
2219 !NoexceptExpr->isIntegerConstantExpr(Dummy, Context, &ErrLoc,
2220 /*evaluated*/false))
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002221 S.Diag(ErrLoc, diag::err_noexcept_needs_constant_expression)
Sebastian Redl60618fa2011-03-12 11:50:43 +00002222 << NoexceptExpr->getSourceRange();
2223 else
2224 EPI.NoexceptExpr = NoexceptExpr;
2225 }
Sebastian Redl8999fe12011-03-14 18:08:30 +00002226 } else if (FTI.getExceptionSpecType() == EST_None &&
2227 ImplicitlyNoexcept && chunkIndex == 0) {
2228 // Only the outermost chunk is marked noexcept, of course.
2229 EPI.ExceptionSpecType = EST_BasicNoexcept;
Sebastian Redlef65f062009-05-29 18:02:33 +00002230 }
Sebastian Redl465226e2009-05-27 22:11:52 +00002231
John McCalle23cf432010-12-14 08:05:40 +00002232 T = Context.getFunctionType(T, ArgTys.data(), ArgTys.size(), EPI);
Reid Spencer5f016e22007-07-11 17:01:13 +00002233 }
John McCall04a67a62010-02-05 21:31:56 +00002234
Reid Spencer5f016e22007-07-11 17:01:13 +00002235 break;
2236 }
Sebastian Redlf30208a2009-01-24 21:16:55 +00002237 case DeclaratorChunk::MemberPointer:
2238 // The scope spec must refer to a class, or be dependent.
Abramo Bagnara7bd06762010-08-13 12:56:25 +00002239 CXXScopeSpec &SS = DeclType.Mem.Scope();
Sebastian Redlf30208a2009-01-24 21:16:55 +00002240 QualType ClsType;
Abramo Bagnara7bd06762010-08-13 12:56:25 +00002241 if (SS.isInvalid()) {
Jeffrey Yasskinedc28772010-04-07 23:29:58 +00002242 // Avoid emitting extra errors if we already errored on the scope.
2243 D.setInvalidType(true);
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002244 } else if (S.isDependentScopeSpecifier(SS) ||
2245 dyn_cast_or_null<CXXRecordDecl>(S.computeDeclContext(SS))) {
Mike Stump1eb44332009-09-09 15:08:12 +00002246 NestedNameSpecifier *NNS
Abramo Bagnara7bd06762010-08-13 12:56:25 +00002247 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
Douglas Gregor87c12c42009-11-04 16:49:01 +00002248 NestedNameSpecifier *NNSPrefix = NNS->getPrefix();
2249 switch (NNS->getKind()) {
2250 case NestedNameSpecifier::Identifier:
Abramo Bagnara7bd06762010-08-13 12:56:25 +00002251 ClsType = Context.getDependentNameType(ETK_None, NNSPrefix,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002252 NNS->getAsIdentifier());
Douglas Gregor87c12c42009-11-04 16:49:01 +00002253 break;
2254
2255 case NestedNameSpecifier::Namespace:
Douglas Gregor14aba762011-02-24 02:36:08 +00002256 case NestedNameSpecifier::NamespaceAlias:
Douglas Gregor87c12c42009-11-04 16:49:01 +00002257 case NestedNameSpecifier::Global:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002258 llvm_unreachable("Nested-name-specifier must name a type");
Douglas Gregor87c12c42009-11-04 16:49:01 +00002259 break;
Abramo Bagnara7bd06762010-08-13 12:56:25 +00002260
Douglas Gregor87c12c42009-11-04 16:49:01 +00002261 case NestedNameSpecifier::TypeSpec:
2262 case NestedNameSpecifier::TypeSpecWithTemplate:
2263 ClsType = QualType(NNS->getAsType(), 0);
Abramo Bagnara91ce2c42011-03-10 10:18:27 +00002264 // Note: if the NNS has a prefix and ClsType is a nondependent
2265 // TemplateSpecializationType, then the NNS prefix is NOT included
2266 // in ClsType; hence we wrap ClsType into an ElaboratedType.
2267 // NOTE: in particular, no wrap occurs if ClsType already is an
2268 // Elaborated, DependentName, or DependentTemplateSpecialization.
2269 if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType()))
Abramo Bagnara7bd06762010-08-13 12:56:25 +00002270 ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType);
Douglas Gregor87c12c42009-11-04 16:49:01 +00002271 break;
2272 }
Sebastian Redlf30208a2009-01-24 21:16:55 +00002273 } else {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002274 S.Diag(DeclType.Mem.Scope().getBeginLoc(),
Douglas Gregor949bf692009-06-09 22:17:39 +00002275 diag::err_illegal_decl_mempointer_in_nonclass)
2276 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
2277 << DeclType.Mem.Scope().getRange();
Sebastian Redlf30208a2009-01-24 21:16:55 +00002278 D.setInvalidType(true);
Sebastian Redlf30208a2009-01-24 21:16:55 +00002279 }
2280
Douglas Gregor949bf692009-06-09 22:17:39 +00002281 if (!ClsType.isNull())
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002282 T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc, D.getIdentifier());
Douglas Gregor949bf692009-06-09 22:17:39 +00002283 if (T.isNull()) {
2284 T = Context.IntTy;
Sebastian Redlf30208a2009-01-24 21:16:55 +00002285 D.setInvalidType(true);
John McCall28654742010-06-05 06:41:15 +00002286 } else if (DeclType.Mem.TypeQuals) {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002287 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals);
Sebastian Redlf30208a2009-01-24 21:16:55 +00002288 }
Sebastian Redlf30208a2009-01-24 21:16:55 +00002289 break;
2290 }
2291
Douglas Gregorcd281c32009-02-28 00:25:32 +00002292 if (T.isNull()) {
2293 D.setInvalidType(true);
2294 T = Context.IntTy;
2295 }
2296
Chris Lattnerc9b346d2008-06-29 00:50:08 +00002297 // See if there are any attributes on this declarator chunk.
John McCall711c52b2011-01-05 12:14:39 +00002298 if (AttributeList *attrs = const_cast<AttributeList*>(DeclType.getAttrs()))
2299 processTypeAttrs(state, T, false, attrs);
Reid Spencer5f016e22007-07-11 17:01:13 +00002300 }
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00002301
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002302 if (LangOpts.CPlusPlus && T->isFunctionType()) {
John McCall183700f2009-09-21 23:43:11 +00002303 const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
Chris Lattner778ed742009-10-25 17:36:50 +00002304 assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00002305
Douglas Gregor708f3b82010-10-14 22:03:51 +00002306 // C++ 8.3.5p4:
2307 // A cv-qualifier-seq shall only be part of the function type
2308 // for a nonstatic member function, the function type to which a pointer
2309 // to member refers, or the top-level function type of a function typedef
2310 // declaration.
Douglas Gregor683a81f2011-01-31 16:09:46 +00002311 //
2312 // Core issue 547 also allows cv-qualifiers on function types that are
2313 // top-level template type arguments.
John McCall613ef3d2010-10-19 01:54:45 +00002314 bool FreeFunction;
2315 if (!D.getCXXScopeSpec().isSet()) {
2316 FreeFunction = (D.getContext() != Declarator::MemberContext ||
2317 D.getDeclSpec().isFriendSpecified());
2318 } else {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002319 DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec());
John McCall613ef3d2010-10-19 01:54:45 +00002320 FreeFunction = (DC && !DC->isRecord());
2321 }
2322
Douglas Gregorc938c162011-01-26 05:01:58 +00002323 // C++0x [dcl.fct]p6:
2324 // A ref-qualifier shall only be part of the function type for a
2325 // non-static member function, the function type to which a pointer to
2326 // member refers, or the top-level function type of a function typedef
2327 // declaration.
2328 if ((FnTy->getTypeQuals() != 0 || FnTy->getRefQualifier()) &&
Douglas Gregor683a81f2011-01-31 16:09:46 +00002329 !(D.getContext() == Declarator::TemplateTypeArgContext &&
Richard Smith162e1c12011-04-15 14:24:37 +00002330 !D.isFunctionDeclarator()) && !IsTypedefName &&
Sebastian Redlc61bb202010-07-09 21:26:08 +00002331 (FreeFunction ||
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00002332 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)) {
Douglas Gregor683a81f2011-01-31 16:09:46 +00002333 if (D.getContext() == Declarator::TemplateTypeArgContext) {
2334 // Accept qualified function types as template type arguments as a GNU
2335 // extension. This is also the subject of C++ core issue 547.
2336 std::string Quals;
2337 if (FnTy->getTypeQuals() != 0)
2338 Quals = Qualifiers::fromCVRMask(FnTy->getTypeQuals()).getAsString();
2339
2340 switch (FnTy->getRefQualifier()) {
2341 case RQ_None:
2342 break;
2343
2344 case RQ_LValue:
2345 if (!Quals.empty())
2346 Quals += ' ';
2347 Quals += '&';
2348 break;
Douglas Gregorc938c162011-01-26 05:01:58 +00002349
Douglas Gregor683a81f2011-01-31 16:09:46 +00002350 case RQ_RValue:
2351 if (!Quals.empty())
2352 Quals += ' ';
2353 Quals += "&&";
2354 break;
Douglas Gregorc938c162011-01-26 05:01:58 +00002355 }
Douglas Gregor683a81f2011-01-31 16:09:46 +00002356
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002357 S.Diag(D.getIdentifierLoc(),
Douglas Gregor683a81f2011-01-31 16:09:46 +00002358 diag::ext_qualified_function_type_template_arg)
2359 << Quals;
2360 } else {
2361 if (FnTy->getTypeQuals() != 0) {
2362 if (D.isFunctionDeclarator())
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002363 S.Diag(D.getIdentifierLoc(),
Douglas Gregor683a81f2011-01-31 16:09:46 +00002364 diag::err_invalid_qualified_function_type);
2365 else
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002366 S.Diag(D.getIdentifierLoc(),
Douglas Gregor683a81f2011-01-31 16:09:46 +00002367 diag::err_invalid_qualified_typedef_function_type_use)
2368 << FreeFunction;
2369 }
2370
2371 if (FnTy->getRefQualifier()) {
2372 if (D.isFunctionDeclarator()) {
2373 SourceLocation Loc = D.getIdentifierLoc();
2374 for (unsigned I = 0, N = D.getNumTypeObjects(); I != N; ++I) {
2375 const DeclaratorChunk &Chunk = D.getTypeObject(N-I-1);
2376 if (Chunk.Kind == DeclaratorChunk::Function &&
2377 Chunk.Fun.hasRefQualifier()) {
2378 Loc = Chunk.Fun.getRefQualifierLoc();
2379 break;
2380 }
2381 }
2382
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002383 S.Diag(Loc, diag::err_invalid_ref_qualifier_function_type)
Douglas Gregor683a81f2011-01-31 16:09:46 +00002384 << (FnTy->getRefQualifier() == RQ_LValue)
2385 << FixItHint::CreateRemoval(Loc);
2386 } else {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002387 S.Diag(D.getIdentifierLoc(),
Douglas Gregor683a81f2011-01-31 16:09:46 +00002388 diag::err_invalid_ref_qualifier_typedef_function_type_use)
2389 << FreeFunction
2390 << (FnTy->getRefQualifier() == RQ_LValue);
2391 }
2392 }
2393
2394 // Strip the cv-qualifiers and ref-qualifiers from the type.
2395 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
2396 EPI.TypeQuals = 0;
2397 EPI.RefQualifier = RQ_None;
2398
2399 T = Context.getFunctionType(FnTy->getResultType(),
2400 FnTy->arg_type_begin(),
2401 FnTy->getNumArgs(), EPI);
Douglas Gregorc938c162011-01-26 05:01:58 +00002402 }
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00002403 }
2404 }
Mike Stump1eb44332009-09-09 15:08:12 +00002405
John McCall711c52b2011-01-05 12:14:39 +00002406 // Apply any undistributed attributes from the declarator.
2407 if (!T.isNull())
2408 if (AttributeList *attrs = D.getAttributes())
2409 processTypeAttrs(state, T, false, attrs);
2410
2411 // Diagnose any ignored type attributes.
2412 if (!T.isNull()) state.diagnoseIgnoredTypeAttrs(T);
2413
Peter Collingbourne148f1f72011-03-20 08:06:45 +00002414 // C++0x [dcl.constexpr]p9:
2415 // A constexpr specifier used in an object declaration declares the object
2416 // as const.
2417 if (D.getDeclSpec().isConstexprSpecified() && T->isObjectType()) {
Sebastian Redl73780122010-06-09 21:19:43 +00002418 T.addConst();
2419 }
2420
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002421 // If there was an ellipsis in the declarator, the declaration declares a
2422 // parameter pack whose type may be a pack expansion type.
2423 if (D.hasEllipsis() && !T.isNull()) {
2424 // C++0x [dcl.fct]p13:
2425 // A declarator-id or abstract-declarator containing an ellipsis shall
2426 // only be used in a parameter-declaration. Such a parameter-declaration
2427 // is a parameter pack (14.5.3). [...]
2428 switch (D.getContext()) {
2429 case Declarator::PrototypeContext:
2430 // C++0x [dcl.fct]p13:
2431 // [...] When it is part of a parameter-declaration-clause, the
2432 // parameter pack is a function parameter pack (14.5.3). The type T
2433 // of the declarator-id of the function parameter pack shall contain
2434 // a template parameter pack; each template parameter pack in T is
2435 // expanded by the function parameter pack.
2436 //
2437 // We represent function parameter packs as function parameters whose
2438 // type is a pack expansion.
2439 if (!T->containsUnexpandedParameterPack()) {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002440 S.Diag(D.getEllipsisLoc(),
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002441 diag::err_function_parameter_pack_without_parameter_packs)
2442 << T << D.getSourceRange();
2443 D.setEllipsisLoc(SourceLocation());
2444 } else {
Douglas Gregorcded4f62011-01-14 17:04:44 +00002445 T = Context.getPackExpansionType(T, llvm::Optional<unsigned>());
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002446 }
2447 break;
2448
2449 case Declarator::TemplateParamContext:
2450 // C++0x [temp.param]p15:
2451 // If a template-parameter is a [...] is a parameter-declaration that
2452 // declares a parameter pack (8.3.5), then the template-parameter is a
2453 // template parameter pack (14.5.3).
2454 //
2455 // Note: core issue 778 clarifies that, if there are any unexpanded
2456 // parameter packs in the type of the non-type template parameter, then
2457 // it expands those parameter packs.
2458 if (T->containsUnexpandedParameterPack())
Douglas Gregorcded4f62011-01-14 17:04:44 +00002459 T = Context.getPackExpansionType(T, llvm::Optional<unsigned>());
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002460 else if (!LangOpts.CPlusPlus0x)
2461 S.Diag(D.getEllipsisLoc(), diag::ext_variadic_templates);
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002462 break;
2463
2464 case Declarator::FileContext:
2465 case Declarator::KNRTypeListContext:
John McCallc05a94b2011-03-23 23:43:04 +00002466 case Declarator::ObjCPrototypeContext: // FIXME: special diagnostic here?
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002467 case Declarator::TypeNameContext:
Argyrios Kyrtzidis0b8c98f2011-06-28 03:01:23 +00002468 case Declarator::CXXNewContext:
Richard Smith162e1c12011-04-15 14:24:37 +00002469 case Declarator::AliasDeclContext:
Richard Smith3e4c6c42011-05-05 21:57:07 +00002470 case Declarator::AliasTemplateContext:
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002471 case Declarator::MemberContext:
2472 case Declarator::BlockContext:
2473 case Declarator::ForContext:
2474 case Declarator::ConditionContext:
2475 case Declarator::CXXCatchContext:
Argyrios Kyrtzidis17b63992011-07-01 22:22:40 +00002476 case Declarator::ObjCCatchContext:
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002477 case Declarator::BlockLiteralContext:
Douglas Gregor683a81f2011-01-31 16:09:46 +00002478 case Declarator::TemplateTypeArgContext:
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002479 // FIXME: We may want to allow parameter packs in block-literal contexts
2480 // in the future.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002481 S.Diag(D.getEllipsisLoc(), diag::err_ellipsis_in_declarator_not_parameter);
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002482 D.setEllipsisLoc(SourceLocation());
2483 break;
2484 }
2485 }
Richard Smithe7397c62011-02-22 00:36:53 +00002486
John McCallbf1a0282010-06-04 23:28:52 +00002487 if (T.isNull())
2488 return Context.getNullTypeSourceInfo();
2489 else if (D.isInvalidType())
2490 return Context.getTrivialTypeSourceInfo(T);
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +00002491
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002492 return S.GetTypeSourceInfoForDeclarator(D, T, TInfo);
2493}
2494
2495/// GetTypeForDeclarator - Convert the type for the specified
2496/// declarator to Type instances.
2497///
2498/// The result of this call will never be null, but the associated
2499/// type may be a null type if there's an unrecoverable error.
2500TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) {
2501 // Determine the type of the declarator. Not all forms of declarator
2502 // have a type.
2503
2504 TypeProcessingState state(*this, D);
2505
2506 TypeSourceInfo *ReturnTypeInfo = 0;
2507 QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
2508 if (T.isNull())
2509 return Context.getNullTypeSourceInfo();
2510
2511 if (D.isPrototypeContext() && getLangOptions().ObjCAutoRefCount)
2512 inferARCWriteback(state, T);
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +00002513
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002514 return GetFullTypeForDeclarator(state, T, ReturnTypeInfo);
Reid Spencer5f016e22007-07-11 17:01:13 +00002515}
2516
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00002517static void transferARCOwnershipToDeclSpec(Sema &S,
2518 QualType &declSpecTy,
2519 Qualifiers::ObjCLifetime ownership) {
2520 if (declSpecTy->isObjCRetainableType() &&
2521 declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) {
2522 Qualifiers qs;
2523 qs.addObjCLifetime(ownership);
2524 declSpecTy = S.Context.getQualifiedType(declSpecTy, qs);
2525 }
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00002526}
2527
2528static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
2529 Qualifiers::ObjCLifetime ownership,
2530 unsigned chunkIndex) {
2531 Sema &S = state.getSema();
2532 Declarator &D = state.getDeclarator();
2533
2534 // Look for an explicit lifetime attribute.
2535 DeclaratorChunk &chunk = D.getTypeObject(chunkIndex);
2536 for (const AttributeList *attr = chunk.getAttrs(); attr;
2537 attr = attr->getNext())
2538 if (attr->getKind() == AttributeList::AT_objc_ownership)
2539 return;
2540
2541 const char *attrStr = 0;
2542 switch (ownership) {
2543 case Qualifiers::OCL_None: llvm_unreachable("no ownership!"); break;
2544 case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break;
2545 case Qualifiers::OCL_Strong: attrStr = "strong"; break;
2546 case Qualifiers::OCL_Weak: attrStr = "weak"; break;
2547 case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break;
2548 }
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00002549
2550 // If there wasn't one, add one (with an invalid source location
2551 // so that we don't make an AttributedType for it).
2552 AttributeList *attr = D.getAttributePool()
2553 .create(&S.Context.Idents.get("objc_ownership"), SourceLocation(),
2554 /*scope*/ 0, SourceLocation(),
2555 &S.Context.Idents.get(attrStr), SourceLocation(),
2556 /*args*/ 0, 0,
2557 /*declspec*/ false, /*C++0x*/ false);
2558 spliceAttrIntoList(*attr, chunk.getAttrListRef());
2559
2560 // TODO: mark whether we did this inference?
2561}
2562
2563static void transferARCOwnership(TypeProcessingState &state,
2564 QualType &declSpecTy,
2565 Qualifiers::ObjCLifetime ownership) {
2566 Sema &S = state.getSema();
2567 Declarator &D = state.getDeclarator();
2568
2569 int inner = -1;
2570 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
2571 DeclaratorChunk &chunk = D.getTypeObject(i);
2572 switch (chunk.Kind) {
2573 case DeclaratorChunk::Paren:
2574 // Ignore parens.
2575 break;
2576
2577 case DeclaratorChunk::Array:
2578 case DeclaratorChunk::Reference:
2579 case DeclaratorChunk::Pointer:
2580 inner = i;
2581 break;
2582
2583 case DeclaratorChunk::BlockPointer:
2584 return transferARCOwnershipToDeclaratorChunk(state, ownership, i);
2585
2586 case DeclaratorChunk::Function:
2587 case DeclaratorChunk::MemberPointer:
2588 return;
2589 }
2590 }
2591
2592 if (inner == -1)
2593 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
2594
2595 DeclaratorChunk &chunk = D.getTypeObject(inner);
2596 if (chunk.Kind == DeclaratorChunk::Pointer) {
2597 if (declSpecTy->isObjCRetainableType())
2598 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
2599 if (declSpecTy->isObjCObjectType())
2600 return transferARCOwnershipToDeclaratorChunk(state, ownership, inner);
2601 } else {
2602 assert(chunk.Kind == DeclaratorChunk::Array ||
2603 chunk.Kind == DeclaratorChunk::Reference);
2604 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
2605 }
2606}
2607
2608TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) {
2609 TypeProcessingState state(*this, D);
2610
2611 TypeSourceInfo *ReturnTypeInfo = 0;
2612 QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
2613 if (declSpecTy.isNull())
2614 return Context.getNullTypeSourceInfo();
2615
2616 if (getLangOptions().ObjCAutoRefCount) {
2617 Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy);
2618 if (ownership != Qualifiers::OCL_None)
2619 transferARCOwnership(state, declSpecTy, ownership);
2620 }
2621
2622 return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo);
2623}
2624
John McCall14aa2172011-03-04 04:00:19 +00002625/// Map an AttributedType::Kind to an AttributeList::Kind.
2626static AttributeList::Kind getAttrListKind(AttributedType::Kind kind) {
2627 switch (kind) {
2628 case AttributedType::attr_address_space:
2629 return AttributeList::AT_address_space;
2630 case AttributedType::attr_regparm:
2631 return AttributeList::AT_regparm;
2632 case AttributedType::attr_vector_size:
2633 return AttributeList::AT_vector_size;
2634 case AttributedType::attr_neon_vector_type:
2635 return AttributeList::AT_neon_vector_type;
2636 case AttributedType::attr_neon_polyvector_type:
2637 return AttributeList::AT_neon_polyvector_type;
2638 case AttributedType::attr_objc_gc:
2639 return AttributeList::AT_objc_gc;
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00002640 case AttributedType::attr_objc_ownership:
2641 return AttributeList::AT_objc_ownership;
John McCall14aa2172011-03-04 04:00:19 +00002642 case AttributedType::attr_noreturn:
2643 return AttributeList::AT_noreturn;
2644 case AttributedType::attr_cdecl:
2645 return AttributeList::AT_cdecl;
2646 case AttributedType::attr_fastcall:
2647 return AttributeList::AT_fastcall;
2648 case AttributedType::attr_stdcall:
2649 return AttributeList::AT_stdcall;
2650 case AttributedType::attr_thiscall:
2651 return AttributeList::AT_thiscall;
2652 case AttributedType::attr_pascal:
2653 return AttributeList::AT_pascal;
Anton Korobeynikov414d8962011-04-14 20:06:49 +00002654 case AttributedType::attr_pcs:
2655 return AttributeList::AT_pcs;
John McCall14aa2172011-03-04 04:00:19 +00002656 }
2657 llvm_unreachable("unexpected attribute kind!");
2658 return AttributeList::Kind();
2659}
2660
2661static void fillAttributedTypeLoc(AttributedTypeLoc TL,
2662 const AttributeList *attrs) {
2663 AttributedType::Kind kind = TL.getAttrKind();
2664
2665 assert(attrs && "no type attributes in the expected location!");
2666 AttributeList::Kind parsedKind = getAttrListKind(kind);
2667 while (attrs->getKind() != parsedKind) {
2668 attrs = attrs->getNext();
2669 assert(attrs && "no matching attribute in expected location!");
2670 }
2671
2672 TL.setAttrNameLoc(attrs->getLoc());
2673 if (TL.hasAttrExprOperand())
2674 TL.setAttrExprOperand(attrs->getArg(0));
2675 else if (TL.hasAttrEnumOperand())
2676 TL.setAttrEnumOperandLoc(attrs->getParameterLoc());
2677
2678 // FIXME: preserve this information to here.
2679 if (TL.hasAttrOperand())
2680 TL.setAttrOperandParensRange(SourceRange());
2681}
2682
John McCall51bd8032009-10-18 01:05:36 +00002683namespace {
2684 class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
Douglas Gregorc21c7e92011-01-25 19:13:18 +00002685 ASTContext &Context;
John McCall51bd8032009-10-18 01:05:36 +00002686 const DeclSpec &DS;
Argyrios Kyrtzidisf352bdd2009-09-29 19:43:35 +00002687
John McCall51bd8032009-10-18 01:05:36 +00002688 public:
Douglas Gregorc21c7e92011-01-25 19:13:18 +00002689 TypeSpecLocFiller(ASTContext &Context, const DeclSpec &DS)
2690 : Context(Context), DS(DS) {}
Argyrios Kyrtzidisf352bdd2009-09-29 19:43:35 +00002691
John McCall14aa2172011-03-04 04:00:19 +00002692 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
2693 fillAttributedTypeLoc(TL, DS.getAttributes().getList());
2694 Visit(TL.getModifiedLoc());
2695 }
John McCall51bd8032009-10-18 01:05:36 +00002696 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
2697 Visit(TL.getUnqualifiedLoc());
2698 }
2699 void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
2700 TL.setNameLoc(DS.getTypeSpecTypeLoc());
2701 }
2702 void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
2703 TL.setNameLoc(DS.getTypeSpecTypeLoc());
John McCallc12c5bb2010-05-15 11:32:37 +00002704 }
2705 void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
2706 // Handle the base type, which might not have been written explicitly.
2707 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
2708 TL.setHasBaseTypeAsWritten(false);
Douglas Gregorc21c7e92011-01-25 19:13:18 +00002709 TL.getBaseLoc().initialize(Context, SourceLocation());
John McCallc12c5bb2010-05-15 11:32:37 +00002710 } else {
2711 TL.setHasBaseTypeAsWritten(true);
2712 Visit(TL.getBaseLoc());
2713 }
Argyrios Kyrtzidiseb667592009-09-29 19:45:22 +00002714
John McCallc12c5bb2010-05-15 11:32:37 +00002715 // Protocol qualifiers.
John McCall54e14c42009-10-22 22:37:11 +00002716 if (DS.getProtocolQualifiers()) {
2717 assert(TL.getNumProtocols() > 0);
2718 assert(TL.getNumProtocols() == DS.getNumProtocolQualifiers());
2719 TL.setLAngleLoc(DS.getProtocolLAngleLoc());
2720 TL.setRAngleLoc(DS.getSourceRange().getEnd());
2721 for (unsigned i = 0, e = DS.getNumProtocolQualifiers(); i != e; ++i)
2722 TL.setProtocolLoc(i, DS.getProtocolLocs()[i]);
2723 } else {
2724 assert(TL.getNumProtocols() == 0);
2725 TL.setLAngleLoc(SourceLocation());
2726 TL.setRAngleLoc(SourceLocation());
2727 }
2728 }
2729 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCall54e14c42009-10-22 22:37:11 +00002730 TL.setStarLoc(SourceLocation());
John McCallc12c5bb2010-05-15 11:32:37 +00002731 Visit(TL.getPointeeLoc());
John McCall51bd8032009-10-18 01:05:36 +00002732 }
John McCall833ca992009-10-29 08:12:44 +00002733 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
John McCalla93c9342009-12-07 02:54:59 +00002734 TypeSourceInfo *TInfo = 0;
John McCallb3d87482010-08-24 05:47:05 +00002735 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
John McCall833ca992009-10-29 08:12:44 +00002736
2737 // If we got no declarator info from previous Sema routines,
2738 // just fill with the typespec loc.
John McCalla93c9342009-12-07 02:54:59 +00002739 if (!TInfo) {
Abramo Bagnara0daaf322011-03-16 20:16:18 +00002740 TL.initialize(Context, DS.getTypeSpecTypeNameLoc());
John McCall833ca992009-10-29 08:12:44 +00002741 return;
2742 }
2743
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00002744 TypeLoc OldTL = TInfo->getTypeLoc();
2745 if (TInfo->getType()->getAs<ElaboratedType>()) {
2746 ElaboratedTypeLoc ElabTL = cast<ElaboratedTypeLoc>(OldTL);
2747 TemplateSpecializationTypeLoc NamedTL =
2748 cast<TemplateSpecializationTypeLoc>(ElabTL.getNamedTypeLoc());
2749 TL.copy(NamedTL);
2750 }
2751 else
2752 TL.copy(cast<TemplateSpecializationTypeLoc>(OldTL));
John McCall833ca992009-10-29 08:12:44 +00002753 }
John McCallcfb708c2010-01-13 20:03:27 +00002754 void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
2755 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr);
2756 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
2757 TL.setParensRange(DS.getTypeofParensRange());
2758 }
2759 void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
2760 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType);
2761 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
2762 TL.setParensRange(DS.getTypeofParensRange());
John McCallb3d87482010-08-24 05:47:05 +00002763 assert(DS.getRepAsType());
John McCallcfb708c2010-01-13 20:03:27 +00002764 TypeSourceInfo *TInfo = 0;
John McCallb3d87482010-08-24 05:47:05 +00002765 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
John McCallcfb708c2010-01-13 20:03:27 +00002766 TL.setUnderlyingTInfo(TInfo);
2767 }
Sean Huntca63c202011-05-24 22:41:36 +00002768 void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
2769 // FIXME: This holds only because we only have one unary transform.
2770 assert(DS.getTypeSpecType() == DeclSpec::TST_underlyingType);
2771 TL.setKWLoc(DS.getTypeSpecTypeLoc());
2772 TL.setParensRange(DS.getTypeofParensRange());
2773 assert(DS.getRepAsType());
2774 TypeSourceInfo *TInfo = 0;
2775 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
2776 TL.setUnderlyingTInfo(TInfo);
2777 }
Douglas Gregorddf889a2010-01-18 18:04:31 +00002778 void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
2779 // By default, use the source location of the type specifier.
2780 TL.setBuiltinLoc(DS.getTypeSpecTypeLoc());
2781 if (TL.needsExtraLocalData()) {
2782 // Set info for the written builtin specifiers.
2783 TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs();
2784 // Try to have a meaningful source location.
2785 if (TL.getWrittenSignSpec() != TSS_unspecified)
2786 // Sign spec loc overrides the others (e.g., 'unsigned long').
2787 TL.setBuiltinLoc(DS.getTypeSpecSignLoc());
2788 else if (TL.getWrittenWidthSpec() != TSW_unspecified)
2789 // Width spec loc overrides type spec loc (e.g., 'short int').
2790 TL.setBuiltinLoc(DS.getTypeSpecWidthLoc());
2791 }
2792 }
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00002793 void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
2794 ElaboratedTypeKeyword Keyword
2795 = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
Nico Weber253e80b2010-11-22 10:30:56 +00002796 if (DS.getTypeSpecType() == TST_typename) {
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00002797 TypeSourceInfo *TInfo = 0;
John McCallb3d87482010-08-24 05:47:05 +00002798 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00002799 if (TInfo) {
2800 TL.copy(cast<ElaboratedTypeLoc>(TInfo->getTypeLoc()));
2801 return;
2802 }
2803 }
2804 TL.setKeywordLoc(Keyword != ETK_None
2805 ? DS.getTypeSpecTypeLoc()
2806 : SourceLocation());
2807 const CXXScopeSpec& SS = DS.getTypeSpecScope();
Douglas Gregor9e876872011-03-01 18:12:44 +00002808 TL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00002809 Visit(TL.getNextTypeLoc().getUnqualifiedLoc());
2810 }
2811 void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
2812 ElaboratedTypeKeyword Keyword
2813 = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
Nico Weber253e80b2010-11-22 10:30:56 +00002814 if (DS.getTypeSpecType() == TST_typename) {
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00002815 TypeSourceInfo *TInfo = 0;
John McCallb3d87482010-08-24 05:47:05 +00002816 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00002817 if (TInfo) {
2818 TL.copy(cast<DependentNameTypeLoc>(TInfo->getTypeLoc()));
2819 return;
2820 }
2821 }
2822 TL.setKeywordLoc(Keyword != ETK_None
2823 ? DS.getTypeSpecTypeLoc()
2824 : SourceLocation());
2825 const CXXScopeSpec& SS = DS.getTypeSpecScope();
Douglas Gregor2494dd02011-03-01 01:34:45 +00002826 TL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnara0daaf322011-03-16 20:16:18 +00002827 TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00002828 }
John McCall33500952010-06-11 00:33:02 +00002829 void VisitDependentTemplateSpecializationTypeLoc(
2830 DependentTemplateSpecializationTypeLoc TL) {
2831 ElaboratedTypeKeyword Keyword
2832 = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
2833 if (Keyword == ETK_Typename) {
2834 TypeSourceInfo *TInfo = 0;
John McCallb3d87482010-08-24 05:47:05 +00002835 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
John McCall33500952010-06-11 00:33:02 +00002836 if (TInfo) {
2837 TL.copy(cast<DependentTemplateSpecializationTypeLoc>(
2838 TInfo->getTypeLoc()));
2839 return;
2840 }
2841 }
Douglas Gregorc21c7e92011-01-25 19:13:18 +00002842 TL.initializeLocal(Context, SourceLocation());
John McCall33500952010-06-11 00:33:02 +00002843 TL.setKeywordLoc(Keyword != ETK_None
2844 ? DS.getTypeSpecTypeLoc()
2845 : SourceLocation());
2846 const CXXScopeSpec& SS = DS.getTypeSpecScope();
Douglas Gregor94fdffa2011-03-01 20:11:18 +00002847 TL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnara0daaf322011-03-16 20:16:18 +00002848 TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
2849 }
2850 void VisitTagTypeLoc(TagTypeLoc TL) {
2851 TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
John McCall33500952010-06-11 00:33:02 +00002852 }
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00002853
John McCall51bd8032009-10-18 01:05:36 +00002854 void VisitTypeLoc(TypeLoc TL) {
2855 // FIXME: add other typespec types and change this to an assert.
Douglas Gregorc21c7e92011-01-25 19:13:18 +00002856 TL.initialize(Context, DS.getTypeSpecTypeLoc());
John McCall51bd8032009-10-18 01:05:36 +00002857 }
2858 };
Argyrios Kyrtzidisf352bdd2009-09-29 19:43:35 +00002859
John McCall51bd8032009-10-18 01:05:36 +00002860 class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
Abramo Bagnarab6ab6c12011-03-05 14:42:21 +00002861 ASTContext &Context;
John McCall51bd8032009-10-18 01:05:36 +00002862 const DeclaratorChunk &Chunk;
2863
2864 public:
Abramo Bagnarab6ab6c12011-03-05 14:42:21 +00002865 DeclaratorLocFiller(ASTContext &Context, const DeclaratorChunk &Chunk)
2866 : Context(Context), Chunk(Chunk) {}
John McCall51bd8032009-10-18 01:05:36 +00002867
2868 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002869 llvm_unreachable("qualified type locs not expected here!");
John McCall51bd8032009-10-18 01:05:36 +00002870 }
2871
John McCallf85e1932011-06-15 23:02:42 +00002872 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
2873 fillAttributedTypeLoc(TL, Chunk.getAttrs());
2874 }
John McCall51bd8032009-10-18 01:05:36 +00002875 void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
2876 assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
2877 TL.setCaretLoc(Chunk.Loc);
2878 }
2879 void VisitPointerTypeLoc(PointerTypeLoc TL) {
2880 assert(Chunk.Kind == DeclaratorChunk::Pointer);
2881 TL.setStarLoc(Chunk.Loc);
2882 }
2883 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
2884 assert(Chunk.Kind == DeclaratorChunk::Pointer);
2885 TL.setStarLoc(Chunk.Loc);
2886 }
2887 void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
2888 assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
Abramo Bagnarab6ab6c12011-03-05 14:42:21 +00002889 const CXXScopeSpec& SS = Chunk.Mem.Scope();
2890 NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context);
2891
2892 const Type* ClsTy = TL.getClass();
2893 QualType ClsQT = QualType(ClsTy, 0);
2894 TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0);
2895 // Now copy source location info into the type loc component.
2896 TypeLoc ClsTL = ClsTInfo->getTypeLoc();
2897 switch (NNSLoc.getNestedNameSpecifier()->getKind()) {
2898 case NestedNameSpecifier::Identifier:
2899 assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc");
2900 {
Abramo Bagnarafd9c42e2011-03-06 22:48:24 +00002901 DependentNameTypeLoc DNTLoc = cast<DependentNameTypeLoc>(ClsTL);
Abramo Bagnarab6ab6c12011-03-05 14:42:21 +00002902 DNTLoc.setKeywordLoc(SourceLocation());
2903 DNTLoc.setQualifierLoc(NNSLoc.getPrefix());
2904 DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc());
2905 }
2906 break;
2907
2908 case NestedNameSpecifier::TypeSpec:
2909 case NestedNameSpecifier::TypeSpecWithTemplate:
2910 if (isa<ElaboratedType>(ClsTy)) {
2911 ElaboratedTypeLoc ETLoc = *cast<ElaboratedTypeLoc>(&ClsTL);
2912 ETLoc.setKeywordLoc(SourceLocation());
2913 ETLoc.setQualifierLoc(NNSLoc.getPrefix());
2914 TypeLoc NamedTL = ETLoc.getNamedTypeLoc();
2915 NamedTL.initializeFullCopy(NNSLoc.getTypeLoc());
2916 } else {
2917 ClsTL.initializeFullCopy(NNSLoc.getTypeLoc());
2918 }
2919 break;
2920
2921 case NestedNameSpecifier::Namespace:
2922 case NestedNameSpecifier::NamespaceAlias:
2923 case NestedNameSpecifier::Global:
2924 llvm_unreachable("Nested-name-specifier must name a type");
2925 break;
2926 }
2927
2928 // Finally fill in MemberPointerLocInfo fields.
John McCall51bd8032009-10-18 01:05:36 +00002929 TL.setStarLoc(Chunk.Loc);
Abramo Bagnarab6ab6c12011-03-05 14:42:21 +00002930 TL.setClassTInfo(ClsTInfo);
John McCall51bd8032009-10-18 01:05:36 +00002931 }
2932 void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
2933 assert(Chunk.Kind == DeclaratorChunk::Reference);
John McCall54e14c42009-10-22 22:37:11 +00002934 // 'Amp' is misleading: this might have been originally
2935 /// spelled with AmpAmp.
John McCall51bd8032009-10-18 01:05:36 +00002936 TL.setAmpLoc(Chunk.Loc);
2937 }
2938 void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
2939 assert(Chunk.Kind == DeclaratorChunk::Reference);
2940 assert(!Chunk.Ref.LValueRef);
2941 TL.setAmpAmpLoc(Chunk.Loc);
2942 }
2943 void VisitArrayTypeLoc(ArrayTypeLoc TL) {
2944 assert(Chunk.Kind == DeclaratorChunk::Array);
2945 TL.setLBracketLoc(Chunk.Loc);
2946 TL.setRBracketLoc(Chunk.EndLoc);
2947 TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
2948 }
2949 void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
2950 assert(Chunk.Kind == DeclaratorChunk::Function);
Abramo Bagnara796aa442011-03-12 11:17:06 +00002951 TL.setLocalRangeBegin(Chunk.Loc);
2952 TL.setLocalRangeEnd(Chunk.EndLoc);
Douglas Gregordab60ad2010-10-01 18:44:50 +00002953 TL.setTrailingReturn(!!Chunk.Fun.TrailingReturnType);
John McCall51bd8032009-10-18 01:05:36 +00002954
2955 const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
John McCall54e14c42009-10-22 22:37:11 +00002956 for (unsigned i = 0, e = TL.getNumArgs(), tpi = 0; i != e; ++i) {
John McCalld226f652010-08-21 09:40:31 +00002957 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
John McCall54e14c42009-10-22 22:37:11 +00002958 TL.setArg(tpi++, Param);
John McCall51bd8032009-10-18 01:05:36 +00002959 }
2960 // FIXME: exception specs
2961 }
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002962 void VisitParenTypeLoc(ParenTypeLoc TL) {
2963 assert(Chunk.Kind == DeclaratorChunk::Paren);
2964 TL.setLParenLoc(Chunk.Loc);
2965 TL.setRParenLoc(Chunk.EndLoc);
2966 }
John McCall51bd8032009-10-18 01:05:36 +00002967
2968 void VisitTypeLoc(TypeLoc TL) {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002969 llvm_unreachable("unsupported TypeLoc kind in declarator!");
John McCall51bd8032009-10-18 01:05:36 +00002970 }
2971 };
Argyrios Kyrtzidisf352bdd2009-09-29 19:43:35 +00002972}
2973
John McCalla93c9342009-12-07 02:54:59 +00002974/// \brief Create and instantiate a TypeSourceInfo with type source information.
Argyrios Kyrtzidis4adab7f2009-08-19 01:28:06 +00002975///
2976/// \param T QualType referring to the type as written in source code.
Douglas Gregor05baacb2010-04-12 23:19:01 +00002977///
2978/// \param ReturnTypeInfo For declarators whose return type does not show
2979/// up in the normal place in the declaration specifiers (such as a C++
2980/// conversion function), this pointer will refer to a type source information
2981/// for that return type.
John McCalla93c9342009-12-07 02:54:59 +00002982TypeSourceInfo *
Douglas Gregor05baacb2010-04-12 23:19:01 +00002983Sema::GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
2984 TypeSourceInfo *ReturnTypeInfo) {
John McCalla93c9342009-12-07 02:54:59 +00002985 TypeSourceInfo *TInfo = Context.CreateTypeSourceInfo(T);
2986 UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc();
Argyrios Kyrtzidis4adab7f2009-08-19 01:28:06 +00002987
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002988 // Handle parameter packs whose type is a pack expansion.
2989 if (isa<PackExpansionType>(T)) {
2990 cast<PackExpansionTypeLoc>(CurrTL).setEllipsisLoc(D.getEllipsisLoc());
2991 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
2992 }
2993
Sebastian Redl8ce35b02009-10-25 21:45:37 +00002994 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
John McCall14aa2172011-03-04 04:00:19 +00002995 while (isa<AttributedTypeLoc>(CurrTL)) {
2996 AttributedTypeLoc TL = cast<AttributedTypeLoc>(CurrTL);
2997 fillAttributedTypeLoc(TL, D.getTypeObject(i).getAttrs());
2998 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
2999 }
3000
Abramo Bagnarab6ab6c12011-03-05 14:42:21 +00003001 DeclaratorLocFiller(Context, D.getTypeObject(i)).Visit(CurrTL);
John McCall51bd8032009-10-18 01:05:36 +00003002 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
Argyrios Kyrtzidis4adab7f2009-08-19 01:28:06 +00003003 }
Argyrios Kyrtzidisf352bdd2009-09-29 19:43:35 +00003004
John McCallb3d87482010-08-24 05:47:05 +00003005 // If we have different source information for the return type, use
3006 // that. This really only applies to C++ conversion functions.
3007 if (ReturnTypeInfo) {
Douglas Gregor05baacb2010-04-12 23:19:01 +00003008 TypeLoc TL = ReturnTypeInfo->getTypeLoc();
3009 assert(TL.getFullDataSize() == CurrTL.getFullDataSize());
3010 memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize());
John McCallb3d87482010-08-24 05:47:05 +00003011 } else {
Douglas Gregorc21c7e92011-01-25 19:13:18 +00003012 TypeSpecLocFiller(Context, D.getDeclSpec()).Visit(CurrTL);
Douglas Gregor05baacb2010-04-12 23:19:01 +00003013 }
3014
John McCalla93c9342009-12-07 02:54:59 +00003015 return TInfo;
Argyrios Kyrtzidis4adab7f2009-08-19 01:28:06 +00003016}
3017
John McCalla93c9342009-12-07 02:54:59 +00003018/// \brief Create a LocInfoType to hold the given QualType and TypeSourceInfo.
John McCallb3d87482010-08-24 05:47:05 +00003019ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) {
Argyrios Kyrtzidis1bb8a452009-08-19 01:28:17 +00003020 // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
3021 // and Sema during declaration parsing. Try deallocating/caching them when
3022 // it's appropriate, instead of allocating them and keeping them around.
Douglas Gregoreb0eb492010-12-10 08:12:03 +00003023 LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType),
3024 TypeAlignment);
John McCalla93c9342009-12-07 02:54:59 +00003025 new (LocT) LocInfoType(T, TInfo);
Argyrios Kyrtzidis1bb8a452009-08-19 01:28:17 +00003026 assert(LocT->getTypeClass() != T->getTypeClass() &&
3027 "LocInfoType's TypeClass conflicts with an existing Type class");
John McCallb3d87482010-08-24 05:47:05 +00003028 return ParsedType::make(QualType(LocT, 0));
Argyrios Kyrtzidis1bb8a452009-08-19 01:28:17 +00003029}
3030
3031void LocInfoType::getAsStringInternal(std::string &Str,
3032 const PrintingPolicy &Policy) const {
Argyrios Kyrtzidis35d44e52009-08-19 01:46:06 +00003033 assert(false && "LocInfoType leaked into the type system; an opaque TypeTy*"
3034 " was used directly instead of getting the QualType through"
3035 " GetTypeFromParser");
Argyrios Kyrtzidis1bb8a452009-08-19 01:28:17 +00003036}
3037
John McCallf312b1e2010-08-26 23:41:50 +00003038TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003039 // C99 6.7.6: Type names have no identifier. This is already validated by
3040 // the parser.
3041 assert(D.getIdentifier() == 0 && "Type name should have no identifier!");
Mike Stump1eb44332009-09-09 15:08:12 +00003042
Argyrios Kyrtzidisd3880f82011-06-28 03:01:18 +00003043 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCallbf1a0282010-06-04 23:28:52 +00003044 QualType T = TInfo->getType();
Chris Lattner5153ee62009-04-25 08:47:54 +00003045 if (D.isInvalidType())
Douglas Gregor809070a2009-02-18 17:45:20 +00003046 return true;
Steve Naroff5912a352007-08-28 20:14:24 +00003047
Douglas Gregor402abb52009-05-28 23:31:59 +00003048 if (getLangOptions().CPlusPlus) {
3049 // Check that there are no default arguments (C++ only).
Douglas Gregor6d6eb572008-05-07 04:49:29 +00003050 CheckExtraCXXDefaultArguments(D);
Douglas Gregor402abb52009-05-28 23:31:59 +00003051 }
3052
John McCallb3d87482010-08-24 05:47:05 +00003053 return CreateParsedType(T, TInfo);
Reid Spencer5f016e22007-07-11 17:01:13 +00003054}
3055
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003056//===----------------------------------------------------------------------===//
3057// Type Attribute Processing
3058//===----------------------------------------------------------------------===//
3059
3060/// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
3061/// specified type. The attribute contains 1 argument, the id of the address
3062/// space for the type.
Mike Stump1eb44332009-09-09 15:08:12 +00003063static void HandleAddressSpaceTypeAttribute(QualType &Type,
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003064 const AttributeList &Attr, Sema &S){
John McCall0953e762009-09-24 19:53:00 +00003065
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003066 // If this type is already address space qualified, reject it.
Peter Collingbourne29e3ef82011-07-27 20:29:53 +00003067 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified by
3068 // qualifiers for two or more different address spaces."
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003069 if (Type.getAddressSpace()) {
3070 S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers);
Abramo Bagnarae215f722010-04-30 13:10:51 +00003071 Attr.setInvalid();
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003072 return;
3073 }
Mike Stump1eb44332009-09-09 15:08:12 +00003074
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003075 // Check the attribute arguments.
3076 if (Attr.getNumArgs() != 1) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003077 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
Abramo Bagnarae215f722010-04-30 13:10:51 +00003078 Attr.setInvalid();
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003079 return;
3080 }
3081 Expr *ASArgExpr = static_cast<Expr *>(Attr.getArg(0));
3082 llvm::APSInt addrSpace(32);
Douglas Gregorac06a0e2010-05-18 23:01:22 +00003083 if (ASArgExpr->isTypeDependent() || ASArgExpr->isValueDependent() ||
3084 !ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003085 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_not_int)
3086 << ASArgExpr->getSourceRange();
Abramo Bagnarae215f722010-04-30 13:10:51 +00003087 Attr.setInvalid();
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003088 return;
3089 }
3090
John McCallefadb772009-07-28 06:52:18 +00003091 // Bounds checking.
3092 if (addrSpace.isSigned()) {
3093 if (addrSpace.isNegative()) {
3094 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_negative)
3095 << ASArgExpr->getSourceRange();
Abramo Bagnarae215f722010-04-30 13:10:51 +00003096 Attr.setInvalid();
John McCallefadb772009-07-28 06:52:18 +00003097 return;
3098 }
3099 addrSpace.setIsSigned(false);
3100 }
3101 llvm::APSInt max(addrSpace.getBitWidth());
John McCall0953e762009-09-24 19:53:00 +00003102 max = Qualifiers::MaxAddressSpace;
John McCallefadb772009-07-28 06:52:18 +00003103 if (addrSpace > max) {
3104 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_too_high)
John McCall0953e762009-09-24 19:53:00 +00003105 << Qualifiers::MaxAddressSpace << ASArgExpr->getSourceRange();
Abramo Bagnarae215f722010-04-30 13:10:51 +00003106 Attr.setInvalid();
John McCallefadb772009-07-28 06:52:18 +00003107 return;
3108 }
3109
Mike Stump1eb44332009-09-09 15:08:12 +00003110 unsigned ASIdx = static_cast<unsigned>(addrSpace.getZExtValue());
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00003111 Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003112}
3113
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00003114/// handleObjCOwnershipTypeAttr - Process an objc_ownership
John McCallf85e1932011-06-15 23:02:42 +00003115/// attribute on the specified type.
3116///
3117/// Returns 'true' if the attribute was handled.
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00003118static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
John McCallf85e1932011-06-15 23:02:42 +00003119 AttributeList &attr,
3120 QualType &type) {
3121 if (!type->isObjCRetainableType() && !type->isDependentType())
3122 return false;
3123
3124 Sema &S = state.getSema();
3125
3126 if (type.getQualifiers().getObjCLifetime()) {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00003127 S.Diag(attr.getLoc(), diag::err_attr_objc_ownership_redundant)
John McCallf85e1932011-06-15 23:02:42 +00003128 << type;
3129 return true;
3130 }
3131
3132 if (!attr.getParameterName()) {
3133 S.Diag(attr.getLoc(), diag::err_attribute_argument_n_not_string)
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00003134 << "objc_ownership" << 1;
John McCallf85e1932011-06-15 23:02:42 +00003135 attr.setInvalid();
3136 return true;
3137 }
3138
3139 Qualifiers::ObjCLifetime lifetime;
3140 if (attr.getParameterName()->isStr("none"))
3141 lifetime = Qualifiers::OCL_ExplicitNone;
3142 else if (attr.getParameterName()->isStr("strong"))
3143 lifetime = Qualifiers::OCL_Strong;
3144 else if (attr.getParameterName()->isStr("weak"))
3145 lifetime = Qualifiers::OCL_Weak;
3146 else if (attr.getParameterName()->isStr("autoreleasing"))
3147 lifetime = Qualifiers::OCL_Autoreleasing;
3148 else {
3149 S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported)
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00003150 << "objc_ownership" << attr.getParameterName();
John McCallf85e1932011-06-15 23:02:42 +00003151 attr.setInvalid();
3152 return true;
3153 }
3154
3155 // Consume lifetime attributes without further comment outside of
3156 // ARC mode.
3157 if (!S.getLangOptions().ObjCAutoRefCount)
3158 return true;
3159
3160 Qualifiers qs;
3161 qs.setObjCLifetime(lifetime);
3162 QualType origType = type;
3163 type = S.Context.getQualifiedType(type, qs);
3164
3165 // If we have a valid source location for the attribute, use an
3166 // AttributedType instead.
3167 if (attr.getLoc().isValid())
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00003168 type = S.Context.getAttributedType(AttributedType::attr_objc_ownership,
John McCallf85e1932011-06-15 23:02:42 +00003169 origType, type);
3170
John McCall9f084a32011-07-06 00:26:06 +00003171 // Forbid __weak if the runtime doesn't support it.
John McCallf85e1932011-06-15 23:02:42 +00003172 if (lifetime == Qualifiers::OCL_Weak &&
John McCall9f084a32011-07-06 00:26:06 +00003173 !S.getLangOptions().ObjCRuntimeHasWeak) {
John McCallf85e1932011-06-15 23:02:42 +00003174
3175 // Actually, delay this until we know what we're parsing.
3176 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
3177 S.DelayedDiagnostics.add(
3178 sema::DelayedDiagnostic::makeForbiddenType(attr.getLoc(),
3179 diag::err_arc_weak_no_runtime, type, /*ignored*/ 0));
3180 } else {
3181 S.Diag(attr.getLoc(), diag::err_arc_weak_no_runtime);
3182 }
3183
3184 attr.setInvalid();
3185 return true;
3186 }
Fariborz Jahanian742352a2011-07-06 19:24:05 +00003187
3188 // Forbid __weak for class objects marked as
3189 // objc_arc_weak_reference_unavailable
3190 if (lifetime == Qualifiers::OCL_Weak) {
3191 QualType T = type;
Fariborz Jahanian742352a2011-07-06 19:24:05 +00003192 while (const PointerType *ptr = T->getAs<PointerType>())
3193 T = ptr->getPointeeType();
3194 if (const ObjCObjectPointerType *ObjT = T->getAs<ObjCObjectPointerType>()) {
3195 ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl();
Fariborz Jahanian7263fee2011-07-06 20:48:48 +00003196 if (Class->isArcWeakrefUnavailable()) {
Fariborz Jahanian742352a2011-07-06 19:24:05 +00003197 S.Diag(attr.getLoc(), diag::err_arc_unsupported_weak_class);
3198 S.Diag(ObjT->getInterfaceDecl()->getLocation(),
3199 diag::note_class_declared);
Fariborz Jahanian742352a2011-07-06 19:24:05 +00003200 }
3201 }
3202 }
3203
John McCallf85e1932011-06-15 23:02:42 +00003204 return true;
3205}
3206
John McCall711c52b2011-01-05 12:14:39 +00003207/// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type
3208/// attribute on the specified type. Returns true to indicate that
3209/// the attribute was handled, false to indicate that the type does
3210/// not permit the attribute.
3211static bool handleObjCGCTypeAttr(TypeProcessingState &state,
3212 AttributeList &attr,
3213 QualType &type) {
3214 Sema &S = state.getSema();
3215
3216 // Delay if this isn't some kind of pointer.
3217 if (!type->isPointerType() &&
3218 !type->isObjCObjectPointerType() &&
3219 !type->isBlockPointerType())
3220 return false;
3221
3222 if (type.getObjCGCAttr() != Qualifiers::GCNone) {
3223 S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc);
3224 attr.setInvalid();
3225 return true;
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00003226 }
Mike Stump1eb44332009-09-09 15:08:12 +00003227
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00003228 // Check the attribute arguments.
John McCall711c52b2011-01-05 12:14:39 +00003229 if (!attr.getParameterName()) {
3230 S.Diag(attr.getLoc(), diag::err_attribute_argument_n_not_string)
Fariborz Jahanianba372b82009-02-18 17:52:36 +00003231 << "objc_gc" << 1;
John McCall711c52b2011-01-05 12:14:39 +00003232 attr.setInvalid();
3233 return true;
Fariborz Jahanianba372b82009-02-18 17:52:36 +00003234 }
John McCall0953e762009-09-24 19:53:00 +00003235 Qualifiers::GC GCAttr;
John McCall711c52b2011-01-05 12:14:39 +00003236 if (attr.getNumArgs() != 0) {
3237 S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
3238 attr.setInvalid();
3239 return true;
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00003240 }
John McCall711c52b2011-01-05 12:14:39 +00003241 if (attr.getParameterName()->isStr("weak"))
John McCall0953e762009-09-24 19:53:00 +00003242 GCAttr = Qualifiers::Weak;
John McCall711c52b2011-01-05 12:14:39 +00003243 else if (attr.getParameterName()->isStr("strong"))
John McCall0953e762009-09-24 19:53:00 +00003244 GCAttr = Qualifiers::Strong;
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00003245 else {
John McCall711c52b2011-01-05 12:14:39 +00003246 S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported)
3247 << "objc_gc" << attr.getParameterName();
3248 attr.setInvalid();
3249 return true;
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00003250 }
Mike Stump1eb44332009-09-09 15:08:12 +00003251
John McCall14aa2172011-03-04 04:00:19 +00003252 QualType origType = type;
3253 type = S.Context.getObjCGCQualType(origType, GCAttr);
3254
3255 // Make an attributed type to preserve the source information.
3256 if (attr.getLoc().isValid())
3257 type = S.Context.getAttributedType(AttributedType::attr_objc_gc,
3258 origType, type);
3259
John McCall711c52b2011-01-05 12:14:39 +00003260 return true;
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00003261}
3262
John McCalle6a365d2010-12-19 02:44:49 +00003263namespace {
3264 /// A helper class to unwrap a type down to a function for the
3265 /// purposes of applying attributes there.
3266 ///
3267 /// Use:
3268 /// FunctionTypeUnwrapper unwrapped(SemaRef, T);
3269 /// if (unwrapped.isFunctionType()) {
3270 /// const FunctionType *fn = unwrapped.get();
3271 /// // change fn somehow
3272 /// T = unwrapped.wrap(fn);
3273 /// }
3274 struct FunctionTypeUnwrapper {
3275 enum WrapKind {
3276 Desugar,
3277 Parens,
3278 Pointer,
3279 BlockPointer,
3280 Reference,
3281 MemberPointer
3282 };
3283
3284 QualType Original;
3285 const FunctionType *Fn;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003286 SmallVector<unsigned char /*WrapKind*/, 8> Stack;
John McCalle6a365d2010-12-19 02:44:49 +00003287
3288 FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) {
3289 while (true) {
3290 const Type *Ty = T.getTypePtr();
3291 if (isa<FunctionType>(Ty)) {
3292 Fn = cast<FunctionType>(Ty);
3293 return;
3294 } else if (isa<ParenType>(Ty)) {
3295 T = cast<ParenType>(Ty)->getInnerType();
3296 Stack.push_back(Parens);
3297 } else if (isa<PointerType>(Ty)) {
3298 T = cast<PointerType>(Ty)->getPointeeType();
3299 Stack.push_back(Pointer);
3300 } else if (isa<BlockPointerType>(Ty)) {
3301 T = cast<BlockPointerType>(Ty)->getPointeeType();
3302 Stack.push_back(BlockPointer);
3303 } else if (isa<MemberPointerType>(Ty)) {
3304 T = cast<MemberPointerType>(Ty)->getPointeeType();
3305 Stack.push_back(MemberPointer);
3306 } else if (isa<ReferenceType>(Ty)) {
3307 T = cast<ReferenceType>(Ty)->getPointeeType();
3308 Stack.push_back(Reference);
3309 } else {
3310 const Type *DTy = Ty->getUnqualifiedDesugaredType();
3311 if (Ty == DTy) {
3312 Fn = 0;
3313 return;
3314 }
3315
3316 T = QualType(DTy, 0);
3317 Stack.push_back(Desugar);
3318 }
3319 }
3320 }
3321
3322 bool isFunctionType() const { return (Fn != 0); }
3323 const FunctionType *get() const { return Fn; }
3324
3325 QualType wrap(Sema &S, const FunctionType *New) {
3326 // If T wasn't modified from the unwrapped type, do nothing.
3327 if (New == get()) return Original;
3328
3329 Fn = New;
3330 return wrap(S.Context, Original, 0);
3331 }
3332
3333 private:
3334 QualType wrap(ASTContext &C, QualType Old, unsigned I) {
3335 if (I == Stack.size())
3336 return C.getQualifiedType(Fn, Old.getQualifiers());
3337
3338 // Build up the inner type, applying the qualifiers from the old
3339 // type to the new type.
3340 SplitQualType SplitOld = Old.split();
3341
3342 // As a special case, tail-recurse if there are no qualifiers.
3343 if (SplitOld.second.empty())
3344 return wrap(C, SplitOld.first, I);
3345 return C.getQualifiedType(wrap(C, SplitOld.first, I), SplitOld.second);
3346 }
3347
3348 QualType wrap(ASTContext &C, const Type *Old, unsigned I) {
3349 if (I == Stack.size()) return QualType(Fn, 0);
3350
3351 switch (static_cast<WrapKind>(Stack[I++])) {
3352 case Desugar:
3353 // This is the point at which we potentially lose source
3354 // information.
3355 return wrap(C, Old->getUnqualifiedDesugaredType(), I);
3356
3357 case Parens: {
3358 QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I);
3359 return C.getParenType(New);
3360 }
3361
3362 case Pointer: {
3363 QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I);
3364 return C.getPointerType(New);
3365 }
3366
3367 case BlockPointer: {
3368 QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I);
3369 return C.getBlockPointerType(New);
3370 }
3371
3372 case MemberPointer: {
3373 const MemberPointerType *OldMPT = cast<MemberPointerType>(Old);
3374 QualType New = wrap(C, OldMPT->getPointeeType(), I);
3375 return C.getMemberPointerType(New, OldMPT->getClass());
3376 }
3377
3378 case Reference: {
3379 const ReferenceType *OldRef = cast<ReferenceType>(Old);
3380 QualType New = wrap(C, OldRef->getPointeeType(), I);
3381 if (isa<LValueReferenceType>(OldRef))
3382 return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue());
3383 else
3384 return C.getRValueReferenceType(New);
3385 }
3386 }
3387
3388 llvm_unreachable("unknown wrapping kind");
3389 return QualType();
3390 }
3391 };
3392}
3393
John McCall711c52b2011-01-05 12:14:39 +00003394/// Process an individual function attribute. Returns true to
3395/// indicate that the attribute was handled, false if it wasn't.
3396static bool handleFunctionTypeAttr(TypeProcessingState &state,
3397 AttributeList &attr,
3398 QualType &type) {
3399 Sema &S = state.getSema();
John McCalle6a365d2010-12-19 02:44:49 +00003400
John McCall711c52b2011-01-05 12:14:39 +00003401 FunctionTypeUnwrapper unwrapped(S, type);
Mike Stump24556362009-07-25 21:26:53 +00003402
John McCall711c52b2011-01-05 12:14:39 +00003403 if (attr.getKind() == AttributeList::AT_noreturn) {
3404 if (S.CheckNoReturnAttr(attr))
John McCall04a67a62010-02-05 21:31:56 +00003405 return true;
John McCalle6a365d2010-12-19 02:44:49 +00003406
John McCall711c52b2011-01-05 12:14:39 +00003407 // Delay if this is not a function type.
3408 if (!unwrapped.isFunctionType())
3409 return false;
3410
John McCall04a67a62010-02-05 21:31:56 +00003411 // Otherwise we can process right away.
John McCall711c52b2011-01-05 12:14:39 +00003412 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true);
3413 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
3414 return true;
John McCall04a67a62010-02-05 21:31:56 +00003415 }
Mike Stump24556362009-07-25 21:26:53 +00003416
John McCallf85e1932011-06-15 23:02:42 +00003417 // ns_returns_retained is not always a type attribute, but if we got
3418 // here, we're treating it as one right now.
3419 if (attr.getKind() == AttributeList::AT_ns_returns_retained) {
3420 assert(S.getLangOptions().ObjCAutoRefCount &&
3421 "ns_returns_retained treated as type attribute in non-ARC");
3422 if (attr.getNumArgs()) return true;
3423
3424 // Delay if this is not a function type.
3425 if (!unwrapped.isFunctionType())
3426 return false;
3427
3428 FunctionType::ExtInfo EI
3429 = unwrapped.get()->getExtInfo().withProducesResult(true);
3430 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
3431 return true;
3432 }
3433
John McCall711c52b2011-01-05 12:14:39 +00003434 if (attr.getKind() == AttributeList::AT_regparm) {
3435 unsigned value;
3436 if (S.CheckRegparmAttr(attr, value))
Rafael Espindola425ef722010-03-30 22:15:11 +00003437 return true;
3438
John McCall711c52b2011-01-05 12:14:39 +00003439 // Delay if this is not a function type.
3440 if (!unwrapped.isFunctionType())
Rafael Espindola425ef722010-03-30 22:15:11 +00003441 return false;
3442
Argyrios Kyrtzidisce955662011-01-25 23:16:40 +00003443 // Diagnose regparm with fastcall.
3444 const FunctionType *fn = unwrapped.get();
3445 CallingConv CC = fn->getCallConv();
3446 if (CC == CC_X86FastCall) {
3447 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
3448 << FunctionType::getNameForCallConv(CC)
3449 << "regparm";
3450 attr.setInvalid();
3451 return true;
3452 }
3453
John McCalle6a365d2010-12-19 02:44:49 +00003454 FunctionType::ExtInfo EI =
John McCall711c52b2011-01-05 12:14:39 +00003455 unwrapped.get()->getExtInfo().withRegParm(value);
3456 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
3457 return true;
Rafael Espindola425ef722010-03-30 22:15:11 +00003458 }
3459
John McCall04a67a62010-02-05 21:31:56 +00003460 // Otherwise, a calling convention.
John McCall711c52b2011-01-05 12:14:39 +00003461 CallingConv CC;
3462 if (S.CheckCallingConvAttr(attr, CC))
3463 return true;
John McCallf82b4e82010-02-04 05:44:44 +00003464
John McCall04a67a62010-02-05 21:31:56 +00003465 // Delay if the type didn't work out to a function.
John McCall711c52b2011-01-05 12:14:39 +00003466 if (!unwrapped.isFunctionType()) return false;
John McCall04a67a62010-02-05 21:31:56 +00003467
John McCall711c52b2011-01-05 12:14:39 +00003468 const FunctionType *fn = unwrapped.get();
3469 CallingConv CCOld = fn->getCallConv();
Charles Davis064f7db2010-02-23 06:13:55 +00003470 if (S.Context.getCanonicalCallConv(CC) ==
Abramo Bagnarae215f722010-04-30 13:10:51 +00003471 S.Context.getCanonicalCallConv(CCOld)) {
Argyrios Kyrtzidisce955662011-01-25 23:16:40 +00003472 FunctionType::ExtInfo EI= unwrapped.get()->getExtInfo().withCallingConv(CC);
3473 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
John McCall711c52b2011-01-05 12:14:39 +00003474 return true;
Abramo Bagnarae215f722010-04-30 13:10:51 +00003475 }
John McCall04a67a62010-02-05 21:31:56 +00003476
3477 if (CCOld != CC_Default) {
3478 // Should we diagnose reapplications of the same convention?
John McCall711c52b2011-01-05 12:14:39 +00003479 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
John McCall04a67a62010-02-05 21:31:56 +00003480 << FunctionType::getNameForCallConv(CC)
3481 << FunctionType::getNameForCallConv(CCOld);
John McCall711c52b2011-01-05 12:14:39 +00003482 attr.setInvalid();
3483 return true;
John McCall04a67a62010-02-05 21:31:56 +00003484 }
3485
3486 // Diagnose the use of X86 fastcall on varargs or unprototyped functions.
3487 if (CC == CC_X86FastCall) {
John McCall711c52b2011-01-05 12:14:39 +00003488 if (isa<FunctionNoProtoType>(fn)) {
3489 S.Diag(attr.getLoc(), diag::err_cconv_knr)
John McCall04a67a62010-02-05 21:31:56 +00003490 << FunctionType::getNameForCallConv(CC);
John McCall711c52b2011-01-05 12:14:39 +00003491 attr.setInvalid();
3492 return true;
John McCall04a67a62010-02-05 21:31:56 +00003493 }
3494
John McCall711c52b2011-01-05 12:14:39 +00003495 const FunctionProtoType *FnP = cast<FunctionProtoType>(fn);
John McCall04a67a62010-02-05 21:31:56 +00003496 if (FnP->isVariadic()) {
John McCall711c52b2011-01-05 12:14:39 +00003497 S.Diag(attr.getLoc(), diag::err_cconv_varargs)
John McCall04a67a62010-02-05 21:31:56 +00003498 << FunctionType::getNameForCallConv(CC);
John McCall711c52b2011-01-05 12:14:39 +00003499 attr.setInvalid();
3500 return true;
John McCall04a67a62010-02-05 21:31:56 +00003501 }
Argyrios Kyrtzidisce955662011-01-25 23:16:40 +00003502
3503 // Also diagnose fastcall with regparm.
Eli Friedmana49218e2011-04-09 08:18:08 +00003504 if (fn->getHasRegParm()) {
Argyrios Kyrtzidisce955662011-01-25 23:16:40 +00003505 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
3506 << "regparm"
3507 << FunctionType::getNameForCallConv(CC);
3508 attr.setInvalid();
3509 return true;
3510 }
John McCall04a67a62010-02-05 21:31:56 +00003511 }
3512
John McCall711c52b2011-01-05 12:14:39 +00003513 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withCallingConv(CC);
3514 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
3515 return true;
John McCallf82b4e82010-02-04 05:44:44 +00003516}
3517
Peter Collingbourne207f4d82011-03-18 22:38:29 +00003518/// Handle OpenCL image access qualifiers: read_only, write_only, read_write
3519static void HandleOpenCLImageAccessAttribute(QualType& CurType,
3520 const AttributeList &Attr,
3521 Sema &S) {
3522 // Check the attribute arguments.
3523 if (Attr.getNumArgs() != 1) {
3524 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
3525 Attr.setInvalid();
3526 return;
3527 }
3528 Expr *sizeExpr = static_cast<Expr *>(Attr.getArg(0));
3529 llvm::APSInt arg(32);
3530 if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() ||
3531 !sizeExpr->isIntegerConstantExpr(arg, S.Context)) {
3532 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
3533 << "opencl_image_access" << sizeExpr->getSourceRange();
3534 Attr.setInvalid();
3535 return;
3536 }
3537 unsigned iarg = static_cast<unsigned>(arg.getZExtValue());
3538 switch (iarg) {
3539 case CLIA_read_only:
3540 case CLIA_write_only:
3541 case CLIA_read_write:
3542 // Implemented in a separate patch
3543 break;
3544 default:
3545 // Implemented in a separate patch
3546 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
3547 << sizeExpr->getSourceRange();
3548 Attr.setInvalid();
3549 break;
3550 }
3551}
3552
John Thompson6e132aa2009-12-04 21:51:28 +00003553/// HandleVectorSizeAttribute - this attribute is only applicable to integral
3554/// and float scalars, although arrays, pointers, and function return values are
3555/// allowed in conjunction with this construct. Aggregates with this attribute
3556/// are invalid, even if they are of the same size as a corresponding scalar.
3557/// The raw attribute should contain precisely 1 argument, the vector size for
3558/// the variable, measured in bytes. If curType and rawAttr are well formed,
3559/// this routine will return a new vector type.
Chris Lattner788b0fd2010-06-23 06:00:24 +00003560static void HandleVectorSizeAttr(QualType& CurType, const AttributeList &Attr,
3561 Sema &S) {
Bob Wilson56affbc2010-11-16 00:32:16 +00003562 // Check the attribute arguments.
John Thompson6e132aa2009-12-04 21:51:28 +00003563 if (Attr.getNumArgs() != 1) {
3564 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
Abramo Bagnarae215f722010-04-30 13:10:51 +00003565 Attr.setInvalid();
John Thompson6e132aa2009-12-04 21:51:28 +00003566 return;
3567 }
3568 Expr *sizeExpr = static_cast<Expr *>(Attr.getArg(0));
3569 llvm::APSInt vecSize(32);
Douglas Gregorac06a0e2010-05-18 23:01:22 +00003570 if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() ||
3571 !sizeExpr->isIntegerConstantExpr(vecSize, S.Context)) {
John Thompson6e132aa2009-12-04 21:51:28 +00003572 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
3573 << "vector_size" << sizeExpr->getSourceRange();
Abramo Bagnarae215f722010-04-30 13:10:51 +00003574 Attr.setInvalid();
John Thompson6e132aa2009-12-04 21:51:28 +00003575 return;
3576 }
3577 // the base type must be integer or float, and can't already be a vector.
Douglas Gregorf6094622010-07-23 15:58:24 +00003578 if (!CurType->isIntegerType() && !CurType->isRealFloatingType()) {
John Thompson6e132aa2009-12-04 21:51:28 +00003579 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
Abramo Bagnarae215f722010-04-30 13:10:51 +00003580 Attr.setInvalid();
John Thompson6e132aa2009-12-04 21:51:28 +00003581 return;
3582 }
3583 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
3584 // vecSize is specified in bytes - convert to bits.
3585 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
3586
3587 // the vector size needs to be an integral multiple of the type size.
3588 if (vectorSize % typeSize) {
3589 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
3590 << sizeExpr->getSourceRange();
Abramo Bagnarae215f722010-04-30 13:10:51 +00003591 Attr.setInvalid();
John Thompson6e132aa2009-12-04 21:51:28 +00003592 return;
3593 }
3594 if (vectorSize == 0) {
3595 S.Diag(Attr.getLoc(), diag::err_attribute_zero_size)
3596 << sizeExpr->getSourceRange();
Abramo Bagnarae215f722010-04-30 13:10:51 +00003597 Attr.setInvalid();
John Thompson6e132aa2009-12-04 21:51:28 +00003598 return;
3599 }
3600
3601 // Success! Instantiate the vector type, the number of elements is > 0, and
3602 // not required to be a power of 2, unlike GCC.
Chris Lattner788b0fd2010-06-23 06:00:24 +00003603 CurType = S.Context.getVectorType(CurType, vectorSize/typeSize,
Bob Wilsone86d78c2010-11-10 21:56:12 +00003604 VectorType::GenericVector);
John Thompson6e132aa2009-12-04 21:51:28 +00003605}
3606
Douglas Gregor4ac01402011-06-15 16:02:29 +00003607/// \brief Process the OpenCL-like ext_vector_type attribute when it occurs on
3608/// a type.
3609static void HandleExtVectorTypeAttr(QualType &CurType,
3610 const AttributeList &Attr,
3611 Sema &S) {
3612 Expr *sizeExpr;
3613
3614 // Special case where the argument is a template id.
3615 if (Attr.getParameterName()) {
3616 CXXScopeSpec SS;
3617 UnqualifiedId id;
3618 id.setIdentifier(Attr.getParameterName(), Attr.getLoc());
3619
3620 ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, id, false,
3621 false);
3622 if (Size.isInvalid())
3623 return;
3624
3625 sizeExpr = Size.get();
3626 } else {
3627 // check the attribute arguments.
3628 if (Attr.getNumArgs() != 1) {
3629 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
3630 return;
3631 }
3632 sizeExpr = Attr.getArg(0);
3633 }
3634
3635 // Create the vector type.
3636 QualType T = S.BuildExtVectorType(CurType, sizeExpr, Attr.getLoc());
3637 if (!T.isNull())
3638 CurType = T;
3639}
3640
Bob Wilson4211bb62010-11-16 00:32:24 +00003641/// HandleNeonVectorTypeAttr - The "neon_vector_type" and
3642/// "neon_polyvector_type" attributes are used to create vector types that
3643/// are mangled according to ARM's ABI. Otherwise, these types are identical
3644/// to those created with the "vector_size" attribute. Unlike "vector_size"
3645/// the argument to these Neon attributes is the number of vector elements,
3646/// not the vector size in bytes. The vector width and element type must
3647/// match one of the standard Neon vector types.
3648static void HandleNeonVectorTypeAttr(QualType& CurType,
3649 const AttributeList &Attr, Sema &S,
3650 VectorType::VectorKind VecKind,
3651 const char *AttrName) {
3652 // Check the attribute arguments.
3653 if (Attr.getNumArgs() != 1) {
3654 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
3655 Attr.setInvalid();
3656 return;
3657 }
3658 // The number of elements must be an ICE.
3659 Expr *numEltsExpr = static_cast<Expr *>(Attr.getArg(0));
3660 llvm::APSInt numEltsInt(32);
3661 if (numEltsExpr->isTypeDependent() || numEltsExpr->isValueDependent() ||
3662 !numEltsExpr->isIntegerConstantExpr(numEltsInt, S.Context)) {
3663 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
3664 << AttrName << numEltsExpr->getSourceRange();
3665 Attr.setInvalid();
3666 return;
3667 }
3668 // Only certain element types are supported for Neon vectors.
3669 const BuiltinType* BTy = CurType->getAs<BuiltinType>();
3670 if (!BTy ||
3671 (VecKind == VectorType::NeonPolyVector &&
3672 BTy->getKind() != BuiltinType::SChar &&
3673 BTy->getKind() != BuiltinType::Short) ||
3674 (BTy->getKind() != BuiltinType::SChar &&
3675 BTy->getKind() != BuiltinType::UChar &&
3676 BTy->getKind() != BuiltinType::Short &&
3677 BTy->getKind() != BuiltinType::UShort &&
3678 BTy->getKind() != BuiltinType::Int &&
3679 BTy->getKind() != BuiltinType::UInt &&
3680 BTy->getKind() != BuiltinType::LongLong &&
3681 BTy->getKind() != BuiltinType::ULongLong &&
3682 BTy->getKind() != BuiltinType::Float)) {
3683 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) <<CurType;
3684 Attr.setInvalid();
3685 return;
3686 }
3687 // The total size of the vector must be 64 or 128 bits.
3688 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
3689 unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue());
3690 unsigned vecSize = typeSize * numElts;
3691 if (vecSize != 64 && vecSize != 128) {
3692 S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType;
3693 Attr.setInvalid();
3694 return;
3695 }
3696
3697 CurType = S.Context.getVectorType(CurType, numElts, VecKind);
3698}
3699
John McCall711c52b2011-01-05 12:14:39 +00003700static void processTypeAttrs(TypeProcessingState &state, QualType &type,
3701 bool isDeclSpec, AttributeList *attrs) {
Chris Lattner232e8822008-02-21 01:08:11 +00003702 // Scan through and apply attributes to this type where it makes sense. Some
3703 // attributes (such as __address_space__, __vector_size__, etc) apply to the
3704 // type, but others can be present in the type specifiers even though they
Chris Lattnerfca0ddd2008-06-26 06:27:57 +00003705 // apply to the decl. Here we apply type attributes and ignore the rest.
John McCall711c52b2011-01-05 12:14:39 +00003706
3707 AttributeList *next;
3708 do {
3709 AttributeList &attr = *attrs;
3710 next = attr.getNext();
3711
Abramo Bagnarae215f722010-04-30 13:10:51 +00003712 // Skip attributes that were marked to be invalid.
John McCall711c52b2011-01-05 12:14:39 +00003713 if (attr.isInvalid())
Abramo Bagnarae215f722010-04-30 13:10:51 +00003714 continue;
3715
Abramo Bagnarab1f1b262010-04-30 09:13:03 +00003716 // If this is an attribute we can handle, do so now,
3717 // otherwise, add it to the FnAttrs list for rechaining.
John McCall711c52b2011-01-05 12:14:39 +00003718 switch (attr.getKind()) {
Chris Lattner232e8822008-02-21 01:08:11 +00003719 default: break;
John McCall04a67a62010-02-05 21:31:56 +00003720
Chris Lattner232e8822008-02-21 01:08:11 +00003721 case AttributeList::AT_address_space:
John McCall711c52b2011-01-05 12:14:39 +00003722 HandleAddressSpaceTypeAttribute(type, attr, state.getSema());
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003723 break;
John McCall711c52b2011-01-05 12:14:39 +00003724 OBJC_POINTER_TYPE_ATTRS_CASELIST:
3725 if (!handleObjCPointerTypeAttr(state, attr, type))
3726 distributeObjCPointerTypeAttr(state, attr, type);
Mike Stump24556362009-07-25 21:26:53 +00003727 break;
John Thompson6e132aa2009-12-04 21:51:28 +00003728 case AttributeList::AT_vector_size:
John McCall711c52b2011-01-05 12:14:39 +00003729 HandleVectorSizeAttr(type, attr, state.getSema());
John McCall04a67a62010-02-05 21:31:56 +00003730 break;
Douglas Gregor4ac01402011-06-15 16:02:29 +00003731 case AttributeList::AT_ext_vector_type:
3732 if (state.getDeclarator().getDeclSpec().getStorageClassSpec()
3733 != DeclSpec::SCS_typedef)
3734 HandleExtVectorTypeAttr(type, attr, state.getSema());
3735 break;
Bob Wilson4211bb62010-11-16 00:32:24 +00003736 case AttributeList::AT_neon_vector_type:
John McCall711c52b2011-01-05 12:14:39 +00003737 HandleNeonVectorTypeAttr(type, attr, state.getSema(),
3738 VectorType::NeonVector, "neon_vector_type");
Bob Wilson4211bb62010-11-16 00:32:24 +00003739 break;
3740 case AttributeList::AT_neon_polyvector_type:
John McCall711c52b2011-01-05 12:14:39 +00003741 HandleNeonVectorTypeAttr(type, attr, state.getSema(),
3742 VectorType::NeonPolyVector,
Bob Wilson4211bb62010-11-16 00:32:24 +00003743 "neon_polyvector_type");
3744 break;
Peter Collingbourne207f4d82011-03-18 22:38:29 +00003745 case AttributeList::AT_opencl_image_access:
3746 HandleOpenCLImageAccessAttribute(type, attr, state.getSema());
3747 break;
3748
John McCallf85e1932011-06-15 23:02:42 +00003749 case AttributeList::AT_ns_returns_retained:
3750 if (!state.getSema().getLangOptions().ObjCAutoRefCount)
3751 break;
3752 // fallthrough into the function attrs
3753
John McCall711c52b2011-01-05 12:14:39 +00003754 FUNCTION_TYPE_ATTRS_CASELIST:
3755 // Never process function type attributes as part of the
3756 // declaration-specifiers.
3757 if (isDeclSpec)
3758 distributeFunctionTypeAttrFromDeclSpec(state, attr, type);
3759
3760 // Otherwise, handle the possible delays.
3761 else if (!handleFunctionTypeAttr(state, attr, type))
3762 distributeFunctionTypeAttr(state, attr, type);
John Thompson6e132aa2009-12-04 21:51:28 +00003763 break;
Chris Lattner232e8822008-02-21 01:08:11 +00003764 }
John McCall711c52b2011-01-05 12:14:39 +00003765 } while ((attrs = next));
Chris Lattner232e8822008-02-21 01:08:11 +00003766}
3767
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003768/// \brief Ensure that the type of the given expression is complete.
3769///
3770/// This routine checks whether the expression \p E has a complete type. If the
3771/// expression refers to an instantiable construct, that instantiation is
3772/// performed as needed to complete its type. Furthermore
3773/// Sema::RequireCompleteType is called for the expression's type (or in the
3774/// case of a reference type, the referred-to type).
3775///
3776/// \param E The expression whose type is required to be complete.
3777/// \param PD The partial diagnostic that will be printed out if the type cannot
3778/// be completed.
3779///
3780/// \returns \c true if the type of \p E is incomplete and diagnosed, \c false
3781/// otherwise.
3782bool Sema::RequireCompleteExprType(Expr *E, const PartialDiagnostic &PD,
3783 std::pair<SourceLocation,
3784 PartialDiagnostic> Note) {
3785 QualType T = E->getType();
3786
3787 // Fast path the case where the type is already complete.
3788 if (!T->isIncompleteType())
3789 return false;
3790
3791 // Incomplete array types may be completed by the initializer attached to
3792 // their definitions. For static data members of class templates we need to
3793 // instantiate the definition to get this initializer and complete the type.
3794 if (T->isIncompleteArrayType()) {
3795 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3796 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
3797 if (Var->isStaticDataMember() &&
3798 Var->getInstantiatedFromStaticDataMember()) {
Douglas Gregor36f255c2011-06-03 14:28:43 +00003799
3800 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
3801 assert(MSInfo && "Missing member specialization information?");
3802 if (MSInfo->getTemplateSpecializationKind()
3803 != TSK_ExplicitSpecialization) {
3804 // If we don't already have a point of instantiation, this is it.
3805 if (MSInfo->getPointOfInstantiation().isInvalid()) {
3806 MSInfo->setPointOfInstantiation(E->getLocStart());
3807
3808 // This is a modification of an existing AST node. Notify
3809 // listeners.
3810 if (ASTMutationListener *L = getASTMutationListener())
3811 L->StaticDataMemberInstantiated(Var);
3812 }
3813
3814 InstantiateStaticDataMemberDefinition(E->getExprLoc(), Var);
3815
3816 // Update the type to the newly instantiated definition's type both
3817 // here and within the expression.
3818 if (VarDecl *Def = Var->getDefinition()) {
3819 DRE->setDecl(Def);
3820 T = Def->getType();
3821 DRE->setType(T);
3822 E->setType(T);
3823 }
Douglas Gregorf15748a2011-06-03 03:35:07 +00003824 }
3825
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003826 // We still go on to try to complete the type independently, as it
3827 // may also require instantiations or diagnostics if it remains
3828 // incomplete.
3829 }
3830 }
3831 }
3832 }
3833
3834 // FIXME: Are there other cases which require instantiating something other
3835 // than the type to complete the type of an expression?
3836
3837 // Look through reference types and complete the referred type.
3838 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
3839 T = Ref->getPointeeType();
3840
3841 return RequireCompleteType(E->getExprLoc(), T, PD, Note);
3842}
3843
Mike Stump1eb44332009-09-09 15:08:12 +00003844/// @brief Ensure that the type T is a complete type.
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003845///
3846/// This routine checks whether the type @p T is complete in any
3847/// context where a complete type is required. If @p T is a complete
Douglas Gregor86447ec2009-03-09 16:13:40 +00003848/// type, returns false. If @p T is a class template specialization,
3849/// this routine then attempts to perform class template
3850/// instantiation. If instantiation fails, or if @p T is incomplete
3851/// and cannot be completed, issues the diagnostic @p diag (giving it
3852/// the type @p T) and returns true.
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003853///
3854/// @param Loc The location in the source that the incomplete type
3855/// diagnostic should refer to.
3856///
3857/// @param T The type that this routine is examining for completeness.
3858///
Mike Stump1eb44332009-09-09 15:08:12 +00003859/// @param PD The partial diagnostic that will be printed out if T is not a
Anders Carlssonb7906612009-08-26 23:45:07 +00003860/// complete type.
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003861///
3862/// @returns @c true if @p T is incomplete and a diagnostic was emitted,
3863/// @c false otherwise.
Anders Carlsson91a0cc92009-08-26 22:33:56 +00003864bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
Anders Carlsson8c8d9192009-10-09 23:51:55 +00003865 const PartialDiagnostic &PD,
3866 std::pair<SourceLocation,
3867 PartialDiagnostic> Note) {
Anders Carlsson91a0cc92009-08-26 22:33:56 +00003868 unsigned diag = PD.getDiagID();
Mike Stump1eb44332009-09-09 15:08:12 +00003869
Douglas Gregor573d9c32009-10-21 23:19:44 +00003870 // FIXME: Add this assertion to make sure we always get instantiation points.
3871 // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
Douglas Gregor690dc7f2009-05-21 23:48:18 +00003872 // FIXME: Add this assertion to help us flush out problems with
3873 // checking for dependent types and type-dependent expressions.
3874 //
Mike Stump1eb44332009-09-09 15:08:12 +00003875 // assert(!T->isDependentType() &&
Douglas Gregor690dc7f2009-05-21 23:48:18 +00003876 // "Can't ask whether a dependent type is complete");
3877
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003878 // If we have a complete type, we're done.
3879 if (!T->isIncompleteType())
3880 return false;
Eli Friedman3c0eb162008-05-27 03:33:27 +00003881
Douglas Gregord475b8d2009-03-25 21:17:03 +00003882 // If we have a class template specialization or a class member of a
Sebastian Redl923d56d2009-11-05 15:52:31 +00003883 // class template specialization, or an array with known size of such,
3884 // try to instantiate it.
3885 QualType MaybeTemplate = T;
Douglas Gregor89c49f02009-11-09 22:08:55 +00003886 if (const ConstantArrayType *Array = Context.getAsConstantArrayType(T))
Sebastian Redl923d56d2009-11-05 15:52:31 +00003887 MaybeTemplate = Array->getElementType();
3888 if (const RecordType *Record = MaybeTemplate->getAs<RecordType>()) {
Douglas Gregor2943aed2009-03-03 04:44:36 +00003889 if (ClassTemplateSpecializationDecl *ClassTemplateSpec
Douglas Gregord475b8d2009-03-25 21:17:03 +00003890 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
Douglas Gregor972e6ce2009-10-27 06:26:26 +00003891 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared)
3892 return InstantiateClassTemplateSpecialization(Loc, ClassTemplateSpec,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00003893 TSK_ImplicitInstantiation,
Douglas Gregor5842ba92009-08-24 15:23:48 +00003894 /*Complain=*/diag != 0);
Mike Stump1eb44332009-09-09 15:08:12 +00003895 } else if (CXXRecordDecl *Rec
Douglas Gregord475b8d2009-03-25 21:17:03 +00003896 = dyn_cast<CXXRecordDecl>(Record->getDecl())) {
3897 if (CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass()) {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003898 MemberSpecializationInfo *MSInfo = Rec->getMemberSpecializationInfo();
3899 assert(MSInfo && "Missing member specialization information?");
Douglas Gregor357bbd02009-08-28 20:50:45 +00003900 // This record was instantiated from a class within a template.
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003901 if (MSInfo->getTemplateSpecializationKind()
Douglas Gregor972e6ce2009-10-27 06:26:26 +00003902 != TSK_ExplicitSpecialization)
Douglas Gregorf6b11852009-10-08 15:14:33 +00003903 return InstantiateClass(Loc, Rec, Pattern,
3904 getTemplateInstantiationArgs(Rec),
3905 TSK_ImplicitInstantiation,
3906 /*Complain=*/diag != 0);
Douglas Gregord475b8d2009-03-25 21:17:03 +00003907 }
3908 }
3909 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00003910
Douglas Gregor5842ba92009-08-24 15:23:48 +00003911 if (diag == 0)
3912 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003913
John McCall916c8702010-11-16 01:44:35 +00003914 const TagType *Tag = T->getAs<TagType>();
Rafael Espindola01620702010-03-21 22:56:43 +00003915
3916 // Avoid diagnosing invalid decls as incomplete.
3917 if (Tag && Tag->getDecl()->isInvalidDecl())
3918 return true;
3919
John McCall916c8702010-11-16 01:44:35 +00003920 // Give the external AST source a chance to complete the type.
3921 if (Tag && Tag->getDecl()->hasExternalLexicalStorage()) {
3922 Context.getExternalSource()->CompleteType(Tag->getDecl());
3923 if (!Tag->isIncompleteType())
3924 return false;
3925 }
3926
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003927 // We have an incomplete type. Produce a diagnostic.
Anders Carlsson91a0cc92009-08-26 22:33:56 +00003928 Diag(Loc, PD) << T;
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003929
Anders Carlsson8c8d9192009-10-09 23:51:55 +00003930 // If we have a note, produce it.
3931 if (!Note.first.isInvalid())
3932 Diag(Note.first, Note.second);
3933
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003934 // If the type was a forward declaration of a class/struct/union
Rafael Espindola01620702010-03-21 22:56:43 +00003935 // type, produce a note.
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003936 if (Tag && !Tag->getDecl()->isInvalidDecl())
Mike Stump1eb44332009-09-09 15:08:12 +00003937 Diag(Tag->getDecl()->getLocation(),
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003938 Tag->isBeingDefined() ? diag::note_type_being_defined
3939 : diag::note_forward_declaration)
3940 << QualType(Tag, 0);
3941
3942 return true;
3943}
Douglas Gregore6258932009-03-19 00:39:20 +00003944
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003945bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
3946 const PartialDiagnostic &PD) {
3947 return RequireCompleteType(Loc, T, PD,
3948 std::make_pair(SourceLocation(), PDiag(0)));
3949}
3950
3951bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
3952 unsigned DiagID) {
3953 return RequireCompleteType(Loc, T, PDiag(DiagID),
3954 std::make_pair(SourceLocation(), PDiag(0)));
3955}
3956
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003957/// \brief Retrieve a version of the type 'T' that is elaborated by Keyword
3958/// and qualified by the nested-name-specifier contained in SS.
3959QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword,
3960 const CXXScopeSpec &SS, QualType T) {
3961 if (T.isNull())
Douglas Gregore6258932009-03-19 00:39:20 +00003962 return T;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003963 NestedNameSpecifier *NNS;
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00003964 if (SS.isValid())
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003965 NNS = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3966 else {
3967 if (Keyword == ETK_None)
3968 return T;
3969 NNS = 0;
3970 }
3971 return Context.getElaboratedType(Keyword, NNS, T);
Douglas Gregore6258932009-03-19 00:39:20 +00003972}
Anders Carlssonaf017e62009-06-29 22:58:55 +00003973
John McCall2a984ca2010-10-12 00:20:44 +00003974QualType Sema::BuildTypeofExprType(Expr *E, SourceLocation Loc) {
John McCallfb8721c2011-04-10 19:13:55 +00003975 ExprResult ER = CheckPlaceholderExpr(E);
John McCall2a984ca2010-10-12 00:20:44 +00003976 if (ER.isInvalid()) return QualType();
3977 E = ER.take();
3978
Fariborz Jahanian2b1d51b2010-10-05 23:24:00 +00003979 if (!E->isTypeDependent()) {
3980 QualType T = E->getType();
Fariborz Jahanianaca7f7b2010-10-06 00:23:25 +00003981 if (const TagType *TT = T->getAs<TagType>())
3982 DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc());
Fariborz Jahanian2b1d51b2010-10-05 23:24:00 +00003983 }
Anders Carlssonaf017e62009-06-29 22:58:55 +00003984 return Context.getTypeOfExprType(E);
3985}
3986
John McCall2a984ca2010-10-12 00:20:44 +00003987QualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc) {
John McCallfb8721c2011-04-10 19:13:55 +00003988 ExprResult ER = CheckPlaceholderExpr(E);
John McCall2a984ca2010-10-12 00:20:44 +00003989 if (ER.isInvalid()) return QualType();
3990 E = ER.take();
Douglas Gregor4b52e252009-12-21 23:17:24 +00003991
Anders Carlssonaf017e62009-06-29 22:58:55 +00003992 return Context.getDecltypeType(E);
3993}
Sean Huntca63c202011-05-24 22:41:36 +00003994
3995QualType Sema::BuildUnaryTransformType(QualType BaseType,
3996 UnaryTransformType::UTTKind UKind,
3997 SourceLocation Loc) {
3998 switch (UKind) {
3999 case UnaryTransformType::EnumUnderlyingType:
4000 if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) {
4001 Diag(Loc, diag::err_only_enums_have_underlying_types);
4002 return QualType();
4003 } else {
4004 QualType Underlying = BaseType;
4005 if (!BaseType->isDependentType()) {
4006 EnumDecl *ED = BaseType->getAs<EnumType>()->getDecl();
4007 assert(ED && "EnumType has no EnumDecl");
4008 DiagnoseUseOfDecl(ED, Loc);
4009 Underlying = ED->getIntegerType();
4010 }
4011 assert(!Underlying.isNull());
4012 return Context.getUnaryTransformType(BaseType, Underlying,
4013 UnaryTransformType::EnumUnderlyingType);
4014 }
4015 }
4016 llvm_unreachable("unknown unary transform type");
4017}