blob: 6ea3f4827a1b8825b219a00e20753118a53c3128 [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 Gregor43f51032011-10-19 06:04:55 +0000558 /*const qualifier*/SourceLocation(),
559 /*volatile qualifier*/SourceLocation(),
Douglas Gregor90ebed02011-07-13 21:47:47 +0000560 /*mutable qualifier*/SourceLocation(),
Sebastian Redl6e5d3192011-03-05 22:42:13 +0000561 /*EH*/ EST_None, SourceLocation(), 0, 0, 0, 0,
John McCall711c52b2011-01-05 12:14:39 +0000562 /*parens*/ loc, loc,
563 declarator));
564
565 // For consistency, make sure the state still has us as processing
566 // the decl spec.
567 assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1);
568 state.setCurrentChunkIndex(declarator.getNumTypeObjects());
John McCall04a67a62010-02-05 21:31:56 +0000569}
570
Douglas Gregor930d8b52009-01-30 22:09:00 +0000571/// \brief Convert the specified declspec to the appropriate type
572/// object.
Chris Lattner5db2bb12009-10-25 18:21:37 +0000573/// \param D the declarator containing the declaration specifier.
Chris Lattner5153ee62009-04-25 08:47:54 +0000574/// \returns The type described by the declaration specifiers. This function
575/// never returns null.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +0000576static QualType ConvertDeclSpecToType(TypeProcessingState &state) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000577 // FIXME: Should move the logic from DeclSpec::Finish to here for validity
578 // checking.
John McCall711c52b2011-01-05 12:14:39 +0000579
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +0000580 Sema &S = state.getSema();
John McCall711c52b2011-01-05 12:14:39 +0000581 Declarator &declarator = state.getDeclarator();
582 const DeclSpec &DS = declarator.getDeclSpec();
583 SourceLocation DeclLoc = declarator.getIdentifierLoc();
Chris Lattner5db2bb12009-10-25 18:21:37 +0000584 if (DeclLoc.isInvalid())
585 DeclLoc = DS.getSourceRange().getBegin();
Chris Lattner1564e392009-10-25 18:07:27 +0000586
John McCall711c52b2011-01-05 12:14:39 +0000587 ASTContext &Context = S.Context;
Mike Stump1eb44332009-09-09 15:08:12 +0000588
Chris Lattner5db2bb12009-10-25 18:21:37 +0000589 QualType Result;
Reid Spencer5f016e22007-07-11 17:01:13 +0000590 switch (DS.getTypeSpecType()) {
Chris Lattner96b77fc2008-04-02 06:50:17 +0000591 case DeclSpec::TST_void:
592 Result = Context.VoidTy;
593 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000594 case DeclSpec::TST_char:
595 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
Chris Lattnerfab5b452008-02-20 23:53:49 +0000596 Result = Context.CharTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000597 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed)
Chris Lattnerfab5b452008-02-20 23:53:49 +0000598 Result = Context.SignedCharTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000599 else {
600 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
601 "Unknown TSS value");
Chris Lattnerfab5b452008-02-20 23:53:49 +0000602 Result = Context.UnsignedCharTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000603 }
Chris Lattner958858e2008-02-20 21:40:32 +0000604 break;
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000605 case DeclSpec::TST_wchar:
606 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
607 Result = Context.WCharTy;
608 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) {
John McCall711c52b2011-01-05 12:14:39 +0000609 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000610 << DS.getSpecifierName(DS.getTypeSpecType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000611 Result = Context.getSignedWCharType();
612 } else {
613 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
614 "Unknown TSS value");
John McCall711c52b2011-01-05 12:14:39 +0000615 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000616 << DS.getSpecifierName(DS.getTypeSpecType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000617 Result = Context.getUnsignedWCharType();
618 }
619 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000620 case DeclSpec::TST_char16:
621 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
622 "Unknown TSS value");
623 Result = Context.Char16Ty;
624 break;
625 case DeclSpec::TST_char32:
626 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
627 "Unknown TSS value");
628 Result = Context.Char32Ty;
629 break;
Chris Lattnerd658b562008-04-05 06:32:51 +0000630 case DeclSpec::TST_unspecified:
Chris Lattner62f5f7f2008-07-26 00:46:50 +0000631 // "<proto1,proto2>" is an objc qualified ID with a missing id.
Chris Lattner097e9162008-10-20 02:01:50 +0000632 if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) {
John McCallc12c5bb2010-05-15 11:32:37 +0000633 Result = Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
634 (ObjCProtocolDecl**)PQ,
635 DS.getNumProtocolQualifiers());
636 Result = Context.getObjCObjectPointerType(Result);
Chris Lattner62f5f7f2008-07-26 00:46:50 +0000637 break;
638 }
Chris Lattner5db2bb12009-10-25 18:21:37 +0000639
640 // If this is a missing declspec in a block literal return context, then it
641 // is inferred from the return statements inside the block.
John McCall711c52b2011-01-05 12:14:39 +0000642 if (isOmittedBlockReturnType(declarator)) {
Chris Lattner5db2bb12009-10-25 18:21:37 +0000643 Result = Context.DependentTy;
644 break;
645 }
Mike Stump1eb44332009-09-09 15:08:12 +0000646
Chris Lattnerd658b562008-04-05 06:32:51 +0000647 // Unspecified typespec defaults to int in C90. However, the C90 grammar
648 // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
649 // type-qualifier, or storage-class-specifier. If not, emit an extwarn.
650 // Note that the one exception to this is function definitions, which are
651 // allowed to be completely missing a declspec. This is handled in the
652 // parser already though by it pretending to have seen an 'int' in this
653 // case.
John McCall711c52b2011-01-05 12:14:39 +0000654 if (S.getLangOptions().ImplicitInt) {
Chris Lattner35d276f2009-02-27 18:53:28 +0000655 // In C89 mode, we only warn if there is a completely missing declspec
656 // when one is not allowed.
Chris Lattner3f84ad22009-04-22 05:27:59 +0000657 if (DS.isEmpty()) {
John McCall711c52b2011-01-05 12:14:39 +0000658 S.Diag(DeclLoc, diag::ext_missing_declspec)
Chris Lattner3f84ad22009-04-22 05:27:59 +0000659 << DS.getSourceRange()
Douglas Gregor849b2432010-03-31 17:46:05 +0000660 << FixItHint::CreateInsertion(DS.getSourceRange().getBegin(), "int");
Chris Lattner3f84ad22009-04-22 05:27:59 +0000661 }
Douglas Gregor4310f4e2009-02-16 22:38:20 +0000662 } else if (!DS.hasTypeSpecifier()) {
Chris Lattnerd658b562008-04-05 06:32:51 +0000663 // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says:
664 // "At least one type specifier shall be given in the declaration
665 // specifiers in each declaration, and in the specifier-qualifier list in
666 // each struct declaration and type name."
Douglas Gregor4310f4e2009-02-16 22:38:20 +0000667 // FIXME: Does Microsoft really have the implicit int extension in C++?
John McCall711c52b2011-01-05 12:14:39 +0000668 if (S.getLangOptions().CPlusPlus &&
Francois Pichet62ec1f22011-09-17 17:15:52 +0000669 !S.getLangOptions().MicrosoftExt) {
John McCall711c52b2011-01-05 12:14:39 +0000670 S.Diag(DeclLoc, diag::err_missing_type_specifier)
Chris Lattner3f84ad22009-04-22 05:27:59 +0000671 << DS.getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000672
Chris Lattnerb78d8332009-06-26 04:45:06 +0000673 // When this occurs in C++ code, often something is very broken with the
674 // value being declared, poison it as invalid so we don't get chains of
675 // errors.
John McCall711c52b2011-01-05 12:14:39 +0000676 declarator.setInvalidType(true);
Chris Lattnerb78d8332009-06-26 04:45:06 +0000677 } else {
John McCall711c52b2011-01-05 12:14:39 +0000678 S.Diag(DeclLoc, diag::ext_missing_type_specifier)
Chris Lattner3f84ad22009-04-22 05:27:59 +0000679 << DS.getSourceRange();
Chris Lattnerb78d8332009-06-26 04:45:06 +0000680 }
Chris Lattnerd658b562008-04-05 06:32:51 +0000681 }
Mike Stump1eb44332009-09-09 15:08:12 +0000682
683 // FALL THROUGH.
Chris Lattner3cbc38b2007-08-21 17:02:28 +0000684 case DeclSpec::TST_int: {
Reid Spencer5f016e22007-07-11 17:01:13 +0000685 if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) {
686 switch (DS.getTypeSpecWidth()) {
Chris Lattnerfab5b452008-02-20 23:53:49 +0000687 case DeclSpec::TSW_unspecified: Result = Context.IntTy; break;
688 case DeclSpec::TSW_short: Result = Context.ShortTy; break;
689 case DeclSpec::TSW_long: Result = Context.LongTy; break;
Chris Lattner311157f2009-10-25 18:25:04 +0000690 case DeclSpec::TSW_longlong:
691 Result = Context.LongLongTy;
692
693 // long long is a C99 feature.
Richard Smithebaf0e62011-10-18 20:49:44 +0000694 if (!S.getLangOptions().C99)
695 S.Diag(DS.getTypeSpecWidthLoc(),
696 S.getLangOptions().CPlusPlus0x ?
697 diag::warn_cxx98_compat_longlong : diag::ext_longlong);
Chris Lattner311157f2009-10-25 18:25:04 +0000698 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000699 }
700 } else {
701 switch (DS.getTypeSpecWidth()) {
Chris Lattnerfab5b452008-02-20 23:53:49 +0000702 case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break;
703 case DeclSpec::TSW_short: Result = Context.UnsignedShortTy; break;
704 case DeclSpec::TSW_long: Result = Context.UnsignedLongTy; break;
Chris Lattner311157f2009-10-25 18:25:04 +0000705 case DeclSpec::TSW_longlong:
706 Result = Context.UnsignedLongLongTy;
707
708 // long long is a C99 feature.
Richard Smithebaf0e62011-10-18 20:49:44 +0000709 if (!S.getLangOptions().C99)
710 S.Diag(DS.getTypeSpecWidthLoc(),
711 S.getLangOptions().CPlusPlus0x ?
712 diag::warn_cxx98_compat_longlong : diag::ext_longlong);
Chris Lattner311157f2009-10-25 18:25:04 +0000713 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000714 }
715 }
Chris Lattner958858e2008-02-20 21:40:32 +0000716 break;
Chris Lattner3cbc38b2007-08-21 17:02:28 +0000717 }
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000718 case DeclSpec::TST_half: Result = Context.HalfTy; break;
Chris Lattnerfab5b452008-02-20 23:53:49 +0000719 case DeclSpec::TST_float: Result = Context.FloatTy; break;
Chris Lattner958858e2008-02-20 21:40:32 +0000720 case DeclSpec::TST_double:
721 if (DS.getTypeSpecWidth() == DeclSpec::TSW_long)
Chris Lattnerfab5b452008-02-20 23:53:49 +0000722 Result = Context.LongDoubleTy;
Chris Lattner958858e2008-02-20 21:40:32 +0000723 else
Chris Lattnerfab5b452008-02-20 23:53:49 +0000724 Result = Context.DoubleTy;
Peter Collingbourne39d3e7a2011-02-15 19:46:23 +0000725
726 if (S.getLangOptions().OpenCL && !S.getOpenCLOptions().cl_khr_fp64) {
727 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_double_requires_fp64);
728 declarator.setInvalidType(true);
729 }
Chris Lattner958858e2008-02-20 21:40:32 +0000730 break;
Chris Lattnerfab5b452008-02-20 23:53:49 +0000731 case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool
Reid Spencer5f016e22007-07-11 17:01:13 +0000732 case DeclSpec::TST_decimal32: // _Decimal32
733 case DeclSpec::TST_decimal64: // _Decimal64
734 case DeclSpec::TST_decimal128: // _Decimal128
John McCall711c52b2011-01-05 12:14:39 +0000735 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
Chris Lattner8f12f652009-05-13 05:02:08 +0000736 Result = Context.IntTy;
John McCall711c52b2011-01-05 12:14:39 +0000737 declarator.setInvalidType(true);
Chris Lattner8f12f652009-05-13 05:02:08 +0000738 break;
Chris Lattner99dc9142008-04-13 18:59:07 +0000739 case DeclSpec::TST_class:
Reid Spencer5f016e22007-07-11 17:01:13 +0000740 case DeclSpec::TST_enum:
741 case DeclSpec::TST_union:
742 case DeclSpec::TST_struct: {
John McCallb3d87482010-08-24 05:47:05 +0000743 TypeDecl *D = dyn_cast_or_null<TypeDecl>(DS.getRepAsDecl());
John McCall6e247262009-10-10 05:48:19 +0000744 if (!D) {
745 // This can happen in C++ with ambiguous lookups.
746 Result = Context.IntTy;
John McCall711c52b2011-01-05 12:14:39 +0000747 declarator.setInvalidType(true);
John McCall6e247262009-10-10 05:48:19 +0000748 break;
749 }
750
Chris Lattnera64ef0a2009-10-25 22:09:09 +0000751 // If the type is deprecated or unavailable, diagnose it.
Abramo Bagnara0daaf322011-03-16 20:16:18 +0000752 S.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeNameLoc());
Chris Lattnera64ef0a2009-10-25 22:09:09 +0000753
Reid Spencer5f016e22007-07-11 17:01:13 +0000754 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
Chris Lattnera64ef0a2009-10-25 22:09:09 +0000755 DS.getTypeSpecSign() == 0 && "No qualifiers on tag names!");
756
Reid Spencer5f016e22007-07-11 17:01:13 +0000757 // TypeQuals handled by caller.
Chris Lattnera64ef0a2009-10-25 22:09:09 +0000758 Result = Context.getTypeDeclType(D);
John McCall2191b202009-09-05 06:31:47 +0000759
Abramo Bagnara0daaf322011-03-16 20:16:18 +0000760 // In both C and C++, make an ElaboratedType.
761 ElaboratedTypeKeyword Keyword
762 = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType());
763 Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result);
764
Chris Lattner5153ee62009-04-25 08:47:54 +0000765 if (D->isInvalidDecl())
John McCall711c52b2011-01-05 12:14:39 +0000766 declarator.setInvalidType(true);
Chris Lattner958858e2008-02-20 21:40:32 +0000767 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000768 }
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000769 case DeclSpec::TST_typename: {
Reid Spencer5f016e22007-07-11 17:01:13 +0000770 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
771 DS.getTypeSpecSign() == 0 &&
772 "Can't handle qualifiers on typedef names yet!");
John McCall711c52b2011-01-05 12:14:39 +0000773 Result = S.GetTypeFromParser(DS.getRepAsType());
John McCall27940d22010-07-30 05:17:22 +0000774 if (Result.isNull())
John McCall711c52b2011-01-05 12:14:39 +0000775 declarator.setInvalidType(true);
John McCall27940d22010-07-30 05:17:22 +0000776 else if (DeclSpec::ProtocolQualifierListTy PQ
777 = DS.getProtocolQualifiers()) {
John McCallc12c5bb2010-05-15 11:32:37 +0000778 if (const ObjCObjectType *ObjT = Result->getAs<ObjCObjectType>()) {
779 // Silently drop any existing protocol qualifiers.
780 // TODO: determine whether that's the right thing to do.
781 if (ObjT->getNumProtocols())
782 Result = ObjT->getBaseType();
783
784 if (DS.getNumProtocolQualifiers())
785 Result = Context.getObjCObjectType(Result,
786 (ObjCProtocolDecl**) PQ,
787 DS.getNumProtocolQualifiers());
788 } else if (Result->isObjCIdType()) {
Chris Lattnerae4da612008-07-26 01:53:50 +0000789 // id<protocol-list>
John McCallc12c5bb2010-05-15 11:32:37 +0000790 Result = Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
791 (ObjCProtocolDecl**) PQ,
792 DS.getNumProtocolQualifiers());
793 Result = Context.getObjCObjectPointerType(Result);
794 } else if (Result->isObjCClassType()) {
Steve Naroff4262a072009-02-23 18:53:24 +0000795 // Class<protocol-list>
John McCallc12c5bb2010-05-15 11:32:37 +0000796 Result = Context.getObjCObjectType(Context.ObjCBuiltinClassTy,
797 (ObjCProtocolDecl**) PQ,
798 DS.getNumProtocolQualifiers());
799 Result = Context.getObjCObjectPointerType(Result);
Chris Lattner3f84ad22009-04-22 05:27:59 +0000800 } else {
John McCall711c52b2011-01-05 12:14:39 +0000801 S.Diag(DeclLoc, diag::err_invalid_protocol_qualifiers)
Chris Lattner3f84ad22009-04-22 05:27:59 +0000802 << DS.getSourceRange();
John McCall711c52b2011-01-05 12:14:39 +0000803 declarator.setInvalidType(true);
Chris Lattner3f84ad22009-04-22 05:27:59 +0000804 }
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000805 }
Mike Stump1eb44332009-09-09 15:08:12 +0000806
Reid Spencer5f016e22007-07-11 17:01:13 +0000807 // TypeQuals handled by caller.
Chris Lattner958858e2008-02-20 21:40:32 +0000808 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000809 }
Chris Lattner958858e2008-02-20 21:40:32 +0000810 case DeclSpec::TST_typeofType:
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000811 // FIXME: Preserve type source info.
John McCall711c52b2011-01-05 12:14:39 +0000812 Result = S.GetTypeFromParser(DS.getRepAsType());
Chris Lattner958858e2008-02-20 21:40:32 +0000813 assert(!Result.isNull() && "Didn't get a type for typeof?");
Fariborz Jahanian730e1752010-10-06 17:00:02 +0000814 if (!Result->isDependentType())
815 if (const TagType *TT = Result->getAs<TagType>())
John McCall711c52b2011-01-05 12:14:39 +0000816 S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc());
Steve Naroffd1861fd2007-07-31 12:34:36 +0000817 // TypeQuals handled by caller.
Chris Lattnerfab5b452008-02-20 23:53:49 +0000818 Result = Context.getTypeOfType(Result);
Chris Lattner958858e2008-02-20 21:40:32 +0000819 break;
Steve Naroffd1861fd2007-07-31 12:34:36 +0000820 case DeclSpec::TST_typeofExpr: {
John McCallb3d87482010-08-24 05:47:05 +0000821 Expr *E = DS.getRepAsExpr();
Steve Naroffd1861fd2007-07-31 12:34:36 +0000822 assert(E && "Didn't get an expression for typeof?");
823 // TypeQuals handled by caller.
John McCall711c52b2011-01-05 12:14:39 +0000824 Result = S.BuildTypeofExprType(E, DS.getTypeSpecTypeLoc());
Douglas Gregor4b52e252009-12-21 23:17:24 +0000825 if (Result.isNull()) {
826 Result = Context.IntTy;
John McCall711c52b2011-01-05 12:14:39 +0000827 declarator.setInvalidType(true);
Douglas Gregor4b52e252009-12-21 23:17:24 +0000828 }
Chris Lattner958858e2008-02-20 21:40:32 +0000829 break;
Steve Naroffd1861fd2007-07-31 12:34:36 +0000830 }
Anders Carlsson6fd634f2009-06-24 17:47:40 +0000831 case DeclSpec::TST_decltype: {
John McCallb3d87482010-08-24 05:47:05 +0000832 Expr *E = DS.getRepAsExpr();
Anders Carlsson6fd634f2009-06-24 17:47:40 +0000833 assert(E && "Didn't get an expression for decltype?");
834 // TypeQuals handled by caller.
John McCall711c52b2011-01-05 12:14:39 +0000835 Result = S.BuildDecltypeType(E, DS.getTypeSpecTypeLoc());
Anders Carlssonaf017e62009-06-29 22:58:55 +0000836 if (Result.isNull()) {
837 Result = Context.IntTy;
John McCall711c52b2011-01-05 12:14:39 +0000838 declarator.setInvalidType(true);
Anders Carlssonaf017e62009-06-29 22:58:55 +0000839 }
Anders Carlsson6fd634f2009-06-24 17:47:40 +0000840 break;
841 }
Sean Huntca63c202011-05-24 22:41:36 +0000842 case DeclSpec::TST_underlyingType:
Sean Huntdb5d44b2011-05-19 05:37:45 +0000843 Result = S.GetTypeFromParser(DS.getRepAsType());
844 assert(!Result.isNull() && "Didn't get a type for __underlying_type?");
Sean Huntca63c202011-05-24 22:41:36 +0000845 Result = S.BuildUnaryTransformType(Result,
846 UnaryTransformType::EnumUnderlyingType,
847 DS.getTypeSpecTypeLoc());
848 if (Result.isNull()) {
849 Result = Context.IntTy;
850 declarator.setInvalidType(true);
Sean Huntdb5d44b2011-05-19 05:37:45 +0000851 }
852 break;
853
Anders Carlssone89d1592009-06-26 18:41:36 +0000854 case DeclSpec::TST_auto: {
855 // TypeQuals handled by caller.
Richard Smith34b41d92011-02-20 03:19:35 +0000856 Result = Context.getAutoType(QualType());
Anders Carlssone89d1592009-06-26 18:41:36 +0000857 break;
858 }
Mike Stump1eb44332009-09-09 15:08:12 +0000859
John McCalla5fc4722011-04-09 22:50:59 +0000860 case DeclSpec::TST_unknown_anytype:
861 Result = Context.UnknownAnyTy;
862 break;
863
Eli Friedmanb001de72011-10-06 23:00:33 +0000864 case DeclSpec::TST_atomic:
865 Result = S.GetTypeFromParser(DS.getRepAsType());
866 assert(!Result.isNull() && "Didn't get a type for _Atomic?");
867 Result = S.BuildAtomicType(Result, DS.getTypeSpecTypeLoc());
868 if (Result.isNull()) {
869 Result = Context.IntTy;
870 declarator.setInvalidType(true);
871 }
872 break;
873
Douglas Gregor809070a2009-02-18 17:45:20 +0000874 case DeclSpec::TST_error:
Chris Lattner5153ee62009-04-25 08:47:54 +0000875 Result = Context.IntTy;
John McCall711c52b2011-01-05 12:14:39 +0000876 declarator.setInvalidType(true);
Chris Lattner5153ee62009-04-25 08:47:54 +0000877 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000878 }
Mike Stump1eb44332009-09-09 15:08:12 +0000879
Chris Lattner958858e2008-02-20 21:40:32 +0000880 // Handle complex types.
Douglas Gregorf244cd72009-02-14 21:06:05 +0000881 if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
John McCall711c52b2011-01-05 12:14:39 +0000882 if (S.getLangOptions().Freestanding)
883 S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
Chris Lattnerfab5b452008-02-20 23:53:49 +0000884 Result = Context.getComplexType(Result);
John Thompson82287d12010-02-05 00:12:22 +0000885 } else if (DS.isTypeAltiVecVector()) {
886 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result));
887 assert(typeSize > 0 && "type size for vector must be greater than 0 bits");
Bob Wilsone86d78c2010-11-10 21:56:12 +0000888 VectorType::VectorKind VecKind = VectorType::AltiVecVector;
Chris Lattner788b0fd2010-06-23 06:00:24 +0000889 if (DS.isTypeAltiVecPixel())
Bob Wilsone86d78c2010-11-10 21:56:12 +0000890 VecKind = VectorType::AltiVecPixel;
Chris Lattner788b0fd2010-06-23 06:00:24 +0000891 else if (DS.isTypeAltiVecBool())
Bob Wilsone86d78c2010-11-10 21:56:12 +0000892 VecKind = VectorType::AltiVecBool;
893 Result = Context.getVectorType(Result, 128/typeSize, VecKind);
Douglas Gregorf244cd72009-02-14 21:06:05 +0000894 }
Mike Stump1eb44332009-09-09 15:08:12 +0000895
Argyrios Kyrtzidis47423bd2010-09-23 09:40:31 +0000896 // FIXME: Imaginary.
897 if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary)
John McCall711c52b2011-01-05 12:14:39 +0000898 S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported);
Mike Stump1eb44332009-09-09 15:08:12 +0000899
John McCall711c52b2011-01-05 12:14:39 +0000900 // Before we process any type attributes, synthesize a block literal
901 // function declarator if necessary.
902 if (declarator.getContext() == Declarator::BlockLiteralContext)
903 maybeSynthesizeBlockSignature(state, Result);
904
905 // Apply any type attributes from the decl spec. This may cause the
906 // list of type attributes to be temporarily saved while the type
907 // attributes are pushed around.
908 if (AttributeList *attrs = DS.getAttributes().getList())
909 processTypeAttrs(state, Result, true, attrs);
Mike Stump1eb44332009-09-09 15:08:12 +0000910
Chris Lattner96b77fc2008-04-02 06:50:17 +0000911 // Apply const/volatile/restrict qualifiers to T.
912 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
913
914 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
915 // or incomplete types shall not be restrict-qualified." C++ also allows
916 // restrict-qualified references.
John McCall0953e762009-09-24 19:53:00 +0000917 if (TypeQuals & DeclSpec::TQ_restrict) {
Fariborz Jahanian2b5ff1a2009-12-07 18:08:58 +0000918 if (Result->isAnyPointerType() || Result->isReferenceType()) {
919 QualType EltTy;
920 if (Result->isObjCObjectPointerType())
921 EltTy = Result;
922 else
923 EltTy = Result->isPointerType() ?
924 Result->getAs<PointerType>()->getPointeeType() :
925 Result->getAs<ReferenceType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +0000926
Douglas Gregorbad0e652009-03-24 20:32:41 +0000927 // If we have a pointer or reference, the pointee must have an object
Chris Lattnerbdcd6372008-04-02 17:35:06 +0000928 // incomplete type.
929 if (!EltTy->isIncompleteOrObjectType()) {
John McCall711c52b2011-01-05 12:14:39 +0000930 S.Diag(DS.getRestrictSpecLoc(),
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000931 diag::err_typecheck_invalid_restrict_invalid_pointee)
Chris Lattnerd1625842008-11-24 06:25:27 +0000932 << EltTy << DS.getSourceRange();
John McCall0953e762009-09-24 19:53:00 +0000933 TypeQuals &= ~DeclSpec::TQ_restrict; // Remove the restrict qualifier.
Chris Lattnerbdcd6372008-04-02 17:35:06 +0000934 }
935 } else {
John McCall711c52b2011-01-05 12:14:39 +0000936 S.Diag(DS.getRestrictSpecLoc(),
937 diag::err_typecheck_invalid_restrict_not_pointer)
Chris Lattnerd1625842008-11-24 06:25:27 +0000938 << Result << DS.getSourceRange();
John McCall0953e762009-09-24 19:53:00 +0000939 TypeQuals &= ~DeclSpec::TQ_restrict; // Remove the restrict qualifier.
Chris Lattner96b77fc2008-04-02 06:50:17 +0000940 }
Chris Lattner96b77fc2008-04-02 06:50:17 +0000941 }
Mike Stump1eb44332009-09-09 15:08:12 +0000942
Chris Lattner96b77fc2008-04-02 06:50:17 +0000943 // Warn about CV qualifiers on functions: C99 6.7.3p8: "If the specification
944 // of a function type includes any type qualifiers, the behavior is
945 // undefined."
946 if (Result->isFunctionType() && TypeQuals) {
947 // Get some location to point at, either the C or V location.
948 SourceLocation Loc;
John McCall0953e762009-09-24 19:53:00 +0000949 if (TypeQuals & DeclSpec::TQ_const)
Chris Lattner96b77fc2008-04-02 06:50:17 +0000950 Loc = DS.getConstSpecLoc();
John McCall0953e762009-09-24 19:53:00 +0000951 else if (TypeQuals & DeclSpec::TQ_volatile)
Chris Lattner96b77fc2008-04-02 06:50:17 +0000952 Loc = DS.getVolatileSpecLoc();
John McCall0953e762009-09-24 19:53:00 +0000953 else {
954 assert((TypeQuals & DeclSpec::TQ_restrict) &&
955 "Has CVR quals but not C, V, or R?");
956 Loc = DS.getRestrictSpecLoc();
Chris Lattner96b77fc2008-04-02 06:50:17 +0000957 }
John McCall711c52b2011-01-05 12:14:39 +0000958 S.Diag(Loc, diag::warn_typecheck_function_qualifiers)
Chris Lattnerd1625842008-11-24 06:25:27 +0000959 << Result << DS.getSourceRange();
Chris Lattner96b77fc2008-04-02 06:50:17 +0000960 }
Mike Stump1eb44332009-09-09 15:08:12 +0000961
Douglas Gregorf1f9b4e2008-11-03 15:51:28 +0000962 // C++ [dcl.ref]p1:
963 // Cv-qualified references are ill-formed except when the
964 // cv-qualifiers are introduced through the use of a typedef
965 // (7.1.3) or of a template type argument (14.3), in which
966 // case the cv-qualifiers are ignored.
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000967 // FIXME: Shouldn't we be checking SCS_typedef here?
968 if (DS.getTypeSpecType() == DeclSpec::TST_typename &&
Douglas Gregorf1f9b4e2008-11-03 15:51:28 +0000969 TypeQuals && Result->isReferenceType()) {
John McCall0953e762009-09-24 19:53:00 +0000970 TypeQuals &= ~DeclSpec::TQ_const;
971 TypeQuals &= ~DeclSpec::TQ_volatile;
Mike Stump1eb44332009-09-09 15:08:12 +0000972 }
973
John McCall0953e762009-09-24 19:53:00 +0000974 Qualifiers Quals = Qualifiers::fromCVRMask(TypeQuals);
975 Result = Context.getQualifiedType(Result, Quals);
Chris Lattner96b77fc2008-04-02 06:50:17 +0000976 }
John McCall0953e762009-09-24 19:53:00 +0000977
Chris Lattnerf1d705c2008-02-21 01:07:18 +0000978 return Result;
979}
980
Douglas Gregorcd281c32009-02-28 00:25:32 +0000981static std::string getPrintableNameForEntity(DeclarationName Entity) {
982 if (Entity)
983 return Entity.getAsString();
Mike Stump1eb44332009-09-09 15:08:12 +0000984
Douglas Gregorcd281c32009-02-28 00:25:32 +0000985 return "type name";
986}
987
John McCall28654742010-06-05 06:41:15 +0000988QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
989 Qualifiers Qs) {
990 // Enforce C99 6.7.3p2: "Types other than pointer types derived from
991 // object or incomplete types shall not be restrict-qualified."
992 if (Qs.hasRestrict()) {
993 unsigned DiagID = 0;
994 QualType ProblemTy;
995
996 const Type *Ty = T->getCanonicalTypeInternal().getTypePtr();
997 if (const ReferenceType *RTy = dyn_cast<ReferenceType>(Ty)) {
998 if (!RTy->getPointeeType()->isIncompleteOrObjectType()) {
999 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1000 ProblemTy = T->getAs<ReferenceType>()->getPointeeType();
1001 }
1002 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
1003 if (!PTy->getPointeeType()->isIncompleteOrObjectType()) {
1004 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1005 ProblemTy = T->getAs<PointerType>()->getPointeeType();
1006 }
1007 } else if (const MemberPointerType *PTy = dyn_cast<MemberPointerType>(Ty)) {
1008 if (!PTy->getPointeeType()->isIncompleteOrObjectType()) {
1009 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1010 ProblemTy = T->getAs<PointerType>()->getPointeeType();
1011 }
1012 } else if (!Ty->isDependentType()) {
1013 // FIXME: this deserves a proper diagnostic
1014 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1015 ProblemTy = T;
1016 }
1017
1018 if (DiagID) {
1019 Diag(Loc, DiagID) << ProblemTy;
1020 Qs.removeRestrict();
1021 }
1022 }
1023
1024 return Context.getQualifiedType(T, Qs);
1025}
1026
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001027/// \brief Build a paren type including \p T.
1028QualType Sema::BuildParenType(QualType T) {
1029 return Context.getParenType(T);
1030}
1031
John McCallf85e1932011-06-15 23:02:42 +00001032/// Given that we're building a pointer or reference to the given
1033static QualType inferARCLifetimeForPointee(Sema &S, QualType type,
1034 SourceLocation loc,
1035 bool isReference) {
1036 // Bail out if retention is unrequired or already specified.
1037 if (!type->isObjCLifetimeType() ||
1038 type.getObjCLifetime() != Qualifiers::OCL_None)
1039 return type;
1040
1041 Qualifiers::ObjCLifetime implicitLifetime = Qualifiers::OCL_None;
1042
1043 // If the object type is const-qualified, we can safely use
1044 // __unsafe_unretained. This is safe (because there are no read
1045 // barriers), and it'll be safe to coerce anything but __weak* to
1046 // the resulting type.
1047 if (type.isConstQualified()) {
1048 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1049
1050 // Otherwise, check whether the static type does not require
1051 // retaining. This currently only triggers for Class (possibly
1052 // protocol-qualifed, and arrays thereof).
1053 } else if (type->isObjCARCImplicitlyUnretainedType()) {
1054 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1055
Argyrios Kyrtzidis5b76f372011-09-20 23:49:22 +00001056 // If we are in an unevaluated context, like sizeof, assume ExplicitNone and
1057 // don't give error.
1058 } else if (S.ExprEvalContexts.back().Context == Sema::Unevaluated) {
1059 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1060
John McCallf85e1932011-06-15 23:02:42 +00001061 // If that failed, give an error and recover using __autoreleasing.
1062 } else {
1063 // These types can show up in private ivars in system headers, so
1064 // we need this to not be an error in those cases. Instead we
1065 // want to delay.
1066 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
1067 S.DelayedDiagnostics.add(
1068 sema::DelayedDiagnostic::makeForbiddenType(loc,
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00001069 diag::err_arc_indirect_no_ownership, type, isReference));
John McCallf85e1932011-06-15 23:02:42 +00001070 } else {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00001071 S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference;
John McCallf85e1932011-06-15 23:02:42 +00001072 }
1073 implicitLifetime = Qualifiers::OCL_Autoreleasing;
1074 }
1075 assert(implicitLifetime && "didn't infer any lifetime!");
1076
1077 Qualifiers qs;
1078 qs.addObjCLifetime(implicitLifetime);
1079 return S.Context.getQualifiedType(type, qs);
1080}
1081
Douglas Gregorcd281c32009-02-28 00:25:32 +00001082/// \brief Build a pointer type.
1083///
1084/// \param T The type to which we'll be building a pointer.
1085///
Douglas Gregorcd281c32009-02-28 00:25:32 +00001086/// \param Loc The location of the entity whose type involves this
1087/// pointer type or, if there is no such entity, the location of the
1088/// type that will have pointer type.
1089///
1090/// \param Entity The name of the entity that involves the pointer
1091/// type, if known.
1092///
1093/// \returns A suitable pointer type, if there are no
1094/// errors. Otherwise, returns a NULL type.
John McCall28654742010-06-05 06:41:15 +00001095QualType Sema::BuildPointerType(QualType T,
Douglas Gregorcd281c32009-02-28 00:25:32 +00001096 SourceLocation Loc, DeclarationName Entity) {
1097 if (T->isReferenceType()) {
1098 // C++ 8.3.2p4: There shall be no ... pointers to references ...
1099 Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
John McCallac406052009-10-30 00:37:20 +00001100 << getPrintableNameForEntity(Entity) << T;
Douglas Gregorcd281c32009-02-28 00:25:32 +00001101 return QualType();
1102 }
1103
John McCallc12c5bb2010-05-15 11:32:37 +00001104 assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType");
Douglas Gregor92e986e2010-04-22 16:44:27 +00001105
John McCallf85e1932011-06-15 23:02:42 +00001106 // In ARC, it is forbidden to build pointers to unqualified pointers.
1107 if (getLangOptions().ObjCAutoRefCount)
1108 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false);
1109
Douglas Gregorcd281c32009-02-28 00:25:32 +00001110 // Build the pointer type.
John McCall28654742010-06-05 06:41:15 +00001111 return Context.getPointerType(T);
Douglas Gregorcd281c32009-02-28 00:25:32 +00001112}
1113
1114/// \brief Build a reference type.
1115///
1116/// \param T The type to which we'll be building a reference.
1117///
Douglas Gregorcd281c32009-02-28 00:25:32 +00001118/// \param Loc The location of the entity whose type involves this
1119/// reference type or, if there is no such entity, the location of the
1120/// type that will have reference type.
1121///
1122/// \param Entity The name of the entity that involves the reference
1123/// type, if known.
1124///
1125/// \returns A suitable reference type, if there are no
1126/// errors. Otherwise, returns a NULL type.
John McCall54e14c42009-10-22 22:37:11 +00001127QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue,
John McCall28654742010-06-05 06:41:15 +00001128 SourceLocation Loc,
John McCall54e14c42009-10-22 22:37:11 +00001129 DeclarationName Entity) {
Douglas Gregor9625e442011-05-21 22:16:50 +00001130 assert(Context.getCanonicalType(T) != Context.OverloadTy &&
1131 "Unresolved overloaded function type");
1132
Douglas Gregor69d83162011-01-20 16:08:06 +00001133 // C++0x [dcl.ref]p6:
1134 // If a typedef (7.1.3), a type template-parameter (14.3.1), or a
1135 // decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a
1136 // type T, an attempt to create the type "lvalue reference to cv TR" creates
1137 // the type "lvalue reference to T", while an attempt to create the type
1138 // "rvalue reference to cv TR" creates the type TR.
John McCall54e14c42009-10-22 22:37:11 +00001139 bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
1140
John McCall54e14c42009-10-22 22:37:11 +00001141 // C++ [dcl.ref]p4: There shall be no references to references.
1142 //
1143 // According to C++ DR 106, references to references are only
1144 // diagnosed when they are written directly (e.g., "int & &"),
1145 // but not when they happen via a typedef:
1146 //
1147 // typedef int& intref;
1148 // typedef intref& intref2;
1149 //
1150 // Parser::ParseDeclaratorInternal diagnoses the case where
1151 // references are written directly; here, we handle the
Douglas Gregor69d83162011-01-20 16:08:06 +00001152 // collapsing of references-to-references as described in C++0x.
1153 // DR 106 and 540 introduce reference-collapsing into C++98/03.
Douglas Gregorcd281c32009-02-28 00:25:32 +00001154
1155 // C++ [dcl.ref]p1:
Eli Friedman33a31382009-08-05 19:21:58 +00001156 // A declarator that specifies the type "reference to cv void"
Douglas Gregorcd281c32009-02-28 00:25:32 +00001157 // is ill-formed.
1158 if (T->isVoidType()) {
1159 Diag(Loc, diag::err_reference_to_void);
1160 return QualType();
1161 }
1162
John McCallf85e1932011-06-15 23:02:42 +00001163 // In ARC, it is forbidden to build references to unqualified pointers.
1164 if (getLangOptions().ObjCAutoRefCount)
1165 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true);
1166
Douglas Gregorcd281c32009-02-28 00:25:32 +00001167 // Handle restrict on references.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001168 if (LValueRef)
John McCall28654742010-06-05 06:41:15 +00001169 return Context.getLValueReferenceType(T, SpelledAsLValue);
1170 return Context.getRValueReferenceType(T);
Douglas Gregorcd281c32009-02-28 00:25:32 +00001171}
1172
Chris Lattnere1eed382011-06-14 06:38:10 +00001173/// Check whether the specified array size makes the array type a VLA. If so,
1174/// return true, if not, return the size of the array in SizeVal.
1175static bool isArraySizeVLA(Expr *ArraySize, llvm::APSInt &SizeVal, Sema &S) {
1176 // If the size is an ICE, it certainly isn't a VLA.
1177 if (ArraySize->isIntegerConstantExpr(SizeVal, S.Context))
1178 return false;
1179
1180 // If we're in a GNU mode (like gnu99, but not c99) accept any evaluatable
1181 // value as an extension.
1182 Expr::EvalResult Result;
Richard Smith51f47082011-10-29 00:50:52 +00001183 if (S.LangOpts.GNUMode && ArraySize->EvaluateAsRValue(Result, S.Context)) {
Chris Lattnere1eed382011-06-14 06:38:10 +00001184 if (!Result.hasSideEffects() && Result.Val.isInt()) {
1185 SizeVal = Result.Val.getInt();
1186 S.Diag(ArraySize->getLocStart(), diag::ext_vla_folded_to_constant);
1187 return false;
1188 }
1189 }
1190
1191 return true;
1192}
1193
1194
Douglas Gregorcd281c32009-02-28 00:25:32 +00001195/// \brief Build an array type.
1196///
1197/// \param T The type of each element in the array.
1198///
1199/// \param ASM C99 array size modifier (e.g., '*', 'static').
Mike Stump1eb44332009-09-09 15:08:12 +00001200///
1201/// \param ArraySize Expression describing the size of the array.
Douglas Gregorcd281c32009-02-28 00:25:32 +00001202///
Douglas Gregorcd281c32009-02-28 00:25:32 +00001203/// \param Loc The location of the entity whose type involves this
1204/// array type or, if there is no such entity, the location of the
1205/// type that will have array type.
1206///
1207/// \param Entity The name of the entity that involves the array
1208/// type, if known.
1209///
1210/// \returns A suitable array type, if there are no errors. Otherwise,
1211/// returns a NULL type.
1212QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1213 Expr *ArraySize, unsigned Quals,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001214 SourceRange Brackets, DeclarationName Entity) {
John McCall0953e762009-09-24 19:53:00 +00001215
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001216 SourceLocation Loc = Brackets.getBegin();
Sebastian Redl923d56d2009-11-05 15:52:31 +00001217 if (getLangOptions().CPlusPlus) {
Douglas Gregor138bb232010-04-27 19:38:14 +00001218 // C++ [dcl.array]p1:
1219 // T is called the array element type; this type shall not be a reference
1220 // type, the (possibly cv-qualified) type void, a function type or an
1221 // abstract class type.
1222 //
1223 // Note: function types are handled in the common path with C.
1224 if (T->isReferenceType()) {
1225 Diag(Loc, diag::err_illegal_decl_array_of_references)
1226 << getPrintableNameForEntity(Entity) << T;
1227 return QualType();
1228 }
1229
Sebastian Redl923d56d2009-11-05 15:52:31 +00001230 if (T->isVoidType()) {
1231 Diag(Loc, diag::err_illegal_decl_array_incomplete_type) << T;
1232 return QualType();
1233 }
Douglas Gregor138bb232010-04-27 19:38:14 +00001234
1235 if (RequireNonAbstractType(Brackets.getBegin(), T,
1236 diag::err_array_of_abstract_type))
1237 return QualType();
1238
Sebastian Redl923d56d2009-11-05 15:52:31 +00001239 } else {
Douglas Gregor138bb232010-04-27 19:38:14 +00001240 // C99 6.7.5.2p1: If the element type is an incomplete or function type,
1241 // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
Sebastian Redl923d56d2009-11-05 15:52:31 +00001242 if (RequireCompleteType(Loc, T,
1243 diag::err_illegal_decl_array_incomplete_type))
1244 return QualType();
1245 }
Douglas Gregorcd281c32009-02-28 00:25:32 +00001246
1247 if (T->isFunctionType()) {
1248 Diag(Loc, diag::err_illegal_decl_array_of_functions)
John McCallac406052009-10-30 00:37:20 +00001249 << getPrintableNameForEntity(Entity) << T;
Douglas Gregorcd281c32009-02-28 00:25:32 +00001250 return QualType();
1251 }
Mike Stump1eb44332009-09-09 15:08:12 +00001252
Richard Smith34b41d92011-02-20 03:19:35 +00001253 if (T->getContainedAutoType()) {
1254 Diag(Loc, diag::err_illegal_decl_array_of_auto)
1255 << getPrintableNameForEntity(Entity) << T;
Anders Carlssone7cf07d2009-06-26 19:33:28 +00001256 return QualType();
1257 }
Mike Stump1eb44332009-09-09 15:08:12 +00001258
Ted Kremenek6217b802009-07-29 21:53:49 +00001259 if (const RecordType *EltTy = T->getAs<RecordType>()) {
Douglas Gregorcd281c32009-02-28 00:25:32 +00001260 // If the element type is a struct or union that contains a variadic
1261 // array, accept it as a GNU extension: C99 6.7.2.1p2.
1262 if (EltTy->getDecl()->hasFlexibleArrayMember())
1263 Diag(Loc, diag::ext_flexible_array_in_array) << T;
John McCallc12c5bb2010-05-15 11:32:37 +00001264 } else if (T->isObjCObjectType()) {
Chris Lattnerc7c11b12009-04-27 01:55:56 +00001265 Diag(Loc, diag::err_objc_array_of_interfaces) << T;
1266 return QualType();
Douglas Gregorcd281c32009-02-28 00:25:32 +00001267 }
Mike Stump1eb44332009-09-09 15:08:12 +00001268
John McCall5e3c67b2010-12-15 04:42:30 +00001269 // Do lvalue-to-rvalue conversions on the array size expression.
John Wiegley429bb272011-04-08 18:41:53 +00001270 if (ArraySize && !ArraySize->isRValue()) {
1271 ExprResult Result = DefaultLvalueConversion(ArraySize);
1272 if (Result.isInvalid())
1273 return QualType();
1274
1275 ArraySize = Result.take();
1276 }
John McCall5e3c67b2010-12-15 04:42:30 +00001277
Douglas Gregorcd281c32009-02-28 00:25:32 +00001278 // C99 6.7.5.2p1: The size expression shall have integer type.
John McCall5e3c67b2010-12-15 04:42:30 +00001279 // TODO: in theory, if we were insane, we could allow contextual
1280 // conversions to integer type here.
Douglas Gregorcd281c32009-02-28 00:25:32 +00001281 if (ArraySize && !ArraySize->isTypeDependent() &&
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001282 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
Douglas Gregorcd281c32009-02-28 00:25:32 +00001283 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
1284 << ArraySize->getType() << ArraySize->getSourceRange();
Douglas Gregorcd281c32009-02-28 00:25:32 +00001285 return QualType();
1286 }
Douglas Gregor2767ce22010-08-18 00:39:00 +00001287 llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType()));
Douglas Gregorcd281c32009-02-28 00:25:32 +00001288 if (!ArraySize) {
Eli Friedmanf91f5c82009-04-26 21:57:51 +00001289 if (ASM == ArrayType::Star)
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001290 T = Context.getVariableArrayType(T, 0, ASM, Quals, Brackets);
Eli Friedmanf91f5c82009-04-26 21:57:51 +00001291 else
1292 T = Context.getIncompleteArrayType(T, ASM, Quals);
Douglas Gregorac06a0e2010-05-18 23:01:22 +00001293 } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) {
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001294 T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets);
Chris Lattnere1eed382011-06-14 06:38:10 +00001295 } else if (!T->isDependentType() && !T->isIncompleteType() &&
1296 !T->isConstantSizeType()) {
1297 // C99: an array with an element type that has a non-constant-size is a VLA.
1298 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
1299 } else if (isArraySizeVLA(ArraySize, ConstVal, *this)) {
1300 // C99: an array with a non-ICE size is a VLA. We accept any expression
1301 // that we can fold to a non-zero positive value as an extension.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001302 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
Douglas Gregorcd281c32009-02-28 00:25:32 +00001303 } else {
1304 // C99 6.7.5.2p1: If the expression is a constant expression, it shall
1305 // have a value greater than zero.
Sebastian Redl923d56d2009-11-05 15:52:31 +00001306 if (ConstVal.isSigned() && ConstVal.isNegative()) {
Chandler Carruthb2b5cc02011-01-04 04:44:35 +00001307 if (Entity)
1308 Diag(ArraySize->getLocStart(), diag::err_decl_negative_array_size)
1309 << getPrintableNameForEntity(Entity) << ArraySize->getSourceRange();
1310 else
1311 Diag(ArraySize->getLocStart(), diag::err_typecheck_negative_array_size)
1312 << ArraySize->getSourceRange();
Sebastian Redl923d56d2009-11-05 15:52:31 +00001313 return QualType();
1314 }
1315 if (ConstVal == 0) {
Douglas Gregor02024a92010-03-28 02:42:43 +00001316 // GCC accepts zero sized static arrays. We allow them when
1317 // we're not in a SFINAE context.
1318 Diag(ArraySize->getLocStart(),
1319 isSFINAEContext()? diag::err_typecheck_zero_array_size
1320 : diag::ext_typecheck_zero_array_size)
Sebastian Redl923d56d2009-11-05 15:52:31 +00001321 << ArraySize->getSourceRange();
Peter Collingbourne20cdbeb2011-10-16 21:17:32 +00001322
1323 if (ASM == ArrayType::Static) {
1324 Diag(ArraySize->getLocStart(),
1325 diag::warn_typecheck_zero_static_array_size)
1326 << ArraySize->getSourceRange();
1327 ASM = ArrayType::Normal;
1328 }
Douglas Gregor2767ce22010-08-18 00:39:00 +00001329 } else if (!T->isDependentType() && !T->isVariablyModifiedType() &&
1330 !T->isIncompleteType()) {
1331 // Is the array too large?
1332 unsigned ActiveSizeBits
1333 = ConstantArrayType::getNumAddressingBits(Context, T, ConstVal);
1334 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
1335 Diag(ArraySize->getLocStart(), diag::err_array_too_large)
1336 << ConstVal.toString(10)
1337 << ArraySize->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001338 }
Douglas Gregor2767ce22010-08-18 00:39:00 +00001339
John McCall46a617a2009-10-16 00:14:28 +00001340 T = Context.getConstantArrayType(T, ConstVal, ASM, Quals);
Douglas Gregorcd281c32009-02-28 00:25:32 +00001341 }
David Chisnallaf407762010-01-11 23:08:08 +00001342 // If this is not C99, extwarn about VLA's and C99 array size modifiers.
1343 if (!getLangOptions().C99) {
Douglas Gregor0fddb972010-05-22 16:17:30 +00001344 if (T->isVariableArrayType()) {
1345 // Prohibit the use of non-POD types in VLAs.
John McCallf85e1932011-06-15 23:02:42 +00001346 QualType BaseT = Context.getBaseElementType(T);
Douglas Gregor204ce172010-05-24 20:42:30 +00001347 if (!T->isDependentType() &&
John McCallf85e1932011-06-15 23:02:42 +00001348 !BaseT.isPODType(Context) &&
1349 !BaseT->isObjCLifetimeType()) {
Douglas Gregor0fddb972010-05-22 16:17:30 +00001350 Diag(Loc, diag::err_vla_non_pod)
John McCallf85e1932011-06-15 23:02:42 +00001351 << BaseT;
Douglas Gregor0fddb972010-05-22 16:17:30 +00001352 return QualType();
1353 }
Douglas Gregora481ec42010-05-23 19:57:01 +00001354 // Prohibit the use of VLAs during template argument deduction.
1355 else if (isSFINAEContext()) {
1356 Diag(Loc, diag::err_vla_in_sfinae);
1357 return QualType();
1358 }
Douglas Gregor0fddb972010-05-22 16:17:30 +00001359 // Just extwarn about VLAs.
1360 else
1361 Diag(Loc, diag::ext_vla);
1362 } else if (ASM != ArrayType::Normal || Quals != 0)
Douglas Gregor043cad22009-09-11 00:18:58 +00001363 Diag(Loc,
1364 getLangOptions().CPlusPlus? diag::err_c99_array_usage_cxx
1365 : diag::ext_c99_array_usage);
Douglas Gregorcd281c32009-02-28 00:25:32 +00001366 }
1367
1368 return T;
1369}
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001370
1371/// \brief Build an ext-vector type.
1372///
1373/// Run the required checks for the extended vector type.
John McCall9ae2f072010-08-23 23:25:46 +00001374QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize,
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001375 SourceLocation AttrLoc) {
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001376 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1377 // in conjunction with complex types (pointers, arrays, functions, etc.).
Mike Stump1eb44332009-09-09 15:08:12 +00001378 if (!T->isDependentType() &&
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001379 !T->isIntegerType() && !T->isRealFloatingType()) {
1380 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
1381 return QualType();
1382 }
1383
John McCall9ae2f072010-08-23 23:25:46 +00001384 if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) {
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001385 llvm::APSInt vecSize(32);
John McCall9ae2f072010-08-23 23:25:46 +00001386 if (!ArraySize->isIntegerConstantExpr(vecSize, Context)) {
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001387 Diag(AttrLoc, diag::err_attribute_argument_not_int)
John McCall9ae2f072010-08-23 23:25:46 +00001388 << "ext_vector_type" << ArraySize->getSourceRange();
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001389 return QualType();
1390 }
Mike Stump1eb44332009-09-09 15:08:12 +00001391
1392 // unlike gcc's vector_size attribute, the size is specified as the
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001393 // number of elements, not the number of bytes.
Mike Stump1eb44332009-09-09 15:08:12 +00001394 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
1395
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001396 if (vectorSize == 0) {
1397 Diag(AttrLoc, diag::err_attribute_zero_size)
John McCall9ae2f072010-08-23 23:25:46 +00001398 << ArraySize->getSourceRange();
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001399 return QualType();
1400 }
Mike Stump1eb44332009-09-09 15:08:12 +00001401
Douglas Gregor4ac01402011-06-15 16:02:29 +00001402 return Context.getExtVectorType(T, vectorSize);
Mike Stump1eb44332009-09-09 15:08:12 +00001403 }
1404
John McCall9ae2f072010-08-23 23:25:46 +00001405 return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc);
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001406}
Mike Stump1eb44332009-09-09 15:08:12 +00001407
Douglas Gregor724651c2009-02-28 01:04:19 +00001408/// \brief Build a function type.
1409///
1410/// This routine checks the function type according to C++ rules and
1411/// under the assumption that the result type and parameter types have
1412/// just been instantiated from a template. It therefore duplicates
Douglas Gregor2943aed2009-03-03 04:44:36 +00001413/// some of the behavior of GetTypeForDeclarator, but in a much
Douglas Gregor724651c2009-02-28 01:04:19 +00001414/// simpler form that is only suitable for this narrow use case.
1415///
1416/// \param T The return type of the function.
1417///
1418/// \param ParamTypes The parameter types of the function. This array
1419/// will be modified to account for adjustments to the types of the
1420/// function parameters.
1421///
1422/// \param NumParamTypes The number of parameter types in ParamTypes.
1423///
1424/// \param Variadic Whether this is a variadic function type.
1425///
1426/// \param Quals The cvr-qualifiers to be applied to the function type.
1427///
1428/// \param Loc The location of the entity whose type involves this
1429/// function type or, if there is no such entity, the location of the
1430/// type that will have function type.
1431///
1432/// \param Entity The name of the entity that involves the function
1433/// type, if known.
1434///
1435/// \returns A suitable function type, if there are no
1436/// errors. Otherwise, returns a NULL type.
1437QualType Sema::BuildFunctionType(QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00001438 QualType *ParamTypes,
Douglas Gregor724651c2009-02-28 01:04:19 +00001439 unsigned NumParamTypes,
1440 bool Variadic, unsigned Quals,
Douglas Gregorc938c162011-01-26 05:01:58 +00001441 RefQualifierKind RefQualifier,
Eli Friedmanfa869542010-08-05 02:54:05 +00001442 SourceLocation Loc, DeclarationName Entity,
John McCalle23cf432010-12-14 08:05:40 +00001443 FunctionType::ExtInfo Info) {
Douglas Gregor724651c2009-02-28 01:04:19 +00001444 if (T->isArrayType() || T->isFunctionType()) {
Douglas Gregor58408bc2010-01-11 18:46:21 +00001445 Diag(Loc, diag::err_func_returning_array_function)
1446 << T->isFunctionType() << T;
Douglas Gregor724651c2009-02-28 01:04:19 +00001447 return QualType();
1448 }
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001449
1450 // Functions cannot return half FP.
1451 if (T->isHalfType()) {
1452 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 <<
1453 FixItHint::CreateInsertion(Loc, "*");
1454 return QualType();
1455 }
1456
Douglas Gregor724651c2009-02-28 01:04:19 +00001457 bool Invalid = false;
1458 for (unsigned Idx = 0; Idx < NumParamTypes; ++Idx) {
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001459 // FIXME: Loc is too inprecise here, should use proper locations for args.
Douglas Gregor79e6bd32011-07-12 04:42:08 +00001460 QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001461 if (ParamType->isVoidType()) {
Douglas Gregor724651c2009-02-28 01:04:19 +00001462 Diag(Loc, diag::err_param_with_void_type);
1463 Invalid = true;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001464 } else if (ParamType->isHalfType()) {
1465 // Disallow half FP arguments.
1466 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 <<
1467 FixItHint::CreateInsertion(Loc, "*");
1468 Invalid = true;
Douglas Gregor724651c2009-02-28 01:04:19 +00001469 }
Douglas Gregorcd281c32009-02-28 00:25:32 +00001470
John McCall54e14c42009-10-22 22:37:11 +00001471 ParamTypes[Idx] = ParamType;
Douglas Gregor724651c2009-02-28 01:04:19 +00001472 }
1473
1474 if (Invalid)
1475 return QualType();
1476
John McCalle23cf432010-12-14 08:05:40 +00001477 FunctionProtoType::ExtProtoInfo EPI;
1478 EPI.Variadic = Variadic;
1479 EPI.TypeQuals = Quals;
Douglas Gregorc938c162011-01-26 05:01:58 +00001480 EPI.RefQualifier = RefQualifier;
John McCalle23cf432010-12-14 08:05:40 +00001481 EPI.ExtInfo = Info;
1482
1483 return Context.getFunctionType(T, ParamTypes, NumParamTypes, EPI);
Douglas Gregor724651c2009-02-28 01:04:19 +00001484}
Mike Stump1eb44332009-09-09 15:08:12 +00001485
Douglas Gregor949bf692009-06-09 22:17:39 +00001486/// \brief Build a member pointer type \c T Class::*.
1487///
1488/// \param T the type to which the member pointer refers.
1489/// \param Class the class type into which the member pointer points.
John McCall0953e762009-09-24 19:53:00 +00001490/// \param CVR Qualifiers applied to the member pointer type
Douglas Gregor949bf692009-06-09 22:17:39 +00001491/// \param Loc the location where this type begins
1492/// \param Entity the name of the entity that will have this member pointer type
1493///
1494/// \returns a member pointer type, if successful, or a NULL type if there was
1495/// an error.
Mike Stump1eb44332009-09-09 15:08:12 +00001496QualType Sema::BuildMemberPointerType(QualType T, QualType Class,
John McCall28654742010-06-05 06:41:15 +00001497 SourceLocation Loc,
Douglas Gregor949bf692009-06-09 22:17:39 +00001498 DeclarationName Entity) {
1499 // Verify that we're not building a pointer to pointer to function with
1500 // exception specification.
1501 if (CheckDistantExceptionSpec(T)) {
1502 Diag(Loc, diag::err_distant_exception_spec);
1503
1504 // FIXME: If we're doing this as part of template instantiation,
1505 // we should return immediately.
1506
1507 // Build the type anyway, but use the canonical type so that the
1508 // exception specifiers are stripped off.
1509 T = Context.getCanonicalType(T);
1510 }
1511
Sebastian Redl73780122010-06-09 21:19:43 +00001512 // C++ 8.3.3p3: A pointer to member shall not point to ... a member
Douglas Gregor949bf692009-06-09 22:17:39 +00001513 // with reference type, or "cv void."
1514 if (T->isReferenceType()) {
Anders Carlsson8d4655d2009-06-30 00:06:57 +00001515 Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
John McCallac406052009-10-30 00:37:20 +00001516 << (Entity? Entity.getAsString() : "type name") << T;
Douglas Gregor949bf692009-06-09 22:17:39 +00001517 return QualType();
1518 }
1519
1520 if (T->isVoidType()) {
1521 Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
1522 << (Entity? Entity.getAsString() : "type name");
1523 return QualType();
1524 }
1525
Douglas Gregor949bf692009-06-09 22:17:39 +00001526 if (!Class->isDependentType() && !Class->isRecordType()) {
1527 Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
1528 return QualType();
1529 }
1530
Charles Davisd18f9f92010-08-16 04:01:50 +00001531 // In the Microsoft ABI, the class is allowed to be an incomplete
1532 // type. In such cases, the compiler makes a worst-case assumption.
1533 // We make no such assumption right now, so emit an error if the
1534 // class isn't a complete type.
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001535 if (Context.getTargetInfo().getCXXABI() == CXXABI_Microsoft &&
Charles Davisd18f9f92010-08-16 04:01:50 +00001536 RequireCompleteType(Loc, Class, diag::err_incomplete_type))
1537 return QualType();
1538
John McCall28654742010-06-05 06:41:15 +00001539 return Context.getMemberPointerType(T, Class.getTypePtr());
Douglas Gregor949bf692009-06-09 22:17:39 +00001540}
Mike Stump1eb44332009-09-09 15:08:12 +00001541
Anders Carlsson9a917e42009-06-12 22:56:54 +00001542/// \brief Build a block pointer type.
1543///
1544/// \param T The type to which we'll be building a block pointer.
1545///
John McCall0953e762009-09-24 19:53:00 +00001546/// \param CVR The cvr-qualifiers to be applied to the block pointer type.
Anders Carlsson9a917e42009-06-12 22:56:54 +00001547///
1548/// \param Loc The location of the entity whose type involves this
1549/// block pointer type or, if there is no such entity, the location of the
1550/// type that will have block pointer type.
1551///
1552/// \param Entity The name of the entity that involves the block pointer
1553/// type, if known.
1554///
1555/// \returns A suitable block pointer type, if there are no
1556/// errors. Otherwise, returns a NULL type.
John McCall28654742010-06-05 06:41:15 +00001557QualType Sema::BuildBlockPointerType(QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00001558 SourceLocation Loc,
Anders Carlsson9a917e42009-06-12 22:56:54 +00001559 DeclarationName Entity) {
John McCall0953e762009-09-24 19:53:00 +00001560 if (!T->isFunctionType()) {
Anders Carlsson9a917e42009-06-12 22:56:54 +00001561 Diag(Loc, diag::err_nonfunction_block_type);
1562 return QualType();
1563 }
Mike Stump1eb44332009-09-09 15:08:12 +00001564
John McCall28654742010-06-05 06:41:15 +00001565 return Context.getBlockPointerType(T);
Anders Carlsson9a917e42009-06-12 22:56:54 +00001566}
1567
John McCallb3d87482010-08-24 05:47:05 +00001568QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) {
1569 QualType QT = Ty.get();
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001570 if (QT.isNull()) {
John McCalla93c9342009-12-07 02:54:59 +00001571 if (TInfo) *TInfo = 0;
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001572 return QualType();
1573 }
1574
John McCalla93c9342009-12-07 02:54:59 +00001575 TypeSourceInfo *DI = 0;
John McCallf4c73712011-01-19 06:33:43 +00001576 if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001577 QT = LIT->getType();
John McCalla93c9342009-12-07 02:54:59 +00001578 DI = LIT->getTypeSourceInfo();
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001579 }
Mike Stump1eb44332009-09-09 15:08:12 +00001580
John McCalla93c9342009-12-07 02:54:59 +00001581 if (TInfo) *TInfo = DI;
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001582 return QT;
1583}
1584
Argyrios Kyrtzidisa8349f52011-07-01 22:23:05 +00001585static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
1586 Qualifiers::ObjCLifetime ownership,
1587 unsigned chunkIndex);
1588
John McCallf85e1932011-06-15 23:02:42 +00001589/// Given that this is the declaration of a parameter under ARC,
1590/// attempt to infer attributes and such for pointer-to-whatever
1591/// types.
1592static void inferARCWriteback(TypeProcessingState &state,
1593 QualType &declSpecType) {
1594 Sema &S = state.getSema();
1595 Declarator &declarator = state.getDeclarator();
1596
1597 // TODO: should we care about decl qualifiers?
1598
1599 // Check whether the declarator has the expected form. We walk
1600 // from the inside out in order to make the block logic work.
1601 unsigned outermostPointerIndex = 0;
1602 bool isBlockPointer = false;
1603 unsigned numPointers = 0;
1604 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
1605 unsigned chunkIndex = i;
1606 DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex);
1607 switch (chunk.Kind) {
1608 case DeclaratorChunk::Paren:
1609 // Ignore parens.
1610 break;
1611
1612 case DeclaratorChunk::Reference:
1613 case DeclaratorChunk::Pointer:
1614 // Count the number of pointers. Treat references
1615 // interchangeably as pointers; if they're mis-ordered, normal
1616 // type building will discover that.
1617 outermostPointerIndex = chunkIndex;
1618 numPointers++;
1619 break;
1620
1621 case DeclaratorChunk::BlockPointer:
1622 // If we have a pointer to block pointer, that's an acceptable
1623 // indirect reference; anything else is not an application of
1624 // the rules.
1625 if (numPointers != 1) return;
1626 numPointers++;
1627 outermostPointerIndex = chunkIndex;
1628 isBlockPointer = true;
1629
1630 // We don't care about pointer structure in return values here.
1631 goto done;
1632
1633 case DeclaratorChunk::Array: // suppress if written (id[])?
1634 case DeclaratorChunk::Function:
1635 case DeclaratorChunk::MemberPointer:
1636 return;
1637 }
1638 }
1639 done:
1640
1641 // If we have *one* pointer, then we want to throw the qualifier on
1642 // the declaration-specifiers, which means that it needs to be a
1643 // retainable object type.
1644 if (numPointers == 1) {
1645 // If it's not a retainable object type, the rule doesn't apply.
1646 if (!declSpecType->isObjCRetainableType()) return;
1647
1648 // If it already has lifetime, don't do anything.
1649 if (declSpecType.getObjCLifetime()) return;
1650
1651 // Otherwise, modify the type in-place.
1652 Qualifiers qs;
1653
1654 if (declSpecType->isObjCARCImplicitlyUnretainedType())
1655 qs.addObjCLifetime(Qualifiers::OCL_ExplicitNone);
1656 else
1657 qs.addObjCLifetime(Qualifiers::OCL_Autoreleasing);
1658 declSpecType = S.Context.getQualifiedType(declSpecType, qs);
1659
1660 // If we have *two* pointers, then we want to throw the qualifier on
1661 // the outermost pointer.
1662 } else if (numPointers == 2) {
1663 // If we don't have a block pointer, we need to check whether the
1664 // declaration-specifiers gave us something that will turn into a
1665 // retainable object pointer after we slap the first pointer on it.
1666 if (!isBlockPointer && !declSpecType->isObjCObjectType())
1667 return;
1668
1669 // Look for an explicit lifetime attribute there.
1670 DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex);
Argyrios Kyrtzidis1c73dcb2011-07-01 22:23:03 +00001671 if (chunk.Kind != DeclaratorChunk::Pointer &&
1672 chunk.Kind != DeclaratorChunk::BlockPointer)
1673 return;
John McCallf85e1932011-06-15 23:02:42 +00001674 for (const AttributeList *attr = chunk.getAttrs(); attr;
1675 attr = attr->getNext())
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00001676 if (attr->getKind() == AttributeList::AT_objc_ownership)
John McCallf85e1932011-06-15 23:02:42 +00001677 return;
1678
Argyrios Kyrtzidisa8349f52011-07-01 22:23:05 +00001679 transferARCOwnershipToDeclaratorChunk(state, Qualifiers::OCL_Autoreleasing,
1680 outermostPointerIndex);
John McCallf85e1932011-06-15 23:02:42 +00001681
1682 // Any other number of pointers/references does not trigger the rule.
1683 } else return;
1684
1685 // TODO: mark whether we did this inference?
1686}
1687
Chandler Carruthd067c072011-02-23 18:51:59 +00001688static void DiagnoseIgnoredQualifiers(unsigned Quals,
1689 SourceLocation ConstQualLoc,
1690 SourceLocation VolatileQualLoc,
1691 SourceLocation RestrictQualLoc,
1692 Sema& S) {
1693 std::string QualStr;
1694 unsigned NumQuals = 0;
1695 SourceLocation Loc;
1696
1697 FixItHint ConstFixIt;
1698 FixItHint VolatileFixIt;
1699 FixItHint RestrictFixIt;
1700
Hans Wennborga08fcb82011-06-03 17:37:26 +00001701 const SourceManager &SM = S.getSourceManager();
1702
Chandler Carruthd067c072011-02-23 18:51:59 +00001703 // FIXME: The locations here are set kind of arbitrarily. It'd be nicer to
1704 // find a range and grow it to encompass all the qualifiers, regardless of
1705 // the order in which they textually appear.
1706 if (Quals & Qualifiers::Const) {
1707 ConstFixIt = FixItHint::CreateRemoval(ConstQualLoc);
Chandler Carruthd067c072011-02-23 18:51:59 +00001708 QualStr = "const";
Hans Wennborga08fcb82011-06-03 17:37:26 +00001709 ++NumQuals;
1710 if (!Loc.isValid() || SM.isBeforeInTranslationUnit(ConstQualLoc, Loc))
1711 Loc = ConstQualLoc;
Chandler Carruthd067c072011-02-23 18:51:59 +00001712 }
1713 if (Quals & Qualifiers::Volatile) {
1714 VolatileFixIt = FixItHint::CreateRemoval(VolatileQualLoc);
Hans Wennborga08fcb82011-06-03 17:37:26 +00001715 QualStr += (NumQuals == 0 ? "volatile" : " volatile");
Chandler Carruthd067c072011-02-23 18:51:59 +00001716 ++NumQuals;
Hans Wennborga08fcb82011-06-03 17:37:26 +00001717 if (!Loc.isValid() || SM.isBeforeInTranslationUnit(VolatileQualLoc, Loc))
1718 Loc = VolatileQualLoc;
Chandler Carruthd067c072011-02-23 18:51:59 +00001719 }
1720 if (Quals & Qualifiers::Restrict) {
1721 RestrictFixIt = FixItHint::CreateRemoval(RestrictQualLoc);
Hans Wennborga08fcb82011-06-03 17:37:26 +00001722 QualStr += (NumQuals == 0 ? "restrict" : " restrict");
Chandler Carruthd067c072011-02-23 18:51:59 +00001723 ++NumQuals;
Hans Wennborga08fcb82011-06-03 17:37:26 +00001724 if (!Loc.isValid() || SM.isBeforeInTranslationUnit(RestrictQualLoc, Loc))
1725 Loc = RestrictQualLoc;
Chandler Carruthd067c072011-02-23 18:51:59 +00001726 }
1727
1728 assert(NumQuals > 0 && "No known qualifiers?");
1729
1730 S.Diag(Loc, diag::warn_qual_return_type)
Hans Wennborga08fcb82011-06-03 17:37:26 +00001731 << QualStr << NumQuals << ConstFixIt << VolatileFixIt << RestrictFixIt;
Chandler Carruthd067c072011-02-23 18:51:59 +00001732}
1733
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001734static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state,
1735 TypeSourceInfo *&ReturnTypeInfo) {
1736 Sema &SemaRef = state.getSema();
1737 Declarator &D = state.getDeclarator();
Douglas Gregor930d8b52009-01-30 22:09:00 +00001738 QualType T;
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001739 ReturnTypeInfo = 0;
1740
1741 // The TagDecl owned by the DeclSpec.
Argyrios Kyrtzidisd3880f82011-06-28 03:01:18 +00001742 TagDecl *OwnedTagDecl = 0;
John McCall711c52b2011-01-05 12:14:39 +00001743
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001744 switch (D.getName().getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001745 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001746 case UnqualifiedId::IK_OperatorFunctionId:
Sebastian Redl8999fe12011-03-14 18:08:30 +00001747 case UnqualifiedId::IK_Identifier:
Sean Hunt0486d742009-11-28 04:44:28 +00001748 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001749 case UnqualifiedId::IK_TemplateId:
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001750 T = ConvertDeclSpecToType(state);
Chris Lattner5db2bb12009-10-25 18:21:37 +00001751
Douglas Gregor591bd3c2010-02-08 22:07:33 +00001752 if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) {
Argyrios Kyrtzidisd3880f82011-06-28 03:01:18 +00001753 OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
Abramo Bagnara15987972011-03-08 22:33:38 +00001754 // Owned declaration is embedded in declarator.
Argyrios Kyrtzidisd3880f82011-06-28 03:01:18 +00001755 OwnedTagDecl->setEmbeddedInDeclarator(true);
Douglas Gregor591bd3c2010-02-08 22:07:33 +00001756 }
Douglas Gregor930d8b52009-01-30 22:09:00 +00001757 break;
1758
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001759 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00001760 case UnqualifiedId::IK_ConstructorTemplateId:
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001761 case UnqualifiedId::IK_DestructorName:
Douglas Gregor930d8b52009-01-30 22:09:00 +00001762 // Constructors and destructors don't have return types. Use
Douglas Gregor48026d22010-01-11 18:40:55 +00001763 // "void" instead.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001764 T = SemaRef.Context.VoidTy;
Douglas Gregor930d8b52009-01-30 22:09:00 +00001765 break;
Douglas Gregor48026d22010-01-11 18:40:55 +00001766
1767 case UnqualifiedId::IK_ConversionFunctionId:
1768 // The result type of a conversion function is the type that it
1769 // converts to.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001770 T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId,
1771 &ReturnTypeInfo);
Douglas Gregor48026d22010-01-11 18:40:55 +00001772 break;
Douglas Gregor930d8b52009-01-30 22:09:00 +00001773 }
Douglas Gregordab60ad2010-10-01 18:44:50 +00001774
John McCall711c52b2011-01-05 12:14:39 +00001775 if (D.getAttributes())
1776 distributeTypeAttrsFromDeclarator(state, T);
1777
Richard Smithe7397c62011-02-22 00:36:53 +00001778 // C++0x [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context.
Richard Smith8110f042011-02-22 01:22:29 +00001779 // In C++0x, a function declarator using 'auto' must have a trailing return
1780 // type (this is checked later) and we can skip this. In other languages
1781 // using auto, we need to check regardless.
Richard Smith34b41d92011-02-20 03:19:35 +00001782 if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto &&
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001783 (!SemaRef.getLangOptions().CPlusPlus0x || !D.isFunctionDeclarator())) {
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001784 int Error = -1;
Mike Stump1eb44332009-09-09 15:08:12 +00001785
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001786 switch (D.getContext()) {
1787 case Declarator::KNRTypeListContext:
David Blaikieb219cfc2011-09-23 05:06:16 +00001788 llvm_unreachable("K&R type lists aren't allowed in C++");
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001789 break;
John McCallcdda47f2011-10-01 09:56:14 +00001790 case Declarator::ObjCParameterContext:
1791 case Declarator::ObjCResultContext:
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001792 case Declarator::PrototypeContext:
1793 Error = 0; // Function prototype
1794 break;
1795 case Declarator::MemberContext:
Richard Smith7a614d82011-06-11 17:19:42 +00001796 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)
1797 break;
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001798 switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) {
David Blaikieeb2d1f12011-09-23 20:26:49 +00001799 case TTK_Enum: llvm_unreachable("unhandled tag kind");
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001800 case TTK_Struct: Error = 1; /* Struct member */ break;
1801 case TTK_Union: Error = 2; /* Union member */ break;
1802 case TTK_Class: Error = 3; /* Class member */ break;
Mike Stump1eb44332009-09-09 15:08:12 +00001803 }
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001804 break;
1805 case Declarator::CXXCatchContext:
Argyrios Kyrtzidis17b63992011-07-01 22:22:40 +00001806 case Declarator::ObjCCatchContext:
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001807 Error = 4; // Exception declaration
1808 break;
1809 case Declarator::TemplateParamContext:
1810 Error = 5; // Template parameter
1811 break;
1812 case Declarator::BlockLiteralContext:
Richard Smith34b41d92011-02-20 03:19:35 +00001813 Error = 6; // Block literal
1814 break;
1815 case Declarator::TemplateTypeArgContext:
1816 Error = 7; // Template type argument
1817 break;
Richard Smith162e1c12011-04-15 14:24:37 +00001818 case Declarator::AliasDeclContext:
Richard Smith3e4c6c42011-05-05 21:57:07 +00001819 case Declarator::AliasTemplateContext:
Richard Smith162e1c12011-04-15 14:24:37 +00001820 Error = 9; // Type alias
1821 break;
Richard Smith34b41d92011-02-20 03:19:35 +00001822 case Declarator::TypeNameContext:
Argyrios Kyrtzidis0b8c98f2011-06-28 03:01:23 +00001823 Error = 11; // Generic
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001824 break;
1825 case Declarator::FileContext:
1826 case Declarator::BlockContext:
1827 case Declarator::ForContext:
1828 case Declarator::ConditionContext:
Argyrios Kyrtzidis0b8c98f2011-06-28 03:01:23 +00001829 case Declarator::CXXNewContext:
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001830 break;
1831 }
1832
Richard Smithddc83f92011-02-21 23:18:00 +00001833 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
1834 Error = 8;
1835
Richard Smith8110f042011-02-22 01:22:29 +00001836 // In Objective-C it is an error to use 'auto' on a function declarator.
1837 if (D.isFunctionDeclarator())
Richard Smith162e1c12011-04-15 14:24:37 +00001838 Error = 10;
Richard Smith8110f042011-02-22 01:22:29 +00001839
Richard Smithe7397c62011-02-22 00:36:53 +00001840 // C++0x [dcl.spec.auto]p2: 'auto' is always fine if the declarator
1841 // contains a trailing return type. That is only legal at the outermost
1842 // level. Check all declarator chunks (outermost first) anyway, to give
1843 // better diagnostics.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001844 if (SemaRef.getLangOptions().CPlusPlus0x && Error != -1) {
Richard Smithe7397c62011-02-22 00:36:53 +00001845 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
1846 unsigned chunkIndex = e - i - 1;
1847 state.setCurrentChunkIndex(chunkIndex);
1848 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
1849 if (DeclType.Kind == DeclaratorChunk::Function) {
1850 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
1851 if (FTI.TrailingReturnType) {
1852 Error = -1;
1853 break;
1854 }
1855 }
1856 }
1857 }
1858
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001859 if (Error != -1) {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001860 SemaRef.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
1861 diag::err_auto_not_allowed)
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001862 << Error;
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001863 T = SemaRef.Context.IntTy;
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001864 D.setInvalidType(true);
Richard Smith0aa86c02011-10-15 05:42:01 +00001865 } else
1866 SemaRef.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
1867 diag::warn_cxx98_compat_auto_type_specifier);
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001868 }
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001869
1870 if (SemaRef.getLangOptions().CPlusPlus &&
John McCall5e1cdac2011-10-07 06:10:15 +00001871 OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001872 // Check the contexts where C++ forbids the declaration of a new class
1873 // or enumeration in a type-specifier-seq.
1874 switch (D.getContext()) {
1875 case Declarator::FileContext:
1876 case Declarator::MemberContext:
1877 case Declarator::BlockContext:
1878 case Declarator::ForContext:
1879 case Declarator::BlockLiteralContext:
1880 // C++0x [dcl.type]p3:
1881 // A type-specifier-seq shall not define a class or enumeration unless
1882 // it appears in the type-id of an alias-declaration (7.1.3) that is not
1883 // the declaration of a template-declaration.
1884 case Declarator::AliasDeclContext:
1885 break;
1886 case Declarator::AliasTemplateContext:
1887 SemaRef.Diag(OwnedTagDecl->getLocation(),
1888 diag::err_type_defined_in_alias_template)
1889 << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
1890 break;
1891 case Declarator::TypeNameContext:
1892 case Declarator::TemplateParamContext:
1893 case Declarator::CXXNewContext:
1894 case Declarator::CXXCatchContext:
1895 case Declarator::ObjCCatchContext:
1896 case Declarator::TemplateTypeArgContext:
1897 SemaRef.Diag(OwnedTagDecl->getLocation(),
1898 diag::err_type_defined_in_type_specifier)
1899 << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
1900 break;
1901 case Declarator::PrototypeContext:
John McCallcdda47f2011-10-01 09:56:14 +00001902 case Declarator::ObjCParameterContext:
1903 case Declarator::ObjCResultContext:
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001904 case Declarator::KNRTypeListContext:
1905 // C++ [dcl.fct]p6:
1906 // Types shall not be defined in return or parameter types.
1907 SemaRef.Diag(OwnedTagDecl->getLocation(),
1908 diag::err_type_defined_in_param_type)
1909 << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
1910 break;
1911 case Declarator::ConditionContext:
1912 // C++ 6.4p2:
1913 // The type-specifier-seq shall not contain typedef and shall not declare
1914 // a new class or enumeration.
1915 SemaRef.Diag(OwnedTagDecl->getLocation(),
1916 diag::err_type_defined_in_condition);
1917 break;
1918 }
1919 }
1920
1921 return T;
1922}
1923
1924static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
1925 QualType declSpecType,
1926 TypeSourceInfo *TInfo) {
1927
1928 QualType T = declSpecType;
1929 Declarator &D = state.getDeclarator();
1930 Sema &S = state.getSema();
1931 ASTContext &Context = S.Context;
1932 const LangOptions &LangOpts = S.getLangOptions();
1933
1934 bool ImplicitlyNoexcept = false;
1935 if (D.getName().getKind() == UnqualifiedId::IK_OperatorFunctionId &&
1936 LangOpts.CPlusPlus0x) {
1937 OverloadedOperatorKind OO = D.getName().OperatorFunctionId.Operator;
1938 /// In C++0x, deallocation functions (normal and array operator delete)
1939 /// are implicitly noexcept.
1940 if (OO == OO_Delete || OO == OO_Array_Delete)
1941 ImplicitlyNoexcept = true;
1942 }
Richard Smith34b41d92011-02-20 03:19:35 +00001943
Douglas Gregorcd281c32009-02-28 00:25:32 +00001944 // The name we're declaring, if any.
1945 DeclarationName Name;
1946 if (D.getIdentifier())
1947 Name = D.getIdentifier();
Mike Stump1eb44332009-09-09 15:08:12 +00001948
Richard Smith162e1c12011-04-15 14:24:37 +00001949 // Does this declaration declare a typedef-name?
1950 bool IsTypedefName =
1951 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef ||
Richard Smith3e4c6c42011-05-05 21:57:07 +00001952 D.getContext() == Declarator::AliasDeclContext ||
1953 D.getContext() == Declarator::AliasTemplateContext;
Richard Smith162e1c12011-04-15 14:24:37 +00001954
Mike Stump98eb8a72009-02-04 22:31:32 +00001955 // Walk the DeclTypeInfo, building the recursive type as we go.
1956 // DeclTypeInfos are ordered from the identifier out, which is
1957 // opposite of what we want :).
Sebastian Redl8ce35b02009-10-25 21:45:37 +00001958 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
John McCall711c52b2011-01-05 12:14:39 +00001959 unsigned chunkIndex = e - i - 1;
1960 state.setCurrentChunkIndex(chunkIndex);
1961 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001962 switch (DeclType.Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001963 default: llvm_unreachable("Unknown decltype!");
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001964 case DeclaratorChunk::Paren:
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001965 T = S.BuildParenType(T);
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001966 break;
Steve Naroff5618bd42008-08-27 16:04:49 +00001967 case DeclaratorChunk::BlockPointer:
Chris Lattner9af55002009-03-27 04:18:06 +00001968 // If blocks are disabled, emit an error.
1969 if (!LangOpts.Blocks)
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001970 S.Diag(DeclType.Loc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +00001971
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001972 T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name);
John McCall28654742010-06-05 06:41:15 +00001973 if (DeclType.Cls.TypeQuals)
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001974 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals);
Steve Naroff5618bd42008-08-27 16:04:49 +00001975 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001976 case DeclaratorChunk::Pointer:
Sebastian Redl6a7330c2009-05-29 15:01:05 +00001977 // Verify that we're not building a pointer to pointer to function with
1978 // exception specification.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001979 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
1980 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
Sebastian Redl6a7330c2009-05-29 15:01:05 +00001981 D.setInvalidType(true);
1982 // Build the type anyway.
1983 }
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001984 if (LangOpts.ObjC1 && T->getAs<ObjCObjectType>()) {
John McCallc12c5bb2010-05-15 11:32:37 +00001985 T = Context.getObjCObjectPointerType(T);
John McCall28654742010-06-05 06:41:15 +00001986 if (DeclType.Ptr.TypeQuals)
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001987 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
Steve Naroff14108da2009-07-10 23:34:53 +00001988 break;
1989 }
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001990 T = S.BuildPointerType(T, DeclType.Loc, Name);
John McCall28654742010-06-05 06:41:15 +00001991 if (DeclType.Ptr.TypeQuals)
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001992 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
John McCall711c52b2011-01-05 12:14:39 +00001993
Reid Spencer5f016e22007-07-11 17:01:13 +00001994 break;
John McCall0953e762009-09-24 19:53:00 +00001995 case DeclaratorChunk::Reference: {
Sebastian Redl6a7330c2009-05-29 15:01:05 +00001996 // Verify that we're not building a reference to pointer to function with
1997 // exception specification.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001998 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
1999 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
Sebastian Redl6a7330c2009-05-29 15:01:05 +00002000 D.setInvalidType(true);
2001 // Build the type anyway.
2002 }
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002003 T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name);
John McCall28654742010-06-05 06:41:15 +00002004
2005 Qualifiers Quals;
2006 if (DeclType.Ref.HasRestrict)
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002007 T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict);
Reid Spencer5f016e22007-07-11 17:01:13 +00002008 break;
John McCall0953e762009-09-24 19:53:00 +00002009 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002010 case DeclaratorChunk::Array: {
Sebastian Redl6a7330c2009-05-29 15:01:05 +00002011 // Verify that we're not building an array of pointers to function with
2012 // exception specification.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002013 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
2014 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
Sebastian Redl6a7330c2009-05-29 15:01:05 +00002015 D.setInvalidType(true);
2016 // Build the type anyway.
2017 }
Chris Lattnerfd89bc82008-04-02 01:05:10 +00002018 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
Chris Lattner94f81fd2007-08-28 16:54:00 +00002019 Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
Reid Spencer5f016e22007-07-11 17:01:13 +00002020 ArrayType::ArraySizeModifier ASM;
2021 if (ATI.isStar)
2022 ASM = ArrayType::Star;
2023 else if (ATI.hasStatic)
2024 ASM = ArrayType::Static;
2025 else
2026 ASM = ArrayType::Normal;
John McCallc05a94b2011-03-23 23:43:04 +00002027 if (ASM == ArrayType::Star && !D.isPrototypeContext()) {
Eli Friedmanf91f5c82009-04-26 21:57:51 +00002028 // FIXME: This check isn't quite right: it allows star in prototypes
2029 // for function definitions, and disallows some edge cases detailed
2030 // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002031 S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
Eli Friedmanf91f5c82009-04-26 21:57:51 +00002032 ASM = ArrayType::Normal;
2033 D.setInvalidType(true);
2034 }
Eli Friedman8ac2c662011-11-11 02:00:42 +00002035 T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals,
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002036 SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
Reid Spencer5f016e22007-07-11 17:01:13 +00002037 break;
2038 }
Sebastian Redlf30208a2009-01-24 21:16:55 +00002039 case DeclaratorChunk::Function: {
Reid Spencer5f016e22007-07-11 17:01:13 +00002040 // If the function declarator has a prototype (i.e. it is not () and
2041 // does not have a K&R-style identifier list), then the arguments are part
2042 // of the type, otherwise the argument list is ().
2043 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
Sebastian Redl3cc97262009-05-31 11:47:27 +00002044
Richard Smithe7397c62011-02-22 00:36:53 +00002045 // Check for auto functions and trailing return type and adjust the
2046 // return type accordingly.
2047 if (!D.isInvalidType()) {
2048 // trailing-return-type is only required if we're declaring a function,
2049 // and not, for instance, a pointer to a function.
2050 if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto &&
2051 !FTI.TrailingReturnType && chunkIndex == 0) {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002052 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
Richard Smithe7397c62011-02-22 00:36:53 +00002053 diag::err_auto_missing_trailing_return);
2054 T = Context.IntTy;
2055 D.setInvalidType(true);
2056 } else if (FTI.TrailingReturnType) {
2057 // T must be exactly 'auto' at this point. See CWG issue 681.
2058 if (isa<ParenType>(T)) {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002059 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
Richard Smithe7397c62011-02-22 00:36:53 +00002060 diag::err_trailing_return_in_parens)
2061 << T << D.getDeclSpec().getSourceRange();
2062 D.setInvalidType(true);
2063 } else if (T.hasQualifiers() || !isa<AutoType>(T)) {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002064 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
Richard Smithe7397c62011-02-22 00:36:53 +00002065 diag::err_trailing_return_without_auto)
2066 << T << D.getDeclSpec().getSourceRange();
2067 D.setInvalidType(true);
2068 }
2069
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002070 T = S.GetTypeFromParser(
Richard Smithe7397c62011-02-22 00:36:53 +00002071 ParsedType::getFromOpaquePtr(FTI.TrailingReturnType),
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002072 &TInfo);
Richard Smithe7397c62011-02-22 00:36:53 +00002073 }
2074 }
2075
Chris Lattnercd881292007-12-19 05:31:29 +00002076 // C99 6.7.5.3p1: The return type may not be a function or array type.
Douglas Gregor58408bc2010-01-11 18:46:21 +00002077 // For conversion functions, we'll diagnose this particular error later.
Douglas Gregor48026d22010-01-11 18:40:55 +00002078 if ((T->isArrayType() || T->isFunctionType()) &&
2079 (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId)) {
Argyrios Kyrtzidis98650442011-01-25 23:16:33 +00002080 unsigned diagID = diag::err_func_returning_array_function;
Argyrios Kyrtzidisa4356ad2011-01-26 01:26:44 +00002081 // Last processing chunk in block context means this function chunk
2082 // represents the block.
2083 if (chunkIndex == 0 &&
2084 D.getContext() == Declarator::BlockLiteralContext)
Argyrios Kyrtzidis98650442011-01-25 23:16:33 +00002085 diagID = diag::err_block_returning_array_function;
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002086 S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T;
Chris Lattnercd881292007-12-19 05:31:29 +00002087 T = Context.IntTy;
2088 D.setInvalidType(true);
2089 }
Sebastian Redl465226e2009-05-27 22:11:52 +00002090
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00002091 // Do not allow returning half FP value.
2092 // FIXME: This really should be in BuildFunctionType.
2093 if (T->isHalfType()) {
2094 S.Diag(D.getIdentifierLoc(),
2095 diag::err_parameters_retval_cannot_have_fp16_type) << 1
2096 << FixItHint::CreateInsertion(D.getIdentifierLoc(), "*");
2097 D.setInvalidType(true);
2098 }
2099
Douglas Gregor5291c3c2010-07-13 08:18:22 +00002100 // cv-qualifiers on return types are pointless except when the type is a
2101 // class type in C++.
Douglas Gregorfff95132011-03-01 17:04:42 +00002102 if (isa<PointerType>(T) && T.getLocalCVRQualifiers() &&
Rafael Espindola1e153942011-03-11 04:56:58 +00002103 (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId) &&
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002104 (!LangOpts.CPlusPlus || !T->isDependentType())) {
Chandler Carruthd067c072011-02-23 18:51:59 +00002105 assert(chunkIndex + 1 < e && "No DeclaratorChunk for the return type?");
2106 DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1);
2107 assert(ReturnTypeChunk.Kind == DeclaratorChunk::Pointer);
2108
2109 DeclaratorChunk::PointerTypeInfo &PTI = ReturnTypeChunk.Ptr;
2110
2111 DiagnoseIgnoredQualifiers(PTI.TypeQuals,
2112 SourceLocation::getFromRawEncoding(PTI.ConstQualLoc),
2113 SourceLocation::getFromRawEncoding(PTI.VolatileQualLoc),
2114 SourceLocation::getFromRawEncoding(PTI.RestrictQualLoc),
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002115 S);
Chandler Carruthd067c072011-02-23 18:51:59 +00002116
2117 } else if (T.getCVRQualifiers() && D.getDeclSpec().getTypeQualifiers() &&
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002118 (!LangOpts.CPlusPlus ||
Douglas Gregor5291c3c2010-07-13 08:18:22 +00002119 (!T->isDependentType() && !T->isRecordType()))) {
Chandler Carruthd067c072011-02-23 18:51:59 +00002120
2121 DiagnoseIgnoredQualifiers(D.getDeclSpec().getTypeQualifiers(),
2122 D.getDeclSpec().getConstSpecLoc(),
2123 D.getDeclSpec().getVolatileSpecLoc(),
2124 D.getDeclSpec().getRestrictSpecLoc(),
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002125 S);
Douglas Gregor5291c3c2010-07-13 08:18:22 +00002126 }
Chandler Carruthd067c072011-02-23 18:51:59 +00002127
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002128 if (LangOpts.CPlusPlus && D.getDeclSpec().isTypeSpecOwned()) {
Douglas Gregor402abb52009-05-28 23:31:59 +00002129 // C++ [dcl.fct]p6:
2130 // Types shall not be defined in return or parameter types.
John McCallb3d87482010-08-24 05:47:05 +00002131 TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
John McCall5e1cdac2011-10-07 06:10:15 +00002132 if (Tag->isCompleteDefinition())
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002133 S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
Douglas Gregor402abb52009-05-28 23:31:59 +00002134 << Context.getTypeDeclType(Tag);
2135 }
2136
Sebastian Redl3cc97262009-05-31 11:47:27 +00002137 // Exception specs are not allowed in typedefs. Complain, but add it
2138 // anyway.
Richard Smith162e1c12011-04-15 14:24:37 +00002139 if (IsTypedefName && FTI.getExceptionSpecType())
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002140 S.Diag(FTI.getExceptionSpecLoc(), diag::err_exception_spec_in_typedef)
Richard Smith3e4c6c42011-05-05 21:57:07 +00002141 << (D.getContext() == Declarator::AliasDeclContext ||
2142 D.getContext() == Declarator::AliasTemplateContext);
Sebastian Redl3cc97262009-05-31 11:47:27 +00002143
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002144 if (!FTI.NumArgs && !FTI.isVariadic && !LangOpts.CPlusPlus) {
John McCall28654742010-06-05 06:41:15 +00002145 // Simple void foo(), where the incoming T is the result type.
2146 T = Context.getFunctionNoProtoType(T);
2147 } else {
2148 // We allow a zero-parameter variadic function in C if the
2149 // function is marked with the "overloadable" attribute. Scan
2150 // for this attribute now.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002151 if (!FTI.NumArgs && FTI.isVariadic && !LangOpts.CPlusPlus) {
Douglas Gregor965acbb2009-02-18 07:07:28 +00002152 bool Overloadable = false;
2153 for (const AttributeList *Attrs = D.getAttributes();
2154 Attrs; Attrs = Attrs->getNext()) {
2155 if (Attrs->getKind() == AttributeList::AT_overloadable) {
2156 Overloadable = true;
2157 break;
2158 }
2159 }
2160
2161 if (!Overloadable)
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002162 S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_arg);
Argyrios Kyrtzidisc6f73452008-10-16 17:31:08 +00002163 }
John McCall28654742010-06-05 06:41:15 +00002164
2165 if (FTI.NumArgs && FTI.ArgInfo[0].Param == 0) {
Chris Lattner788b0fd2010-06-23 06:00:24 +00002166 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function
2167 // definition.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002168 S.Diag(FTI.ArgInfo[0].IdentLoc, diag::err_ident_list_in_fn_declaration);
John McCall28654742010-06-05 06:41:15 +00002169 D.setInvalidType(true);
2170 break;
2171 }
2172
John McCalle23cf432010-12-14 08:05:40 +00002173 FunctionProtoType::ExtProtoInfo EPI;
2174 EPI.Variadic = FTI.isVariadic;
2175 EPI.TypeQuals = FTI.TypeQuals;
Douglas Gregorc938c162011-01-26 05:01:58 +00002176 EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None
2177 : FTI.RefQualifierIsLValueRef? RQ_LValue
2178 : RQ_RValue;
2179
Reid Spencer5f016e22007-07-11 17:01:13 +00002180 // Otherwise, we have a function with an argument list that is
2181 // potentially variadic.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002182 SmallVector<QualType, 16> ArgTys;
John McCall28654742010-06-05 06:41:15 +00002183 ArgTys.reserve(FTI.NumArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002184
Chris Lattner5f9e2722011-07-23 10:55:15 +00002185 SmallVector<bool, 16> ConsumedArguments;
John McCallf85e1932011-06-15 23:02:42 +00002186 ConsumedArguments.reserve(FTI.NumArgs);
2187 bool HasAnyConsumedArguments = false;
2188
Reid Spencer5f016e22007-07-11 17:01:13 +00002189 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
John McCalld226f652010-08-21 09:40:31 +00002190 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
Chris Lattner8123a952008-04-10 02:22:51 +00002191 QualType ArgTy = Param->getType();
Chris Lattner78c75fb2007-07-21 05:30:18 +00002192 assert(!ArgTy.isNull() && "Couldn't parse type?");
Douglas Gregor2dc0e642009-03-23 23:06:20 +00002193
2194 // Adjust the parameter type.
Douglas Gregor79e6bd32011-07-12 04:42:08 +00002195 assert((ArgTy == Context.getAdjustedParameterType(ArgTy)) &&
2196 "Unadjusted type?");
Douglas Gregor2dc0e642009-03-23 23:06:20 +00002197
Reid Spencer5f016e22007-07-11 17:01:13 +00002198 // Look for 'void'. void is allowed only as a single argument to a
2199 // function with no other parameters (C99 6.7.5.3p10). We record
Douglas Gregor72564e72009-02-26 23:50:07 +00002200 // int(void) as a FunctionProtoType with an empty argument list.
Douglas Gregor2dc0e642009-03-23 23:06:20 +00002201 if (ArgTy->isVoidType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002202 // If this is something like 'float(int, void)', reject it. 'void'
2203 // is an incomplete type (C99 6.2.5p19) and function decls cannot
2204 // have arguments of incomplete type.
2205 if (FTI.NumArgs != 1 || FTI.isVariadic) {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002206 S.Diag(DeclType.Loc, diag::err_void_only_param);
Chris Lattner2ff54262007-07-21 05:18:12 +00002207 ArgTy = Context.IntTy;
Chris Lattner8123a952008-04-10 02:22:51 +00002208 Param->setType(ArgTy);
Chris Lattner2ff54262007-07-21 05:18:12 +00002209 } else if (FTI.ArgInfo[i].Ident) {
2210 // Reject, but continue to parse 'int(void abc)'.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002211 S.Diag(FTI.ArgInfo[i].IdentLoc,
Chris Lattner4565d4e2007-07-21 05:26:43 +00002212 diag::err_param_with_void_type);
Chris Lattner2ff54262007-07-21 05:18:12 +00002213 ArgTy = Context.IntTy;
Chris Lattner8123a952008-04-10 02:22:51 +00002214 Param->setType(ArgTy);
Chris Lattner2ff54262007-07-21 05:18:12 +00002215 } else {
2216 // Reject, but continue to parse 'float(const void)'.
John McCall0953e762009-09-24 19:53:00 +00002217 if (ArgTy.hasQualifiers())
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002218 S.Diag(DeclType.Loc, diag::err_void_param_qualified);
Mike Stump1eb44332009-09-09 15:08:12 +00002219
Chris Lattner2ff54262007-07-21 05:18:12 +00002220 // Do not add 'void' to the ArgTys list.
2221 break;
2222 }
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00002223 } else if (ArgTy->isHalfType()) {
2224 // Disallow half FP arguments.
2225 // FIXME: This really should be in BuildFunctionType.
2226 S.Diag(Param->getLocation(),
2227 diag::err_parameters_retval_cannot_have_fp16_type) << 0
2228 << FixItHint::CreateInsertion(Param->getLocation(), "*");
2229 D.setInvalidType();
Eli Friedmaneb4b7052008-08-25 21:31:01 +00002230 } else if (!FTI.hasPrototype) {
2231 if (ArgTy->isPromotableIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00002232 ArgTy = Context.getPromotedIntegerType(ArgTy);
John McCalleecf5fa2011-03-09 04:22:44 +00002233 Param->setKNRPromoted(true);
John McCall183700f2009-09-21 23:43:11 +00002234 } else if (const BuiltinType* BTy = ArgTy->getAs<BuiltinType>()) {
John McCalleecf5fa2011-03-09 04:22:44 +00002235 if (BTy->getKind() == BuiltinType::Float) {
Eli Friedmaneb4b7052008-08-25 21:31:01 +00002236 ArgTy = Context.DoubleTy;
John McCalleecf5fa2011-03-09 04:22:44 +00002237 Param->setKNRPromoted(true);
2238 }
Eli Friedmaneb4b7052008-08-25 21:31:01 +00002239 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002240 }
Fariborz Jahanian56a965c2010-09-08 21:36:35 +00002241
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002242 if (LangOpts.ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00002243 bool Consumed = Param->hasAttr<NSConsumedAttr>();
2244 ConsumedArguments.push_back(Consumed);
2245 HasAnyConsumedArguments |= Consumed;
2246 }
2247
John McCall54e14c42009-10-22 22:37:11 +00002248 ArgTys.push_back(ArgTy);
Reid Spencer5f016e22007-07-11 17:01:13 +00002249 }
Sebastian Redl465226e2009-05-27 22:11:52 +00002250
John McCallf85e1932011-06-15 23:02:42 +00002251 if (HasAnyConsumedArguments)
2252 EPI.ConsumedArguments = ConsumedArguments.data();
2253
Chris Lattner5f9e2722011-07-23 10:55:15 +00002254 SmallVector<QualType, 4> Exceptions;
Sebastian Redl8b5b4092011-03-06 10:52:04 +00002255 EPI.ExceptionSpecType = FTI.getExceptionSpecType();
2256 if (FTI.getExceptionSpecType() == EST_Dynamic) {
John McCalle23cf432010-12-14 08:05:40 +00002257 Exceptions.reserve(FTI.NumExceptions);
2258 for (unsigned ei = 0, ee = FTI.NumExceptions; ei != ee; ++ei) {
2259 // FIXME: Preserve type source info.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002260 QualType ET = S.GetTypeFromParser(FTI.Exceptions[ei].Ty);
John McCalle23cf432010-12-14 08:05:40 +00002261 // Check that the type is valid for an exception spec, and
2262 // drop it if not.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002263 if (!S.CheckSpecifiedExceptionType(ET, FTI.Exceptions[ei].Range))
John McCalle23cf432010-12-14 08:05:40 +00002264 Exceptions.push_back(ET);
2265 }
John McCall373920b2010-12-14 16:45:57 +00002266 EPI.NumExceptions = Exceptions.size();
John McCalle23cf432010-12-14 08:05:40 +00002267 EPI.Exceptions = Exceptions.data();
Sebastian Redl8b5b4092011-03-06 10:52:04 +00002268 } else if (FTI.getExceptionSpecType() == EST_ComputedNoexcept) {
Sebastian Redl60618fa2011-03-12 11:50:43 +00002269 // If an error occurred, there's no expression here.
2270 if (Expr *NoexceptExpr = FTI.NoexceptExpr) {
2271 assert((NoexceptExpr->isTypeDependent() ||
2272 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
2273 Context.BoolTy) &&
2274 "Parser should have made sure that the expression is boolean");
2275 SourceLocation ErrLoc;
2276 llvm::APSInt Dummy;
2277 if (!NoexceptExpr->isValueDependent() &&
2278 !NoexceptExpr->isIntegerConstantExpr(Dummy, Context, &ErrLoc,
2279 /*evaluated*/false))
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002280 S.Diag(ErrLoc, diag::err_noexcept_needs_constant_expression)
Sebastian Redl60618fa2011-03-12 11:50:43 +00002281 << NoexceptExpr->getSourceRange();
2282 else
2283 EPI.NoexceptExpr = NoexceptExpr;
2284 }
Sebastian Redl8999fe12011-03-14 18:08:30 +00002285 } else if (FTI.getExceptionSpecType() == EST_None &&
2286 ImplicitlyNoexcept && chunkIndex == 0) {
2287 // Only the outermost chunk is marked noexcept, of course.
2288 EPI.ExceptionSpecType = EST_BasicNoexcept;
Sebastian Redlef65f062009-05-29 18:02:33 +00002289 }
Sebastian Redl465226e2009-05-27 22:11:52 +00002290
John McCalle23cf432010-12-14 08:05:40 +00002291 T = Context.getFunctionType(T, ArgTys.data(), ArgTys.size(), EPI);
Reid Spencer5f016e22007-07-11 17:01:13 +00002292 }
John McCall04a67a62010-02-05 21:31:56 +00002293
Reid Spencer5f016e22007-07-11 17:01:13 +00002294 break;
2295 }
Sebastian Redlf30208a2009-01-24 21:16:55 +00002296 case DeclaratorChunk::MemberPointer:
2297 // The scope spec must refer to a class, or be dependent.
Abramo Bagnara7bd06762010-08-13 12:56:25 +00002298 CXXScopeSpec &SS = DeclType.Mem.Scope();
Sebastian Redlf30208a2009-01-24 21:16:55 +00002299 QualType ClsType;
Abramo Bagnara7bd06762010-08-13 12:56:25 +00002300 if (SS.isInvalid()) {
Jeffrey Yasskinedc28772010-04-07 23:29:58 +00002301 // Avoid emitting extra errors if we already errored on the scope.
2302 D.setInvalidType(true);
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002303 } else if (S.isDependentScopeSpecifier(SS) ||
2304 dyn_cast_or_null<CXXRecordDecl>(S.computeDeclContext(SS))) {
Mike Stump1eb44332009-09-09 15:08:12 +00002305 NestedNameSpecifier *NNS
Abramo Bagnara7bd06762010-08-13 12:56:25 +00002306 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
Douglas Gregor87c12c42009-11-04 16:49:01 +00002307 NestedNameSpecifier *NNSPrefix = NNS->getPrefix();
2308 switch (NNS->getKind()) {
2309 case NestedNameSpecifier::Identifier:
Abramo Bagnara7bd06762010-08-13 12:56:25 +00002310 ClsType = Context.getDependentNameType(ETK_None, NNSPrefix,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002311 NNS->getAsIdentifier());
Douglas Gregor87c12c42009-11-04 16:49:01 +00002312 break;
2313
2314 case NestedNameSpecifier::Namespace:
Douglas Gregor14aba762011-02-24 02:36:08 +00002315 case NestedNameSpecifier::NamespaceAlias:
Douglas Gregor87c12c42009-11-04 16:49:01 +00002316 case NestedNameSpecifier::Global:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002317 llvm_unreachable("Nested-name-specifier must name a type");
Douglas Gregor87c12c42009-11-04 16:49:01 +00002318 break;
Abramo Bagnara7bd06762010-08-13 12:56:25 +00002319
Douglas Gregor87c12c42009-11-04 16:49:01 +00002320 case NestedNameSpecifier::TypeSpec:
2321 case NestedNameSpecifier::TypeSpecWithTemplate:
2322 ClsType = QualType(NNS->getAsType(), 0);
Abramo Bagnara91ce2c42011-03-10 10:18:27 +00002323 // Note: if the NNS has a prefix and ClsType is a nondependent
2324 // TemplateSpecializationType, then the NNS prefix is NOT included
2325 // in ClsType; hence we wrap ClsType into an ElaboratedType.
2326 // NOTE: in particular, no wrap occurs if ClsType already is an
2327 // Elaborated, DependentName, or DependentTemplateSpecialization.
2328 if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType()))
Abramo Bagnara7bd06762010-08-13 12:56:25 +00002329 ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType);
Douglas Gregor87c12c42009-11-04 16:49:01 +00002330 break;
2331 }
Sebastian Redlf30208a2009-01-24 21:16:55 +00002332 } else {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002333 S.Diag(DeclType.Mem.Scope().getBeginLoc(),
Douglas Gregor949bf692009-06-09 22:17:39 +00002334 diag::err_illegal_decl_mempointer_in_nonclass)
2335 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
2336 << DeclType.Mem.Scope().getRange();
Sebastian Redlf30208a2009-01-24 21:16:55 +00002337 D.setInvalidType(true);
Sebastian Redlf30208a2009-01-24 21:16:55 +00002338 }
2339
Douglas Gregor949bf692009-06-09 22:17:39 +00002340 if (!ClsType.isNull())
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002341 T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc, D.getIdentifier());
Douglas Gregor949bf692009-06-09 22:17:39 +00002342 if (T.isNull()) {
2343 T = Context.IntTy;
Sebastian Redlf30208a2009-01-24 21:16:55 +00002344 D.setInvalidType(true);
John McCall28654742010-06-05 06:41:15 +00002345 } else if (DeclType.Mem.TypeQuals) {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002346 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals);
Sebastian Redlf30208a2009-01-24 21:16:55 +00002347 }
Sebastian Redlf30208a2009-01-24 21:16:55 +00002348 break;
2349 }
2350
Douglas Gregorcd281c32009-02-28 00:25:32 +00002351 if (T.isNull()) {
2352 D.setInvalidType(true);
2353 T = Context.IntTy;
2354 }
2355
Chris Lattnerc9b346d2008-06-29 00:50:08 +00002356 // See if there are any attributes on this declarator chunk.
John McCall711c52b2011-01-05 12:14:39 +00002357 if (AttributeList *attrs = const_cast<AttributeList*>(DeclType.getAttrs()))
2358 processTypeAttrs(state, T, false, attrs);
Reid Spencer5f016e22007-07-11 17:01:13 +00002359 }
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00002360
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002361 if (LangOpts.CPlusPlus && T->isFunctionType()) {
John McCall183700f2009-09-21 23:43:11 +00002362 const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
Chris Lattner778ed742009-10-25 17:36:50 +00002363 assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00002364
Douglas Gregor708f3b82010-10-14 22:03:51 +00002365 // C++ 8.3.5p4:
2366 // A cv-qualifier-seq shall only be part of the function type
2367 // for a nonstatic member function, the function type to which a pointer
2368 // to member refers, or the top-level function type of a function typedef
2369 // declaration.
Douglas Gregor683a81f2011-01-31 16:09:46 +00002370 //
2371 // Core issue 547 also allows cv-qualifiers on function types that are
2372 // top-level template type arguments.
John McCall613ef3d2010-10-19 01:54:45 +00002373 bool FreeFunction;
2374 if (!D.getCXXScopeSpec().isSet()) {
2375 FreeFunction = (D.getContext() != Declarator::MemberContext ||
2376 D.getDeclSpec().isFriendSpecified());
2377 } else {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002378 DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec());
John McCall613ef3d2010-10-19 01:54:45 +00002379 FreeFunction = (DC && !DC->isRecord());
2380 }
2381
Richard Smith55dec862011-09-30 00:45:47 +00002382 // C++0x [dcl.constexpr]p8: A constexpr specifier for a non-static member
2383 // function that is not a constructor declares that function to be const.
2384 if (D.getDeclSpec().isConstexprSpecified() && !FreeFunction &&
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002385 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static &&
Richard Smith55dec862011-09-30 00:45:47 +00002386 D.getName().getKind() != UnqualifiedId::IK_ConstructorName &&
2387 D.getName().getKind() != UnqualifiedId::IK_ConstructorTemplateId &&
2388 !(FnTy->getTypeQuals() & DeclSpec::TQ_const)) {
2389 // Rebuild function type adding a 'const' qualifier.
2390 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
2391 EPI.TypeQuals |= DeclSpec::TQ_const;
2392 T = Context.getFunctionType(FnTy->getResultType(),
2393 FnTy->arg_type_begin(),
2394 FnTy->getNumArgs(), EPI);
2395 }
2396
Douglas Gregorc938c162011-01-26 05:01:58 +00002397 // C++0x [dcl.fct]p6:
2398 // A ref-qualifier shall only be part of the function type for a
2399 // non-static member function, the function type to which a pointer to
2400 // member refers, or the top-level function type of a function typedef
2401 // declaration.
2402 if ((FnTy->getTypeQuals() != 0 || FnTy->getRefQualifier()) &&
Douglas Gregor683a81f2011-01-31 16:09:46 +00002403 !(D.getContext() == Declarator::TemplateTypeArgContext &&
Richard Smith162e1c12011-04-15 14:24:37 +00002404 !D.isFunctionDeclarator()) && !IsTypedefName &&
Sebastian Redlc61bb202010-07-09 21:26:08 +00002405 (FreeFunction ||
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00002406 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)) {
Douglas Gregor683a81f2011-01-31 16:09:46 +00002407 if (D.getContext() == Declarator::TemplateTypeArgContext) {
2408 // Accept qualified function types as template type arguments as a GNU
2409 // extension. This is also the subject of C++ core issue 547.
2410 std::string Quals;
2411 if (FnTy->getTypeQuals() != 0)
2412 Quals = Qualifiers::fromCVRMask(FnTy->getTypeQuals()).getAsString();
2413
2414 switch (FnTy->getRefQualifier()) {
2415 case RQ_None:
2416 break;
2417
2418 case RQ_LValue:
2419 if (!Quals.empty())
2420 Quals += ' ';
2421 Quals += '&';
2422 break;
Douglas Gregorc938c162011-01-26 05:01:58 +00002423
Douglas Gregor683a81f2011-01-31 16:09:46 +00002424 case RQ_RValue:
2425 if (!Quals.empty())
2426 Quals += ' ';
2427 Quals += "&&";
2428 break;
Douglas Gregorc938c162011-01-26 05:01:58 +00002429 }
Douglas Gregor683a81f2011-01-31 16:09:46 +00002430
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002431 S.Diag(D.getIdentifierLoc(),
Douglas Gregor683a81f2011-01-31 16:09:46 +00002432 diag::ext_qualified_function_type_template_arg)
2433 << Quals;
2434 } else {
2435 if (FnTy->getTypeQuals() != 0) {
Douglas Gregor43f51032011-10-19 06:04:55 +00002436 if (D.isFunctionDeclarator()) {
2437 SourceRange Range = D.getIdentifierLoc();
2438 for (unsigned I = 0, N = D.getNumTypeObjects(); I != N; ++I) {
2439 const DeclaratorChunk &Chunk = D.getTypeObject(N-I-1);
2440 if (Chunk.Kind == DeclaratorChunk::Function &&
2441 Chunk.Fun.TypeQuals != 0) {
2442 switch (Chunk.Fun.TypeQuals) {
2443 case Qualifiers::Const:
2444 Range = Chunk.Fun.getConstQualifierLoc();
2445 break;
2446 case Qualifiers::Volatile:
2447 Range = Chunk.Fun.getVolatileQualifierLoc();
2448 break;
2449 case Qualifiers::Const | Qualifiers::Volatile: {
2450 SourceLocation CLoc = Chunk.Fun.getConstQualifierLoc();
2451 SourceLocation VLoc = Chunk.Fun.getVolatileQualifierLoc();
2452 if (S.getSourceManager()
2453 .isBeforeInTranslationUnit(CLoc, VLoc)) {
2454 Range = SourceRange(CLoc, VLoc);
2455 } else {
2456 Range = SourceRange(VLoc, CLoc);
2457 }
2458 }
2459 break;
2460 }
2461 break;
2462 }
2463 }
2464 S.Diag(Range.getBegin(), diag::err_invalid_qualified_function_type)
2465 << FixItHint::CreateRemoval(Range);
2466 } else
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002467 S.Diag(D.getIdentifierLoc(),
Douglas Gregor683a81f2011-01-31 16:09:46 +00002468 diag::err_invalid_qualified_typedef_function_type_use)
2469 << FreeFunction;
2470 }
2471
2472 if (FnTy->getRefQualifier()) {
2473 if (D.isFunctionDeclarator()) {
2474 SourceLocation Loc = D.getIdentifierLoc();
2475 for (unsigned I = 0, N = D.getNumTypeObjects(); I != N; ++I) {
2476 const DeclaratorChunk &Chunk = D.getTypeObject(N-I-1);
2477 if (Chunk.Kind == DeclaratorChunk::Function &&
2478 Chunk.Fun.hasRefQualifier()) {
2479 Loc = Chunk.Fun.getRefQualifierLoc();
2480 break;
2481 }
2482 }
2483
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002484 S.Diag(Loc, diag::err_invalid_ref_qualifier_function_type)
Douglas Gregor683a81f2011-01-31 16:09:46 +00002485 << (FnTy->getRefQualifier() == RQ_LValue)
2486 << FixItHint::CreateRemoval(Loc);
2487 } else {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002488 S.Diag(D.getIdentifierLoc(),
Douglas Gregor683a81f2011-01-31 16:09:46 +00002489 diag::err_invalid_ref_qualifier_typedef_function_type_use)
2490 << FreeFunction
2491 << (FnTy->getRefQualifier() == RQ_LValue);
2492 }
2493 }
2494
2495 // Strip the cv-qualifiers and ref-qualifiers from the type.
2496 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
2497 EPI.TypeQuals = 0;
2498 EPI.RefQualifier = RQ_None;
2499
2500 T = Context.getFunctionType(FnTy->getResultType(),
2501 FnTy->arg_type_begin(),
2502 FnTy->getNumArgs(), EPI);
Douglas Gregorc938c162011-01-26 05:01:58 +00002503 }
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00002504 }
2505 }
Mike Stump1eb44332009-09-09 15:08:12 +00002506
John McCall711c52b2011-01-05 12:14:39 +00002507 // Apply any undistributed attributes from the declarator.
2508 if (!T.isNull())
2509 if (AttributeList *attrs = D.getAttributes())
2510 processTypeAttrs(state, T, false, attrs);
2511
2512 // Diagnose any ignored type attributes.
2513 if (!T.isNull()) state.diagnoseIgnoredTypeAttrs(T);
2514
Peter Collingbourne148f1f72011-03-20 08:06:45 +00002515 // C++0x [dcl.constexpr]p9:
2516 // A constexpr specifier used in an object declaration declares the object
2517 // as const.
2518 if (D.getDeclSpec().isConstexprSpecified() && T->isObjectType()) {
Sebastian Redl73780122010-06-09 21:19:43 +00002519 T.addConst();
2520 }
2521
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002522 // If there was an ellipsis in the declarator, the declaration declares a
2523 // parameter pack whose type may be a pack expansion type.
2524 if (D.hasEllipsis() && !T.isNull()) {
2525 // C++0x [dcl.fct]p13:
2526 // A declarator-id or abstract-declarator containing an ellipsis shall
2527 // only be used in a parameter-declaration. Such a parameter-declaration
2528 // is a parameter pack (14.5.3). [...]
2529 switch (D.getContext()) {
2530 case Declarator::PrototypeContext:
2531 // C++0x [dcl.fct]p13:
2532 // [...] When it is part of a parameter-declaration-clause, the
2533 // parameter pack is a function parameter pack (14.5.3). The type T
2534 // of the declarator-id of the function parameter pack shall contain
2535 // a template parameter pack; each template parameter pack in T is
2536 // expanded by the function parameter pack.
2537 //
2538 // We represent function parameter packs as function parameters whose
2539 // type is a pack expansion.
2540 if (!T->containsUnexpandedParameterPack()) {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002541 S.Diag(D.getEllipsisLoc(),
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002542 diag::err_function_parameter_pack_without_parameter_packs)
2543 << T << D.getSourceRange();
2544 D.setEllipsisLoc(SourceLocation());
2545 } else {
Douglas Gregorcded4f62011-01-14 17:04:44 +00002546 T = Context.getPackExpansionType(T, llvm::Optional<unsigned>());
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002547 }
2548 break;
2549
2550 case Declarator::TemplateParamContext:
2551 // C++0x [temp.param]p15:
2552 // If a template-parameter is a [...] is a parameter-declaration that
2553 // declares a parameter pack (8.3.5), then the template-parameter is a
2554 // template parameter pack (14.5.3).
2555 //
2556 // Note: core issue 778 clarifies that, if there are any unexpanded
2557 // parameter packs in the type of the non-type template parameter, then
2558 // it expands those parameter packs.
2559 if (T->containsUnexpandedParameterPack())
Douglas Gregorcded4f62011-01-14 17:04:44 +00002560 T = Context.getPackExpansionType(T, llvm::Optional<unsigned>());
Richard Smithe5acd132011-10-14 20:31:37 +00002561 else
2562 S.Diag(D.getEllipsisLoc(),
2563 LangOpts.CPlusPlus0x
2564 ? diag::warn_cxx98_compat_variadic_templates
2565 : diag::ext_variadic_templates);
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002566 break;
2567
2568 case Declarator::FileContext:
2569 case Declarator::KNRTypeListContext:
John McCallcdda47f2011-10-01 09:56:14 +00002570 case Declarator::ObjCParameterContext: // FIXME: special diagnostic here?
2571 case Declarator::ObjCResultContext: // FIXME: special diagnostic here?
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002572 case Declarator::TypeNameContext:
Argyrios Kyrtzidis0b8c98f2011-06-28 03:01:23 +00002573 case Declarator::CXXNewContext:
Richard Smith162e1c12011-04-15 14:24:37 +00002574 case Declarator::AliasDeclContext:
Richard Smith3e4c6c42011-05-05 21:57:07 +00002575 case Declarator::AliasTemplateContext:
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002576 case Declarator::MemberContext:
2577 case Declarator::BlockContext:
2578 case Declarator::ForContext:
2579 case Declarator::ConditionContext:
2580 case Declarator::CXXCatchContext:
Argyrios Kyrtzidis17b63992011-07-01 22:22:40 +00002581 case Declarator::ObjCCatchContext:
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002582 case Declarator::BlockLiteralContext:
Douglas Gregor683a81f2011-01-31 16:09:46 +00002583 case Declarator::TemplateTypeArgContext:
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002584 // FIXME: We may want to allow parameter packs in block-literal contexts
2585 // in the future.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002586 S.Diag(D.getEllipsisLoc(), diag::err_ellipsis_in_declarator_not_parameter);
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002587 D.setEllipsisLoc(SourceLocation());
2588 break;
2589 }
2590 }
Richard Smithe7397c62011-02-22 00:36:53 +00002591
John McCallbf1a0282010-06-04 23:28:52 +00002592 if (T.isNull())
2593 return Context.getNullTypeSourceInfo();
2594 else if (D.isInvalidType())
2595 return Context.getTrivialTypeSourceInfo(T);
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +00002596
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002597 return S.GetTypeSourceInfoForDeclarator(D, T, TInfo);
2598}
2599
2600/// GetTypeForDeclarator - Convert the type for the specified
2601/// declarator to Type instances.
2602///
2603/// The result of this call will never be null, but the associated
2604/// type may be a null type if there's an unrecoverable error.
2605TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) {
2606 // Determine the type of the declarator. Not all forms of declarator
2607 // have a type.
2608
2609 TypeProcessingState state(*this, D);
2610
2611 TypeSourceInfo *ReturnTypeInfo = 0;
2612 QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
2613 if (T.isNull())
2614 return Context.getNullTypeSourceInfo();
2615
2616 if (D.isPrototypeContext() && getLangOptions().ObjCAutoRefCount)
2617 inferARCWriteback(state, T);
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +00002618
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002619 return GetFullTypeForDeclarator(state, T, ReturnTypeInfo);
Reid Spencer5f016e22007-07-11 17:01:13 +00002620}
2621
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00002622static void transferARCOwnershipToDeclSpec(Sema &S,
2623 QualType &declSpecTy,
2624 Qualifiers::ObjCLifetime ownership) {
2625 if (declSpecTy->isObjCRetainableType() &&
2626 declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) {
2627 Qualifiers qs;
2628 qs.addObjCLifetime(ownership);
2629 declSpecTy = S.Context.getQualifiedType(declSpecTy, qs);
2630 }
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00002631}
2632
2633static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
2634 Qualifiers::ObjCLifetime ownership,
2635 unsigned chunkIndex) {
2636 Sema &S = state.getSema();
2637 Declarator &D = state.getDeclarator();
2638
2639 // Look for an explicit lifetime attribute.
2640 DeclaratorChunk &chunk = D.getTypeObject(chunkIndex);
2641 for (const AttributeList *attr = chunk.getAttrs(); attr;
2642 attr = attr->getNext())
2643 if (attr->getKind() == AttributeList::AT_objc_ownership)
2644 return;
2645
2646 const char *attrStr = 0;
2647 switch (ownership) {
2648 case Qualifiers::OCL_None: llvm_unreachable("no ownership!"); break;
2649 case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break;
2650 case Qualifiers::OCL_Strong: attrStr = "strong"; break;
2651 case Qualifiers::OCL_Weak: attrStr = "weak"; break;
2652 case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break;
2653 }
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00002654
2655 // If there wasn't one, add one (with an invalid source location
2656 // so that we don't make an AttributedType for it).
2657 AttributeList *attr = D.getAttributePool()
2658 .create(&S.Context.Idents.get("objc_ownership"), SourceLocation(),
2659 /*scope*/ 0, SourceLocation(),
2660 &S.Context.Idents.get(attrStr), SourceLocation(),
2661 /*args*/ 0, 0,
2662 /*declspec*/ false, /*C++0x*/ false);
2663 spliceAttrIntoList(*attr, chunk.getAttrListRef());
2664
2665 // TODO: mark whether we did this inference?
2666}
2667
Argyrios Kyrtzidis6ee54922011-10-28 22:54:28 +00002668/// \brief Used for transfering ownership in casts resulting in l-values.
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00002669static void transferARCOwnership(TypeProcessingState &state,
2670 QualType &declSpecTy,
2671 Qualifiers::ObjCLifetime ownership) {
2672 Sema &S = state.getSema();
2673 Declarator &D = state.getDeclarator();
2674
2675 int inner = -1;
Argyrios Kyrtzidis6ee54922011-10-28 22:54:28 +00002676 bool hasIndirection = false;
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00002677 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
2678 DeclaratorChunk &chunk = D.getTypeObject(i);
2679 switch (chunk.Kind) {
2680 case DeclaratorChunk::Paren:
2681 // Ignore parens.
2682 break;
2683
2684 case DeclaratorChunk::Array:
2685 case DeclaratorChunk::Reference:
2686 case DeclaratorChunk::Pointer:
Argyrios Kyrtzidis6ee54922011-10-28 22:54:28 +00002687 if (inner != -1)
2688 hasIndirection = true;
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00002689 inner = i;
2690 break;
2691
2692 case DeclaratorChunk::BlockPointer:
Argyrios Kyrtzidis6ee54922011-10-28 22:54:28 +00002693 if (inner != -1)
2694 transferARCOwnershipToDeclaratorChunk(state, ownership, i);
2695 return;
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00002696
2697 case DeclaratorChunk::Function:
2698 case DeclaratorChunk::MemberPointer:
2699 return;
2700 }
2701 }
2702
2703 if (inner == -1)
Argyrios Kyrtzidis6ee54922011-10-28 22:54:28 +00002704 return;
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00002705
2706 DeclaratorChunk &chunk = D.getTypeObject(inner);
2707 if (chunk.Kind == DeclaratorChunk::Pointer) {
2708 if (declSpecTy->isObjCRetainableType())
2709 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
Argyrios Kyrtzidis6ee54922011-10-28 22:54:28 +00002710 if (declSpecTy->isObjCObjectType() && hasIndirection)
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00002711 return transferARCOwnershipToDeclaratorChunk(state, ownership, inner);
2712 } else {
2713 assert(chunk.Kind == DeclaratorChunk::Array ||
2714 chunk.Kind == DeclaratorChunk::Reference);
2715 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
2716 }
2717}
2718
2719TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) {
2720 TypeProcessingState state(*this, D);
2721
2722 TypeSourceInfo *ReturnTypeInfo = 0;
2723 QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
2724 if (declSpecTy.isNull())
2725 return Context.getNullTypeSourceInfo();
2726
2727 if (getLangOptions().ObjCAutoRefCount) {
2728 Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy);
2729 if (ownership != Qualifiers::OCL_None)
2730 transferARCOwnership(state, declSpecTy, ownership);
2731 }
2732
2733 return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo);
2734}
2735
John McCall14aa2172011-03-04 04:00:19 +00002736/// Map an AttributedType::Kind to an AttributeList::Kind.
2737static AttributeList::Kind getAttrListKind(AttributedType::Kind kind) {
2738 switch (kind) {
2739 case AttributedType::attr_address_space:
2740 return AttributeList::AT_address_space;
2741 case AttributedType::attr_regparm:
2742 return AttributeList::AT_regparm;
2743 case AttributedType::attr_vector_size:
2744 return AttributeList::AT_vector_size;
2745 case AttributedType::attr_neon_vector_type:
2746 return AttributeList::AT_neon_vector_type;
2747 case AttributedType::attr_neon_polyvector_type:
2748 return AttributeList::AT_neon_polyvector_type;
2749 case AttributedType::attr_objc_gc:
2750 return AttributeList::AT_objc_gc;
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00002751 case AttributedType::attr_objc_ownership:
2752 return AttributeList::AT_objc_ownership;
John McCall14aa2172011-03-04 04:00:19 +00002753 case AttributedType::attr_noreturn:
2754 return AttributeList::AT_noreturn;
2755 case AttributedType::attr_cdecl:
2756 return AttributeList::AT_cdecl;
2757 case AttributedType::attr_fastcall:
2758 return AttributeList::AT_fastcall;
2759 case AttributedType::attr_stdcall:
2760 return AttributeList::AT_stdcall;
2761 case AttributedType::attr_thiscall:
2762 return AttributeList::AT_thiscall;
2763 case AttributedType::attr_pascal:
2764 return AttributeList::AT_pascal;
Anton Korobeynikov414d8962011-04-14 20:06:49 +00002765 case AttributedType::attr_pcs:
2766 return AttributeList::AT_pcs;
John McCall14aa2172011-03-04 04:00:19 +00002767 }
2768 llvm_unreachable("unexpected attribute kind!");
2769 return AttributeList::Kind();
2770}
2771
2772static void fillAttributedTypeLoc(AttributedTypeLoc TL,
2773 const AttributeList *attrs) {
2774 AttributedType::Kind kind = TL.getAttrKind();
2775
2776 assert(attrs && "no type attributes in the expected location!");
2777 AttributeList::Kind parsedKind = getAttrListKind(kind);
2778 while (attrs->getKind() != parsedKind) {
2779 attrs = attrs->getNext();
2780 assert(attrs && "no matching attribute in expected location!");
2781 }
2782
2783 TL.setAttrNameLoc(attrs->getLoc());
2784 if (TL.hasAttrExprOperand())
2785 TL.setAttrExprOperand(attrs->getArg(0));
2786 else if (TL.hasAttrEnumOperand())
2787 TL.setAttrEnumOperandLoc(attrs->getParameterLoc());
2788
2789 // FIXME: preserve this information to here.
2790 if (TL.hasAttrOperand())
2791 TL.setAttrOperandParensRange(SourceRange());
2792}
2793
John McCall51bd8032009-10-18 01:05:36 +00002794namespace {
2795 class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
Douglas Gregorc21c7e92011-01-25 19:13:18 +00002796 ASTContext &Context;
John McCall51bd8032009-10-18 01:05:36 +00002797 const DeclSpec &DS;
Argyrios Kyrtzidisf352bdd2009-09-29 19:43:35 +00002798
John McCall51bd8032009-10-18 01:05:36 +00002799 public:
Douglas Gregorc21c7e92011-01-25 19:13:18 +00002800 TypeSpecLocFiller(ASTContext &Context, const DeclSpec &DS)
2801 : Context(Context), DS(DS) {}
Argyrios Kyrtzidisf352bdd2009-09-29 19:43:35 +00002802
John McCall14aa2172011-03-04 04:00:19 +00002803 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
2804 fillAttributedTypeLoc(TL, DS.getAttributes().getList());
2805 Visit(TL.getModifiedLoc());
2806 }
John McCall51bd8032009-10-18 01:05:36 +00002807 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
2808 Visit(TL.getUnqualifiedLoc());
2809 }
2810 void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
2811 TL.setNameLoc(DS.getTypeSpecTypeLoc());
2812 }
2813 void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
2814 TL.setNameLoc(DS.getTypeSpecTypeLoc());
John McCallc12c5bb2010-05-15 11:32:37 +00002815 }
2816 void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
2817 // Handle the base type, which might not have been written explicitly.
2818 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
2819 TL.setHasBaseTypeAsWritten(false);
Douglas Gregorc21c7e92011-01-25 19:13:18 +00002820 TL.getBaseLoc().initialize(Context, SourceLocation());
John McCallc12c5bb2010-05-15 11:32:37 +00002821 } else {
2822 TL.setHasBaseTypeAsWritten(true);
2823 Visit(TL.getBaseLoc());
2824 }
Argyrios Kyrtzidiseb667592009-09-29 19:45:22 +00002825
John McCallc12c5bb2010-05-15 11:32:37 +00002826 // Protocol qualifiers.
John McCall54e14c42009-10-22 22:37:11 +00002827 if (DS.getProtocolQualifiers()) {
2828 assert(TL.getNumProtocols() > 0);
2829 assert(TL.getNumProtocols() == DS.getNumProtocolQualifiers());
2830 TL.setLAngleLoc(DS.getProtocolLAngleLoc());
2831 TL.setRAngleLoc(DS.getSourceRange().getEnd());
2832 for (unsigned i = 0, e = DS.getNumProtocolQualifiers(); i != e; ++i)
2833 TL.setProtocolLoc(i, DS.getProtocolLocs()[i]);
2834 } else {
2835 assert(TL.getNumProtocols() == 0);
2836 TL.setLAngleLoc(SourceLocation());
2837 TL.setRAngleLoc(SourceLocation());
2838 }
2839 }
2840 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCall54e14c42009-10-22 22:37:11 +00002841 TL.setStarLoc(SourceLocation());
John McCallc12c5bb2010-05-15 11:32:37 +00002842 Visit(TL.getPointeeLoc());
John McCall51bd8032009-10-18 01:05:36 +00002843 }
John McCall833ca992009-10-29 08:12:44 +00002844 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
John McCalla93c9342009-12-07 02:54:59 +00002845 TypeSourceInfo *TInfo = 0;
John McCallb3d87482010-08-24 05:47:05 +00002846 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
John McCall833ca992009-10-29 08:12:44 +00002847
2848 // If we got no declarator info from previous Sema routines,
2849 // just fill with the typespec loc.
John McCalla93c9342009-12-07 02:54:59 +00002850 if (!TInfo) {
Abramo Bagnara0daaf322011-03-16 20:16:18 +00002851 TL.initialize(Context, DS.getTypeSpecTypeNameLoc());
John McCall833ca992009-10-29 08:12:44 +00002852 return;
2853 }
2854
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00002855 TypeLoc OldTL = TInfo->getTypeLoc();
2856 if (TInfo->getType()->getAs<ElaboratedType>()) {
2857 ElaboratedTypeLoc ElabTL = cast<ElaboratedTypeLoc>(OldTL);
2858 TemplateSpecializationTypeLoc NamedTL =
2859 cast<TemplateSpecializationTypeLoc>(ElabTL.getNamedTypeLoc());
2860 TL.copy(NamedTL);
2861 }
2862 else
2863 TL.copy(cast<TemplateSpecializationTypeLoc>(OldTL));
John McCall833ca992009-10-29 08:12:44 +00002864 }
John McCallcfb708c2010-01-13 20:03:27 +00002865 void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
2866 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr);
2867 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
2868 TL.setParensRange(DS.getTypeofParensRange());
2869 }
2870 void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
2871 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType);
2872 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
2873 TL.setParensRange(DS.getTypeofParensRange());
John McCallb3d87482010-08-24 05:47:05 +00002874 assert(DS.getRepAsType());
John McCallcfb708c2010-01-13 20:03:27 +00002875 TypeSourceInfo *TInfo = 0;
John McCallb3d87482010-08-24 05:47:05 +00002876 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
John McCallcfb708c2010-01-13 20:03:27 +00002877 TL.setUnderlyingTInfo(TInfo);
2878 }
Sean Huntca63c202011-05-24 22:41:36 +00002879 void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
2880 // FIXME: This holds only because we only have one unary transform.
2881 assert(DS.getTypeSpecType() == DeclSpec::TST_underlyingType);
2882 TL.setKWLoc(DS.getTypeSpecTypeLoc());
2883 TL.setParensRange(DS.getTypeofParensRange());
2884 assert(DS.getRepAsType());
2885 TypeSourceInfo *TInfo = 0;
2886 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
2887 TL.setUnderlyingTInfo(TInfo);
2888 }
Douglas Gregorddf889a2010-01-18 18:04:31 +00002889 void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
2890 // By default, use the source location of the type specifier.
2891 TL.setBuiltinLoc(DS.getTypeSpecTypeLoc());
2892 if (TL.needsExtraLocalData()) {
2893 // Set info for the written builtin specifiers.
2894 TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs();
2895 // Try to have a meaningful source location.
2896 if (TL.getWrittenSignSpec() != TSS_unspecified)
2897 // Sign spec loc overrides the others (e.g., 'unsigned long').
2898 TL.setBuiltinLoc(DS.getTypeSpecSignLoc());
2899 else if (TL.getWrittenWidthSpec() != TSW_unspecified)
2900 // Width spec loc overrides type spec loc (e.g., 'short int').
2901 TL.setBuiltinLoc(DS.getTypeSpecWidthLoc());
2902 }
2903 }
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00002904 void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
2905 ElaboratedTypeKeyword Keyword
2906 = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
Nico Weber253e80b2010-11-22 10:30:56 +00002907 if (DS.getTypeSpecType() == TST_typename) {
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00002908 TypeSourceInfo *TInfo = 0;
John McCallb3d87482010-08-24 05:47:05 +00002909 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00002910 if (TInfo) {
2911 TL.copy(cast<ElaboratedTypeLoc>(TInfo->getTypeLoc()));
2912 return;
2913 }
2914 }
2915 TL.setKeywordLoc(Keyword != ETK_None
2916 ? DS.getTypeSpecTypeLoc()
2917 : SourceLocation());
2918 const CXXScopeSpec& SS = DS.getTypeSpecScope();
Douglas Gregor9e876872011-03-01 18:12:44 +00002919 TL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00002920 Visit(TL.getNextTypeLoc().getUnqualifiedLoc());
2921 }
2922 void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
2923 ElaboratedTypeKeyword Keyword
2924 = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
Nico Weber253e80b2010-11-22 10:30:56 +00002925 if (DS.getTypeSpecType() == TST_typename) {
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00002926 TypeSourceInfo *TInfo = 0;
John McCallb3d87482010-08-24 05:47:05 +00002927 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00002928 if (TInfo) {
2929 TL.copy(cast<DependentNameTypeLoc>(TInfo->getTypeLoc()));
2930 return;
2931 }
2932 }
2933 TL.setKeywordLoc(Keyword != ETK_None
2934 ? DS.getTypeSpecTypeLoc()
2935 : SourceLocation());
2936 const CXXScopeSpec& SS = DS.getTypeSpecScope();
Douglas Gregor2494dd02011-03-01 01:34:45 +00002937 TL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnara0daaf322011-03-16 20:16:18 +00002938 TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00002939 }
John McCall33500952010-06-11 00:33:02 +00002940 void VisitDependentTemplateSpecializationTypeLoc(
2941 DependentTemplateSpecializationTypeLoc TL) {
2942 ElaboratedTypeKeyword Keyword
2943 = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
2944 if (Keyword == ETK_Typename) {
2945 TypeSourceInfo *TInfo = 0;
John McCallb3d87482010-08-24 05:47:05 +00002946 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
John McCall33500952010-06-11 00:33:02 +00002947 if (TInfo) {
2948 TL.copy(cast<DependentTemplateSpecializationTypeLoc>(
2949 TInfo->getTypeLoc()));
2950 return;
2951 }
2952 }
Douglas Gregorc21c7e92011-01-25 19:13:18 +00002953 TL.initializeLocal(Context, SourceLocation());
John McCall33500952010-06-11 00:33:02 +00002954 TL.setKeywordLoc(Keyword != ETK_None
2955 ? DS.getTypeSpecTypeLoc()
2956 : SourceLocation());
2957 const CXXScopeSpec& SS = DS.getTypeSpecScope();
Douglas Gregor94fdffa2011-03-01 20:11:18 +00002958 TL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnara0daaf322011-03-16 20:16:18 +00002959 TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
2960 }
2961 void VisitTagTypeLoc(TagTypeLoc TL) {
2962 TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
John McCall33500952010-06-11 00:33:02 +00002963 }
Eli Friedmanb001de72011-10-06 23:00:33 +00002964 void VisitAtomicTypeLoc(AtomicTypeLoc TL) {
2965 TL.setKWLoc(DS.getTypeSpecTypeLoc());
2966 TL.setParensRange(DS.getTypeofParensRange());
Douglas Gregor43fe2452011-10-09 18:45:17 +00002967
2968 TypeSourceInfo *TInfo = 0;
2969 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
2970 TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
Eli Friedmanb001de72011-10-06 23:00:33 +00002971 }
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00002972
John McCall51bd8032009-10-18 01:05:36 +00002973 void VisitTypeLoc(TypeLoc TL) {
2974 // FIXME: add other typespec types and change this to an assert.
Douglas Gregorc21c7e92011-01-25 19:13:18 +00002975 TL.initialize(Context, DS.getTypeSpecTypeLoc());
John McCall51bd8032009-10-18 01:05:36 +00002976 }
2977 };
Argyrios Kyrtzidisf352bdd2009-09-29 19:43:35 +00002978
John McCall51bd8032009-10-18 01:05:36 +00002979 class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
Abramo Bagnarab6ab6c12011-03-05 14:42:21 +00002980 ASTContext &Context;
John McCall51bd8032009-10-18 01:05:36 +00002981 const DeclaratorChunk &Chunk;
2982
2983 public:
Abramo Bagnarab6ab6c12011-03-05 14:42:21 +00002984 DeclaratorLocFiller(ASTContext &Context, const DeclaratorChunk &Chunk)
2985 : Context(Context), Chunk(Chunk) {}
John McCall51bd8032009-10-18 01:05:36 +00002986
2987 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002988 llvm_unreachable("qualified type locs not expected here!");
John McCall51bd8032009-10-18 01:05:36 +00002989 }
2990
John McCallf85e1932011-06-15 23:02:42 +00002991 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
2992 fillAttributedTypeLoc(TL, Chunk.getAttrs());
2993 }
John McCall51bd8032009-10-18 01:05:36 +00002994 void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
2995 assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
2996 TL.setCaretLoc(Chunk.Loc);
2997 }
2998 void VisitPointerTypeLoc(PointerTypeLoc TL) {
2999 assert(Chunk.Kind == DeclaratorChunk::Pointer);
3000 TL.setStarLoc(Chunk.Loc);
3001 }
3002 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
3003 assert(Chunk.Kind == DeclaratorChunk::Pointer);
3004 TL.setStarLoc(Chunk.Loc);
3005 }
3006 void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
3007 assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
Abramo Bagnarab6ab6c12011-03-05 14:42:21 +00003008 const CXXScopeSpec& SS = Chunk.Mem.Scope();
3009 NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context);
3010
3011 const Type* ClsTy = TL.getClass();
3012 QualType ClsQT = QualType(ClsTy, 0);
3013 TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0);
3014 // Now copy source location info into the type loc component.
3015 TypeLoc ClsTL = ClsTInfo->getTypeLoc();
3016 switch (NNSLoc.getNestedNameSpecifier()->getKind()) {
3017 case NestedNameSpecifier::Identifier:
3018 assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc");
3019 {
Abramo Bagnarafd9c42e2011-03-06 22:48:24 +00003020 DependentNameTypeLoc DNTLoc = cast<DependentNameTypeLoc>(ClsTL);
Abramo Bagnarab6ab6c12011-03-05 14:42:21 +00003021 DNTLoc.setKeywordLoc(SourceLocation());
3022 DNTLoc.setQualifierLoc(NNSLoc.getPrefix());
3023 DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc());
3024 }
3025 break;
3026
3027 case NestedNameSpecifier::TypeSpec:
3028 case NestedNameSpecifier::TypeSpecWithTemplate:
3029 if (isa<ElaboratedType>(ClsTy)) {
3030 ElaboratedTypeLoc ETLoc = *cast<ElaboratedTypeLoc>(&ClsTL);
3031 ETLoc.setKeywordLoc(SourceLocation());
3032 ETLoc.setQualifierLoc(NNSLoc.getPrefix());
3033 TypeLoc NamedTL = ETLoc.getNamedTypeLoc();
3034 NamedTL.initializeFullCopy(NNSLoc.getTypeLoc());
3035 } else {
3036 ClsTL.initializeFullCopy(NNSLoc.getTypeLoc());
3037 }
3038 break;
3039
3040 case NestedNameSpecifier::Namespace:
3041 case NestedNameSpecifier::NamespaceAlias:
3042 case NestedNameSpecifier::Global:
3043 llvm_unreachable("Nested-name-specifier must name a type");
3044 break;
3045 }
3046
3047 // Finally fill in MemberPointerLocInfo fields.
John McCall51bd8032009-10-18 01:05:36 +00003048 TL.setStarLoc(Chunk.Loc);
Abramo Bagnarab6ab6c12011-03-05 14:42:21 +00003049 TL.setClassTInfo(ClsTInfo);
John McCall51bd8032009-10-18 01:05:36 +00003050 }
3051 void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
3052 assert(Chunk.Kind == DeclaratorChunk::Reference);
John McCall54e14c42009-10-22 22:37:11 +00003053 // 'Amp' is misleading: this might have been originally
3054 /// spelled with AmpAmp.
John McCall51bd8032009-10-18 01:05:36 +00003055 TL.setAmpLoc(Chunk.Loc);
3056 }
3057 void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
3058 assert(Chunk.Kind == DeclaratorChunk::Reference);
3059 assert(!Chunk.Ref.LValueRef);
3060 TL.setAmpAmpLoc(Chunk.Loc);
3061 }
3062 void VisitArrayTypeLoc(ArrayTypeLoc TL) {
3063 assert(Chunk.Kind == DeclaratorChunk::Array);
3064 TL.setLBracketLoc(Chunk.Loc);
3065 TL.setRBracketLoc(Chunk.EndLoc);
3066 TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
3067 }
3068 void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
3069 assert(Chunk.Kind == DeclaratorChunk::Function);
Abramo Bagnara796aa442011-03-12 11:17:06 +00003070 TL.setLocalRangeBegin(Chunk.Loc);
3071 TL.setLocalRangeEnd(Chunk.EndLoc);
Douglas Gregordab60ad2010-10-01 18:44:50 +00003072 TL.setTrailingReturn(!!Chunk.Fun.TrailingReturnType);
John McCall51bd8032009-10-18 01:05:36 +00003073
3074 const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
John McCall54e14c42009-10-22 22:37:11 +00003075 for (unsigned i = 0, e = TL.getNumArgs(), tpi = 0; i != e; ++i) {
John McCalld226f652010-08-21 09:40:31 +00003076 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
John McCall54e14c42009-10-22 22:37:11 +00003077 TL.setArg(tpi++, Param);
John McCall51bd8032009-10-18 01:05:36 +00003078 }
3079 // FIXME: exception specs
3080 }
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003081 void VisitParenTypeLoc(ParenTypeLoc TL) {
3082 assert(Chunk.Kind == DeclaratorChunk::Paren);
3083 TL.setLParenLoc(Chunk.Loc);
3084 TL.setRParenLoc(Chunk.EndLoc);
3085 }
John McCall51bd8032009-10-18 01:05:36 +00003086
3087 void VisitTypeLoc(TypeLoc TL) {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00003088 llvm_unreachable("unsupported TypeLoc kind in declarator!");
John McCall51bd8032009-10-18 01:05:36 +00003089 }
3090 };
Argyrios Kyrtzidisf352bdd2009-09-29 19:43:35 +00003091}
3092
John McCalla93c9342009-12-07 02:54:59 +00003093/// \brief Create and instantiate a TypeSourceInfo with type source information.
Argyrios Kyrtzidis4adab7f2009-08-19 01:28:06 +00003094///
3095/// \param T QualType referring to the type as written in source code.
Douglas Gregor05baacb2010-04-12 23:19:01 +00003096///
3097/// \param ReturnTypeInfo For declarators whose return type does not show
3098/// up in the normal place in the declaration specifiers (such as a C++
3099/// conversion function), this pointer will refer to a type source information
3100/// for that return type.
John McCalla93c9342009-12-07 02:54:59 +00003101TypeSourceInfo *
Douglas Gregor05baacb2010-04-12 23:19:01 +00003102Sema::GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
3103 TypeSourceInfo *ReturnTypeInfo) {
John McCalla93c9342009-12-07 02:54:59 +00003104 TypeSourceInfo *TInfo = Context.CreateTypeSourceInfo(T);
3105 UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc();
Argyrios Kyrtzidis4adab7f2009-08-19 01:28:06 +00003106
Douglas Gregora8bc8c92010-12-23 22:44:42 +00003107 // Handle parameter packs whose type is a pack expansion.
3108 if (isa<PackExpansionType>(T)) {
3109 cast<PackExpansionTypeLoc>(CurrTL).setEllipsisLoc(D.getEllipsisLoc());
3110 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
3111 }
3112
Sebastian Redl8ce35b02009-10-25 21:45:37 +00003113 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
John McCall14aa2172011-03-04 04:00:19 +00003114 while (isa<AttributedTypeLoc>(CurrTL)) {
3115 AttributedTypeLoc TL = cast<AttributedTypeLoc>(CurrTL);
3116 fillAttributedTypeLoc(TL, D.getTypeObject(i).getAttrs());
3117 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
3118 }
3119
Abramo Bagnarab6ab6c12011-03-05 14:42:21 +00003120 DeclaratorLocFiller(Context, D.getTypeObject(i)).Visit(CurrTL);
John McCall51bd8032009-10-18 01:05:36 +00003121 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
Argyrios Kyrtzidis4adab7f2009-08-19 01:28:06 +00003122 }
Argyrios Kyrtzidisf352bdd2009-09-29 19:43:35 +00003123
John McCallb3d87482010-08-24 05:47:05 +00003124 // If we have different source information for the return type, use
3125 // that. This really only applies to C++ conversion functions.
3126 if (ReturnTypeInfo) {
Douglas Gregor05baacb2010-04-12 23:19:01 +00003127 TypeLoc TL = ReturnTypeInfo->getTypeLoc();
3128 assert(TL.getFullDataSize() == CurrTL.getFullDataSize());
3129 memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize());
John McCallb3d87482010-08-24 05:47:05 +00003130 } else {
Douglas Gregorc21c7e92011-01-25 19:13:18 +00003131 TypeSpecLocFiller(Context, D.getDeclSpec()).Visit(CurrTL);
Douglas Gregor05baacb2010-04-12 23:19:01 +00003132 }
3133
John McCalla93c9342009-12-07 02:54:59 +00003134 return TInfo;
Argyrios Kyrtzidis4adab7f2009-08-19 01:28:06 +00003135}
3136
John McCalla93c9342009-12-07 02:54:59 +00003137/// \brief Create a LocInfoType to hold the given QualType and TypeSourceInfo.
John McCallb3d87482010-08-24 05:47:05 +00003138ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) {
Argyrios Kyrtzidis1bb8a452009-08-19 01:28:17 +00003139 // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
3140 // and Sema during declaration parsing. Try deallocating/caching them when
3141 // it's appropriate, instead of allocating them and keeping them around.
Douglas Gregoreb0eb492010-12-10 08:12:03 +00003142 LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType),
3143 TypeAlignment);
John McCalla93c9342009-12-07 02:54:59 +00003144 new (LocT) LocInfoType(T, TInfo);
Argyrios Kyrtzidis1bb8a452009-08-19 01:28:17 +00003145 assert(LocT->getTypeClass() != T->getTypeClass() &&
3146 "LocInfoType's TypeClass conflicts with an existing Type class");
John McCallb3d87482010-08-24 05:47:05 +00003147 return ParsedType::make(QualType(LocT, 0));
Argyrios Kyrtzidis1bb8a452009-08-19 01:28:17 +00003148}
3149
3150void LocInfoType::getAsStringInternal(std::string &Str,
3151 const PrintingPolicy &Policy) const {
David Blaikieb219cfc2011-09-23 05:06:16 +00003152 llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*"
Argyrios Kyrtzidis35d44e52009-08-19 01:46:06 +00003153 " was used directly instead of getting the QualType through"
3154 " GetTypeFromParser");
Argyrios Kyrtzidis1bb8a452009-08-19 01:28:17 +00003155}
3156
John McCallf312b1e2010-08-26 23:41:50 +00003157TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003158 // C99 6.7.6: Type names have no identifier. This is already validated by
3159 // the parser.
3160 assert(D.getIdentifier() == 0 && "Type name should have no identifier!");
Mike Stump1eb44332009-09-09 15:08:12 +00003161
Argyrios Kyrtzidisd3880f82011-06-28 03:01:18 +00003162 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCallbf1a0282010-06-04 23:28:52 +00003163 QualType T = TInfo->getType();
Chris Lattner5153ee62009-04-25 08:47:54 +00003164 if (D.isInvalidType())
Douglas Gregor809070a2009-02-18 17:45:20 +00003165 return true;
Steve Naroff5912a352007-08-28 20:14:24 +00003166
John McCalle82247a2011-10-01 05:17:03 +00003167 // Make sure there are no unused decl attributes on the declarator.
John McCallcdda47f2011-10-01 09:56:14 +00003168 // We don't want to do this for ObjC parameters because we're going
3169 // to apply them to the actual parameter declaration.
3170 if (D.getContext() != Declarator::ObjCParameterContext)
3171 checkUnusedDeclAttributes(D);
John McCalle82247a2011-10-01 05:17:03 +00003172
Douglas Gregor402abb52009-05-28 23:31:59 +00003173 if (getLangOptions().CPlusPlus) {
3174 // Check that there are no default arguments (C++ only).
Douglas Gregor6d6eb572008-05-07 04:49:29 +00003175 CheckExtraCXXDefaultArguments(D);
Douglas Gregor402abb52009-05-28 23:31:59 +00003176 }
3177
John McCallb3d87482010-08-24 05:47:05 +00003178 return CreateParsedType(T, TInfo);
Reid Spencer5f016e22007-07-11 17:01:13 +00003179}
3180
Douglas Gregore97179c2011-09-08 01:46:34 +00003181ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) {
3182 QualType T = Context.getObjCInstanceType();
3183 TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
3184 return CreateParsedType(T, TInfo);
3185}
3186
3187
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003188//===----------------------------------------------------------------------===//
3189// Type Attribute Processing
3190//===----------------------------------------------------------------------===//
3191
3192/// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
3193/// specified type. The attribute contains 1 argument, the id of the address
3194/// space for the type.
Mike Stump1eb44332009-09-09 15:08:12 +00003195static void HandleAddressSpaceTypeAttribute(QualType &Type,
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003196 const AttributeList &Attr, Sema &S){
John McCall0953e762009-09-24 19:53:00 +00003197
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003198 // If this type is already address space qualified, reject it.
Peter Collingbourne29e3ef82011-07-27 20:29:53 +00003199 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified by
3200 // qualifiers for two or more different address spaces."
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003201 if (Type.getAddressSpace()) {
3202 S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers);
Abramo Bagnarae215f722010-04-30 13:10:51 +00003203 Attr.setInvalid();
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003204 return;
3205 }
Mike Stump1eb44332009-09-09 15:08:12 +00003206
Peter Collingbourne020972d2011-07-27 20:30:05 +00003207 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be
3208 // qualified by an address-space qualifier."
3209 if (Type->isFunctionType()) {
3210 S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type);
3211 Attr.setInvalid();
3212 return;
3213 }
3214
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003215 // Check the attribute arguments.
3216 if (Attr.getNumArgs() != 1) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003217 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
Abramo Bagnarae215f722010-04-30 13:10:51 +00003218 Attr.setInvalid();
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003219 return;
3220 }
3221 Expr *ASArgExpr = static_cast<Expr *>(Attr.getArg(0));
3222 llvm::APSInt addrSpace(32);
Douglas Gregorac06a0e2010-05-18 23:01:22 +00003223 if (ASArgExpr->isTypeDependent() || ASArgExpr->isValueDependent() ||
3224 !ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003225 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_not_int)
3226 << ASArgExpr->getSourceRange();
Abramo Bagnarae215f722010-04-30 13:10:51 +00003227 Attr.setInvalid();
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003228 return;
3229 }
3230
John McCallefadb772009-07-28 06:52:18 +00003231 // Bounds checking.
3232 if (addrSpace.isSigned()) {
3233 if (addrSpace.isNegative()) {
3234 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_negative)
3235 << ASArgExpr->getSourceRange();
Abramo Bagnarae215f722010-04-30 13:10:51 +00003236 Attr.setInvalid();
John McCallefadb772009-07-28 06:52:18 +00003237 return;
3238 }
3239 addrSpace.setIsSigned(false);
3240 }
3241 llvm::APSInt max(addrSpace.getBitWidth());
John McCall0953e762009-09-24 19:53:00 +00003242 max = Qualifiers::MaxAddressSpace;
John McCallefadb772009-07-28 06:52:18 +00003243 if (addrSpace > max) {
3244 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_too_high)
John McCall0953e762009-09-24 19:53:00 +00003245 << Qualifiers::MaxAddressSpace << ASArgExpr->getSourceRange();
Abramo Bagnarae215f722010-04-30 13:10:51 +00003246 Attr.setInvalid();
John McCallefadb772009-07-28 06:52:18 +00003247 return;
3248 }
3249
Mike Stump1eb44332009-09-09 15:08:12 +00003250 unsigned ASIdx = static_cast<unsigned>(addrSpace.getZExtValue());
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00003251 Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003252}
3253
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00003254/// handleObjCOwnershipTypeAttr - Process an objc_ownership
John McCallf85e1932011-06-15 23:02:42 +00003255/// attribute on the specified type.
3256///
3257/// Returns 'true' if the attribute was handled.
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00003258static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
John McCallf85e1932011-06-15 23:02:42 +00003259 AttributeList &attr,
3260 QualType &type) {
Argyrios Kyrtzidise71202e2011-11-04 20:37:24 +00003261 bool NonObjCPointer = false;
3262
3263 if (!type->isDependentType()) {
3264 if (const PointerType *ptr = type->getAs<PointerType>()) {
3265 QualType pointee = ptr->getPointeeType();
3266 if (pointee->isObjCRetainableType() || pointee->isPointerType())
3267 return false;
3268 // It is important not to lose the source info that there was an attribute
3269 // applied to non-objc pointer. We will create an attributed type but
3270 // its type will be the same as the original type.
3271 NonObjCPointer = true;
3272 } else if (!type->isObjCRetainableType()) {
3273 return false;
3274 }
3275 }
John McCallf85e1932011-06-15 23:02:42 +00003276
3277 Sema &S = state.getSema();
Argyrios Kyrtzidis440ec2e2011-09-28 18:35:06 +00003278 SourceLocation AttrLoc = attr.getLoc();
3279 if (AttrLoc.isMacroID())
3280 AttrLoc = S.getSourceManager().getImmediateExpansionRange(AttrLoc).first;
John McCallf85e1932011-06-15 23:02:42 +00003281
3282 if (type.getQualifiers().getObjCLifetime()) {
Argyrios Kyrtzidis440ec2e2011-09-28 18:35:06 +00003283 S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant)
John McCallf85e1932011-06-15 23:02:42 +00003284 << type;
3285 return true;
3286 }
3287
3288 if (!attr.getParameterName()) {
Argyrios Kyrtzidis440ec2e2011-09-28 18:35:06 +00003289 S.Diag(AttrLoc, diag::err_attribute_argument_n_not_string)
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00003290 << "objc_ownership" << 1;
John McCallf85e1932011-06-15 23:02:42 +00003291 attr.setInvalid();
3292 return true;
3293 }
3294
3295 Qualifiers::ObjCLifetime lifetime;
3296 if (attr.getParameterName()->isStr("none"))
3297 lifetime = Qualifiers::OCL_ExplicitNone;
3298 else if (attr.getParameterName()->isStr("strong"))
3299 lifetime = Qualifiers::OCL_Strong;
3300 else if (attr.getParameterName()->isStr("weak"))
3301 lifetime = Qualifiers::OCL_Weak;
3302 else if (attr.getParameterName()->isStr("autoreleasing"))
3303 lifetime = Qualifiers::OCL_Autoreleasing;
3304 else {
Argyrios Kyrtzidis440ec2e2011-09-28 18:35:06 +00003305 S.Diag(AttrLoc, diag::warn_attribute_type_not_supported)
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00003306 << "objc_ownership" << attr.getParameterName();
John McCallf85e1932011-06-15 23:02:42 +00003307 attr.setInvalid();
3308 return true;
3309 }
3310
3311 // Consume lifetime attributes without further comment outside of
3312 // ARC mode.
3313 if (!S.getLangOptions().ObjCAutoRefCount)
3314 return true;
3315
Argyrios Kyrtzidise71202e2011-11-04 20:37:24 +00003316 if (NonObjCPointer) {
3317 StringRef name = attr.getName()->getName();
3318 switch (lifetime) {
3319 case Qualifiers::OCL_None:
3320 case Qualifiers::OCL_ExplicitNone:
3321 break;
3322 case Qualifiers::OCL_Strong: name = "__strong"; break;
3323 case Qualifiers::OCL_Weak: name = "__weak"; break;
3324 case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break;
3325 }
3326 S.Diag(AttrLoc, diag::warn_objc_object_attribute_wrong_type)
3327 << name << type;
3328 }
3329
John McCallf85e1932011-06-15 23:02:42 +00003330 Qualifiers qs;
3331 qs.setObjCLifetime(lifetime);
3332 QualType origType = type;
Argyrios Kyrtzidise71202e2011-11-04 20:37:24 +00003333 if (!NonObjCPointer)
3334 type = S.Context.getQualifiedType(type, qs);
John McCallf85e1932011-06-15 23:02:42 +00003335
3336 // If we have a valid source location for the attribute, use an
3337 // AttributedType instead.
Argyrios Kyrtzidis440ec2e2011-09-28 18:35:06 +00003338 if (AttrLoc.isValid())
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00003339 type = S.Context.getAttributedType(AttributedType::attr_objc_ownership,
John McCallf85e1932011-06-15 23:02:42 +00003340 origType, type);
3341
John McCall9f084a32011-07-06 00:26:06 +00003342 // Forbid __weak if the runtime doesn't support it.
John McCallf85e1932011-06-15 23:02:42 +00003343 if (lifetime == Qualifiers::OCL_Weak &&
Argyrios Kyrtzidis5cad8222011-11-07 18:40:21 +00003344 !S.getLangOptions().ObjCRuntimeHasWeak && !NonObjCPointer) {
John McCallf85e1932011-06-15 23:02:42 +00003345
3346 // Actually, delay this until we know what we're parsing.
3347 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
3348 S.DelayedDiagnostics.add(
Argyrios Kyrtzidis440ec2e2011-09-28 18:35:06 +00003349 sema::DelayedDiagnostic::makeForbiddenType(
3350 S.getSourceManager().getExpansionLoc(AttrLoc),
John McCallf85e1932011-06-15 23:02:42 +00003351 diag::err_arc_weak_no_runtime, type, /*ignored*/ 0));
3352 } else {
Argyrios Kyrtzidis440ec2e2011-09-28 18:35:06 +00003353 S.Diag(AttrLoc, diag::err_arc_weak_no_runtime);
John McCallf85e1932011-06-15 23:02:42 +00003354 }
3355
3356 attr.setInvalid();
3357 return true;
3358 }
Fariborz Jahanian742352a2011-07-06 19:24:05 +00003359
3360 // Forbid __weak for class objects marked as
3361 // objc_arc_weak_reference_unavailable
3362 if (lifetime == Qualifiers::OCL_Weak) {
3363 QualType T = type;
Fariborz Jahanian742352a2011-07-06 19:24:05 +00003364 while (const PointerType *ptr = T->getAs<PointerType>())
3365 T = ptr->getPointeeType();
3366 if (const ObjCObjectPointerType *ObjT = T->getAs<ObjCObjectPointerType>()) {
3367 ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl();
Fariborz Jahanian7263fee2011-07-06 20:48:48 +00003368 if (Class->isArcWeakrefUnavailable()) {
Argyrios Kyrtzidis440ec2e2011-09-28 18:35:06 +00003369 S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class);
Fariborz Jahanian742352a2011-07-06 19:24:05 +00003370 S.Diag(ObjT->getInterfaceDecl()->getLocation(),
3371 diag::note_class_declared);
Fariborz Jahanian742352a2011-07-06 19:24:05 +00003372 }
3373 }
3374 }
3375
John McCallf85e1932011-06-15 23:02:42 +00003376 return true;
3377}
3378
John McCall711c52b2011-01-05 12:14:39 +00003379/// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type
3380/// attribute on the specified type. Returns true to indicate that
3381/// the attribute was handled, false to indicate that the type does
3382/// not permit the attribute.
3383static bool handleObjCGCTypeAttr(TypeProcessingState &state,
3384 AttributeList &attr,
3385 QualType &type) {
3386 Sema &S = state.getSema();
3387
3388 // Delay if this isn't some kind of pointer.
3389 if (!type->isPointerType() &&
3390 !type->isObjCObjectPointerType() &&
3391 !type->isBlockPointerType())
3392 return false;
3393
3394 if (type.getObjCGCAttr() != Qualifiers::GCNone) {
3395 S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc);
3396 attr.setInvalid();
3397 return true;
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00003398 }
Mike Stump1eb44332009-09-09 15:08:12 +00003399
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00003400 // Check the attribute arguments.
John McCall711c52b2011-01-05 12:14:39 +00003401 if (!attr.getParameterName()) {
3402 S.Diag(attr.getLoc(), diag::err_attribute_argument_n_not_string)
Fariborz Jahanianba372b82009-02-18 17:52:36 +00003403 << "objc_gc" << 1;
John McCall711c52b2011-01-05 12:14:39 +00003404 attr.setInvalid();
3405 return true;
Fariborz Jahanianba372b82009-02-18 17:52:36 +00003406 }
John McCall0953e762009-09-24 19:53:00 +00003407 Qualifiers::GC GCAttr;
John McCall711c52b2011-01-05 12:14:39 +00003408 if (attr.getNumArgs() != 0) {
3409 S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
3410 attr.setInvalid();
3411 return true;
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00003412 }
John McCall711c52b2011-01-05 12:14:39 +00003413 if (attr.getParameterName()->isStr("weak"))
John McCall0953e762009-09-24 19:53:00 +00003414 GCAttr = Qualifiers::Weak;
John McCall711c52b2011-01-05 12:14:39 +00003415 else if (attr.getParameterName()->isStr("strong"))
John McCall0953e762009-09-24 19:53:00 +00003416 GCAttr = Qualifiers::Strong;
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00003417 else {
John McCall711c52b2011-01-05 12:14:39 +00003418 S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported)
3419 << "objc_gc" << attr.getParameterName();
3420 attr.setInvalid();
3421 return true;
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00003422 }
Mike Stump1eb44332009-09-09 15:08:12 +00003423
John McCall14aa2172011-03-04 04:00:19 +00003424 QualType origType = type;
3425 type = S.Context.getObjCGCQualType(origType, GCAttr);
3426
3427 // Make an attributed type to preserve the source information.
3428 if (attr.getLoc().isValid())
3429 type = S.Context.getAttributedType(AttributedType::attr_objc_gc,
3430 origType, type);
3431
John McCall711c52b2011-01-05 12:14:39 +00003432 return true;
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00003433}
3434
John McCalle6a365d2010-12-19 02:44:49 +00003435namespace {
3436 /// A helper class to unwrap a type down to a function for the
3437 /// purposes of applying attributes there.
3438 ///
3439 /// Use:
3440 /// FunctionTypeUnwrapper unwrapped(SemaRef, T);
3441 /// if (unwrapped.isFunctionType()) {
3442 /// const FunctionType *fn = unwrapped.get();
3443 /// // change fn somehow
3444 /// T = unwrapped.wrap(fn);
3445 /// }
3446 struct FunctionTypeUnwrapper {
3447 enum WrapKind {
3448 Desugar,
3449 Parens,
3450 Pointer,
3451 BlockPointer,
3452 Reference,
3453 MemberPointer
3454 };
3455
3456 QualType Original;
3457 const FunctionType *Fn;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003458 SmallVector<unsigned char /*WrapKind*/, 8> Stack;
John McCalle6a365d2010-12-19 02:44:49 +00003459
3460 FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) {
3461 while (true) {
3462 const Type *Ty = T.getTypePtr();
3463 if (isa<FunctionType>(Ty)) {
3464 Fn = cast<FunctionType>(Ty);
3465 return;
3466 } else if (isa<ParenType>(Ty)) {
3467 T = cast<ParenType>(Ty)->getInnerType();
3468 Stack.push_back(Parens);
3469 } else if (isa<PointerType>(Ty)) {
3470 T = cast<PointerType>(Ty)->getPointeeType();
3471 Stack.push_back(Pointer);
3472 } else if (isa<BlockPointerType>(Ty)) {
3473 T = cast<BlockPointerType>(Ty)->getPointeeType();
3474 Stack.push_back(BlockPointer);
3475 } else if (isa<MemberPointerType>(Ty)) {
3476 T = cast<MemberPointerType>(Ty)->getPointeeType();
3477 Stack.push_back(MemberPointer);
3478 } else if (isa<ReferenceType>(Ty)) {
3479 T = cast<ReferenceType>(Ty)->getPointeeType();
3480 Stack.push_back(Reference);
3481 } else {
3482 const Type *DTy = Ty->getUnqualifiedDesugaredType();
3483 if (Ty == DTy) {
3484 Fn = 0;
3485 return;
3486 }
3487
3488 T = QualType(DTy, 0);
3489 Stack.push_back(Desugar);
3490 }
3491 }
3492 }
3493
3494 bool isFunctionType() const { return (Fn != 0); }
3495 const FunctionType *get() const { return Fn; }
3496
3497 QualType wrap(Sema &S, const FunctionType *New) {
3498 // If T wasn't modified from the unwrapped type, do nothing.
3499 if (New == get()) return Original;
3500
3501 Fn = New;
3502 return wrap(S.Context, Original, 0);
3503 }
3504
3505 private:
3506 QualType wrap(ASTContext &C, QualType Old, unsigned I) {
3507 if (I == Stack.size())
3508 return C.getQualifiedType(Fn, Old.getQualifiers());
3509
3510 // Build up the inner type, applying the qualifiers from the old
3511 // type to the new type.
3512 SplitQualType SplitOld = Old.split();
3513
3514 // As a special case, tail-recurse if there are no qualifiers.
3515 if (SplitOld.second.empty())
3516 return wrap(C, SplitOld.first, I);
3517 return C.getQualifiedType(wrap(C, SplitOld.first, I), SplitOld.second);
3518 }
3519
3520 QualType wrap(ASTContext &C, const Type *Old, unsigned I) {
3521 if (I == Stack.size()) return QualType(Fn, 0);
3522
3523 switch (static_cast<WrapKind>(Stack[I++])) {
3524 case Desugar:
3525 // This is the point at which we potentially lose source
3526 // information.
3527 return wrap(C, Old->getUnqualifiedDesugaredType(), I);
3528
3529 case Parens: {
3530 QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I);
3531 return C.getParenType(New);
3532 }
3533
3534 case Pointer: {
3535 QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I);
3536 return C.getPointerType(New);
3537 }
3538
3539 case BlockPointer: {
3540 QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I);
3541 return C.getBlockPointerType(New);
3542 }
3543
3544 case MemberPointer: {
3545 const MemberPointerType *OldMPT = cast<MemberPointerType>(Old);
3546 QualType New = wrap(C, OldMPT->getPointeeType(), I);
3547 return C.getMemberPointerType(New, OldMPT->getClass());
3548 }
3549
3550 case Reference: {
3551 const ReferenceType *OldRef = cast<ReferenceType>(Old);
3552 QualType New = wrap(C, OldRef->getPointeeType(), I);
3553 if (isa<LValueReferenceType>(OldRef))
3554 return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue());
3555 else
3556 return C.getRValueReferenceType(New);
3557 }
3558 }
3559
3560 llvm_unreachable("unknown wrapping kind");
3561 return QualType();
3562 }
3563 };
3564}
3565
John McCall711c52b2011-01-05 12:14:39 +00003566/// Process an individual function attribute. Returns true to
3567/// indicate that the attribute was handled, false if it wasn't.
3568static bool handleFunctionTypeAttr(TypeProcessingState &state,
3569 AttributeList &attr,
3570 QualType &type) {
3571 Sema &S = state.getSema();
John McCalle6a365d2010-12-19 02:44:49 +00003572
John McCall711c52b2011-01-05 12:14:39 +00003573 FunctionTypeUnwrapper unwrapped(S, type);
Mike Stump24556362009-07-25 21:26:53 +00003574
John McCall711c52b2011-01-05 12:14:39 +00003575 if (attr.getKind() == AttributeList::AT_noreturn) {
3576 if (S.CheckNoReturnAttr(attr))
John McCall04a67a62010-02-05 21:31:56 +00003577 return true;
John McCalle6a365d2010-12-19 02:44:49 +00003578
John McCall711c52b2011-01-05 12:14:39 +00003579 // Delay if this is not a function type.
3580 if (!unwrapped.isFunctionType())
3581 return false;
3582
John McCall04a67a62010-02-05 21:31:56 +00003583 // Otherwise we can process right away.
John McCall711c52b2011-01-05 12:14:39 +00003584 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true);
3585 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
3586 return true;
John McCall04a67a62010-02-05 21:31:56 +00003587 }
Mike Stump24556362009-07-25 21:26:53 +00003588
John McCallf85e1932011-06-15 23:02:42 +00003589 // ns_returns_retained is not always a type attribute, but if we got
3590 // here, we're treating it as one right now.
3591 if (attr.getKind() == AttributeList::AT_ns_returns_retained) {
3592 assert(S.getLangOptions().ObjCAutoRefCount &&
3593 "ns_returns_retained treated as type attribute in non-ARC");
3594 if (attr.getNumArgs()) return true;
3595
3596 // Delay if this is not a function type.
3597 if (!unwrapped.isFunctionType())
3598 return false;
3599
3600 FunctionType::ExtInfo EI
3601 = unwrapped.get()->getExtInfo().withProducesResult(true);
3602 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
3603 return true;
3604 }
3605
John McCall711c52b2011-01-05 12:14:39 +00003606 if (attr.getKind() == AttributeList::AT_regparm) {
3607 unsigned value;
3608 if (S.CheckRegparmAttr(attr, value))
Rafael Espindola425ef722010-03-30 22:15:11 +00003609 return true;
3610
John McCall711c52b2011-01-05 12:14:39 +00003611 // Delay if this is not a function type.
3612 if (!unwrapped.isFunctionType())
Rafael Espindola425ef722010-03-30 22:15:11 +00003613 return false;
3614
Argyrios Kyrtzidisce955662011-01-25 23:16:40 +00003615 // Diagnose regparm with fastcall.
3616 const FunctionType *fn = unwrapped.get();
3617 CallingConv CC = fn->getCallConv();
3618 if (CC == CC_X86FastCall) {
3619 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
3620 << FunctionType::getNameForCallConv(CC)
3621 << "regparm";
3622 attr.setInvalid();
3623 return true;
3624 }
3625
John McCalle6a365d2010-12-19 02:44:49 +00003626 FunctionType::ExtInfo EI =
John McCall711c52b2011-01-05 12:14:39 +00003627 unwrapped.get()->getExtInfo().withRegParm(value);
3628 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
3629 return true;
Rafael Espindola425ef722010-03-30 22:15:11 +00003630 }
3631
John McCall04a67a62010-02-05 21:31:56 +00003632 // Otherwise, a calling convention.
John McCall711c52b2011-01-05 12:14:39 +00003633 CallingConv CC;
3634 if (S.CheckCallingConvAttr(attr, CC))
3635 return true;
John McCallf82b4e82010-02-04 05:44:44 +00003636
John McCall04a67a62010-02-05 21:31:56 +00003637 // Delay if the type didn't work out to a function.
John McCall711c52b2011-01-05 12:14:39 +00003638 if (!unwrapped.isFunctionType()) return false;
John McCall04a67a62010-02-05 21:31:56 +00003639
John McCall711c52b2011-01-05 12:14:39 +00003640 const FunctionType *fn = unwrapped.get();
3641 CallingConv CCOld = fn->getCallConv();
Charles Davis064f7db2010-02-23 06:13:55 +00003642 if (S.Context.getCanonicalCallConv(CC) ==
Abramo Bagnarae215f722010-04-30 13:10:51 +00003643 S.Context.getCanonicalCallConv(CCOld)) {
Argyrios Kyrtzidisce955662011-01-25 23:16:40 +00003644 FunctionType::ExtInfo EI= unwrapped.get()->getExtInfo().withCallingConv(CC);
3645 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
John McCall711c52b2011-01-05 12:14:39 +00003646 return true;
Abramo Bagnarae215f722010-04-30 13:10:51 +00003647 }
John McCall04a67a62010-02-05 21:31:56 +00003648
Roman Divacky8e68f1c2011-08-05 16:37:22 +00003649 if (CCOld != (S.LangOpts.MRTD ? CC_X86StdCall : CC_Default)) {
John McCall04a67a62010-02-05 21:31:56 +00003650 // Should we diagnose reapplications of the same convention?
John McCall711c52b2011-01-05 12:14:39 +00003651 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
John McCall04a67a62010-02-05 21:31:56 +00003652 << FunctionType::getNameForCallConv(CC)
3653 << FunctionType::getNameForCallConv(CCOld);
John McCall711c52b2011-01-05 12:14:39 +00003654 attr.setInvalid();
3655 return true;
John McCall04a67a62010-02-05 21:31:56 +00003656 }
3657
3658 // Diagnose the use of X86 fastcall on varargs or unprototyped functions.
3659 if (CC == CC_X86FastCall) {
John McCall711c52b2011-01-05 12:14:39 +00003660 if (isa<FunctionNoProtoType>(fn)) {
3661 S.Diag(attr.getLoc(), diag::err_cconv_knr)
John McCall04a67a62010-02-05 21:31:56 +00003662 << FunctionType::getNameForCallConv(CC);
John McCall711c52b2011-01-05 12:14:39 +00003663 attr.setInvalid();
3664 return true;
John McCall04a67a62010-02-05 21:31:56 +00003665 }
3666
John McCall711c52b2011-01-05 12:14:39 +00003667 const FunctionProtoType *FnP = cast<FunctionProtoType>(fn);
John McCall04a67a62010-02-05 21:31:56 +00003668 if (FnP->isVariadic()) {
John McCall711c52b2011-01-05 12:14:39 +00003669 S.Diag(attr.getLoc(), diag::err_cconv_varargs)
John McCall04a67a62010-02-05 21:31:56 +00003670 << FunctionType::getNameForCallConv(CC);
John McCall711c52b2011-01-05 12:14:39 +00003671 attr.setInvalid();
3672 return true;
John McCall04a67a62010-02-05 21:31:56 +00003673 }
Argyrios Kyrtzidisce955662011-01-25 23:16:40 +00003674
3675 // Also diagnose fastcall with regparm.
Eli Friedmana49218e2011-04-09 08:18:08 +00003676 if (fn->getHasRegParm()) {
Argyrios Kyrtzidisce955662011-01-25 23:16:40 +00003677 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
3678 << "regparm"
3679 << FunctionType::getNameForCallConv(CC);
3680 attr.setInvalid();
3681 return true;
3682 }
John McCall04a67a62010-02-05 21:31:56 +00003683 }
3684
John McCall711c52b2011-01-05 12:14:39 +00003685 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withCallingConv(CC);
3686 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
3687 return true;
John McCallf82b4e82010-02-04 05:44:44 +00003688}
3689
Peter Collingbourne207f4d82011-03-18 22:38:29 +00003690/// Handle OpenCL image access qualifiers: read_only, write_only, read_write
3691static void HandleOpenCLImageAccessAttribute(QualType& CurType,
3692 const AttributeList &Attr,
3693 Sema &S) {
3694 // Check the attribute arguments.
3695 if (Attr.getNumArgs() != 1) {
3696 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
3697 Attr.setInvalid();
3698 return;
3699 }
3700 Expr *sizeExpr = static_cast<Expr *>(Attr.getArg(0));
3701 llvm::APSInt arg(32);
3702 if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() ||
3703 !sizeExpr->isIntegerConstantExpr(arg, S.Context)) {
3704 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
3705 << "opencl_image_access" << sizeExpr->getSourceRange();
3706 Attr.setInvalid();
3707 return;
3708 }
3709 unsigned iarg = static_cast<unsigned>(arg.getZExtValue());
3710 switch (iarg) {
3711 case CLIA_read_only:
3712 case CLIA_write_only:
3713 case CLIA_read_write:
3714 // Implemented in a separate patch
3715 break;
3716 default:
3717 // Implemented in a separate patch
3718 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
3719 << sizeExpr->getSourceRange();
3720 Attr.setInvalid();
3721 break;
3722 }
3723}
3724
John Thompson6e132aa2009-12-04 21:51:28 +00003725/// HandleVectorSizeAttribute - this attribute is only applicable to integral
3726/// and float scalars, although arrays, pointers, and function return values are
3727/// allowed in conjunction with this construct. Aggregates with this attribute
3728/// are invalid, even if they are of the same size as a corresponding scalar.
3729/// The raw attribute should contain precisely 1 argument, the vector size for
3730/// the variable, measured in bytes. If curType and rawAttr are well formed,
3731/// this routine will return a new vector type.
Chris Lattner788b0fd2010-06-23 06:00:24 +00003732static void HandleVectorSizeAttr(QualType& CurType, const AttributeList &Attr,
3733 Sema &S) {
Bob Wilson56affbc2010-11-16 00:32:16 +00003734 // Check the attribute arguments.
John Thompson6e132aa2009-12-04 21:51:28 +00003735 if (Attr.getNumArgs() != 1) {
3736 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
Abramo Bagnarae215f722010-04-30 13:10:51 +00003737 Attr.setInvalid();
John Thompson6e132aa2009-12-04 21:51:28 +00003738 return;
3739 }
3740 Expr *sizeExpr = static_cast<Expr *>(Attr.getArg(0));
3741 llvm::APSInt vecSize(32);
Douglas Gregorac06a0e2010-05-18 23:01:22 +00003742 if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() ||
3743 !sizeExpr->isIntegerConstantExpr(vecSize, S.Context)) {
John Thompson6e132aa2009-12-04 21:51:28 +00003744 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
3745 << "vector_size" << sizeExpr->getSourceRange();
Abramo Bagnarae215f722010-04-30 13:10:51 +00003746 Attr.setInvalid();
John Thompson6e132aa2009-12-04 21:51:28 +00003747 return;
3748 }
3749 // the base type must be integer or float, and can't already be a vector.
Douglas Gregorf6094622010-07-23 15:58:24 +00003750 if (!CurType->isIntegerType() && !CurType->isRealFloatingType()) {
John Thompson6e132aa2009-12-04 21:51:28 +00003751 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
Abramo Bagnarae215f722010-04-30 13:10:51 +00003752 Attr.setInvalid();
John Thompson6e132aa2009-12-04 21:51:28 +00003753 return;
3754 }
3755 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
3756 // vecSize is specified in bytes - convert to bits.
3757 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
3758
3759 // the vector size needs to be an integral multiple of the type size.
3760 if (vectorSize % typeSize) {
3761 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
3762 << sizeExpr->getSourceRange();
Abramo Bagnarae215f722010-04-30 13:10:51 +00003763 Attr.setInvalid();
John Thompson6e132aa2009-12-04 21:51:28 +00003764 return;
3765 }
3766 if (vectorSize == 0) {
3767 S.Diag(Attr.getLoc(), diag::err_attribute_zero_size)
3768 << sizeExpr->getSourceRange();
Abramo Bagnarae215f722010-04-30 13:10:51 +00003769 Attr.setInvalid();
John Thompson6e132aa2009-12-04 21:51:28 +00003770 return;
3771 }
3772
3773 // Success! Instantiate the vector type, the number of elements is > 0, and
3774 // not required to be a power of 2, unlike GCC.
Chris Lattner788b0fd2010-06-23 06:00:24 +00003775 CurType = S.Context.getVectorType(CurType, vectorSize/typeSize,
Bob Wilsone86d78c2010-11-10 21:56:12 +00003776 VectorType::GenericVector);
John Thompson6e132aa2009-12-04 21:51:28 +00003777}
3778
Douglas Gregor4ac01402011-06-15 16:02:29 +00003779/// \brief Process the OpenCL-like ext_vector_type attribute when it occurs on
3780/// a type.
3781static void HandleExtVectorTypeAttr(QualType &CurType,
3782 const AttributeList &Attr,
3783 Sema &S) {
3784 Expr *sizeExpr;
3785
3786 // Special case where the argument is a template id.
3787 if (Attr.getParameterName()) {
3788 CXXScopeSpec SS;
3789 UnqualifiedId id;
3790 id.setIdentifier(Attr.getParameterName(), Attr.getLoc());
3791
3792 ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, id, false,
3793 false);
3794 if (Size.isInvalid())
3795 return;
3796
3797 sizeExpr = Size.get();
3798 } else {
3799 // check the attribute arguments.
3800 if (Attr.getNumArgs() != 1) {
3801 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
3802 return;
3803 }
3804 sizeExpr = Attr.getArg(0);
3805 }
3806
3807 // Create the vector type.
3808 QualType T = S.BuildExtVectorType(CurType, sizeExpr, Attr.getLoc());
3809 if (!T.isNull())
3810 CurType = T;
3811}
3812
Bob Wilson4211bb62010-11-16 00:32:24 +00003813/// HandleNeonVectorTypeAttr - The "neon_vector_type" and
3814/// "neon_polyvector_type" attributes are used to create vector types that
3815/// are mangled according to ARM's ABI. Otherwise, these types are identical
3816/// to those created with the "vector_size" attribute. Unlike "vector_size"
3817/// the argument to these Neon attributes is the number of vector elements,
3818/// not the vector size in bytes. The vector width and element type must
3819/// match one of the standard Neon vector types.
3820static void HandleNeonVectorTypeAttr(QualType& CurType,
3821 const AttributeList &Attr, Sema &S,
3822 VectorType::VectorKind VecKind,
3823 const char *AttrName) {
3824 // Check the attribute arguments.
3825 if (Attr.getNumArgs() != 1) {
3826 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
3827 Attr.setInvalid();
3828 return;
3829 }
3830 // The number of elements must be an ICE.
3831 Expr *numEltsExpr = static_cast<Expr *>(Attr.getArg(0));
3832 llvm::APSInt numEltsInt(32);
3833 if (numEltsExpr->isTypeDependent() || numEltsExpr->isValueDependent() ||
3834 !numEltsExpr->isIntegerConstantExpr(numEltsInt, S.Context)) {
3835 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
3836 << AttrName << numEltsExpr->getSourceRange();
3837 Attr.setInvalid();
3838 return;
3839 }
3840 // Only certain element types are supported for Neon vectors.
3841 const BuiltinType* BTy = CurType->getAs<BuiltinType>();
3842 if (!BTy ||
3843 (VecKind == VectorType::NeonPolyVector &&
3844 BTy->getKind() != BuiltinType::SChar &&
3845 BTy->getKind() != BuiltinType::Short) ||
3846 (BTy->getKind() != BuiltinType::SChar &&
3847 BTy->getKind() != BuiltinType::UChar &&
3848 BTy->getKind() != BuiltinType::Short &&
3849 BTy->getKind() != BuiltinType::UShort &&
3850 BTy->getKind() != BuiltinType::Int &&
3851 BTy->getKind() != BuiltinType::UInt &&
3852 BTy->getKind() != BuiltinType::LongLong &&
3853 BTy->getKind() != BuiltinType::ULongLong &&
3854 BTy->getKind() != BuiltinType::Float)) {
3855 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) <<CurType;
3856 Attr.setInvalid();
3857 return;
3858 }
3859 // The total size of the vector must be 64 or 128 bits.
3860 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
3861 unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue());
3862 unsigned vecSize = typeSize * numElts;
3863 if (vecSize != 64 && vecSize != 128) {
3864 S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType;
3865 Attr.setInvalid();
3866 return;
3867 }
3868
3869 CurType = S.Context.getVectorType(CurType, numElts, VecKind);
3870}
3871
John McCall711c52b2011-01-05 12:14:39 +00003872static void processTypeAttrs(TypeProcessingState &state, QualType &type,
3873 bool isDeclSpec, AttributeList *attrs) {
Chris Lattner232e8822008-02-21 01:08:11 +00003874 // Scan through and apply attributes to this type where it makes sense. Some
3875 // attributes (such as __address_space__, __vector_size__, etc) apply to the
3876 // type, but others can be present in the type specifiers even though they
Chris Lattnerfca0ddd2008-06-26 06:27:57 +00003877 // apply to the decl. Here we apply type attributes and ignore the rest.
John McCall711c52b2011-01-05 12:14:39 +00003878
3879 AttributeList *next;
3880 do {
3881 AttributeList &attr = *attrs;
3882 next = attr.getNext();
3883
Abramo Bagnarae215f722010-04-30 13:10:51 +00003884 // Skip attributes that were marked to be invalid.
John McCall711c52b2011-01-05 12:14:39 +00003885 if (attr.isInvalid())
Abramo Bagnarae215f722010-04-30 13:10:51 +00003886 continue;
3887
Abramo Bagnarab1f1b262010-04-30 09:13:03 +00003888 // If this is an attribute we can handle, do so now,
3889 // otherwise, add it to the FnAttrs list for rechaining.
John McCall711c52b2011-01-05 12:14:39 +00003890 switch (attr.getKind()) {
Chris Lattner232e8822008-02-21 01:08:11 +00003891 default: break;
John McCall04a67a62010-02-05 21:31:56 +00003892
Chandler Carruth682eae22011-10-07 18:40:27 +00003893 case AttributeList::AT_may_alias:
3894 // FIXME: This attribute needs to actually be handled, but if we ignore
3895 // it it breaks large amounts of Linux software.
3896 attr.setUsedAsTypeAttr();
3897 break;
Chris Lattner232e8822008-02-21 01:08:11 +00003898 case AttributeList::AT_address_space:
John McCall711c52b2011-01-05 12:14:39 +00003899 HandleAddressSpaceTypeAttribute(type, attr, state.getSema());
John McCalle82247a2011-10-01 05:17:03 +00003900 attr.setUsedAsTypeAttr();
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003901 break;
John McCall711c52b2011-01-05 12:14:39 +00003902 OBJC_POINTER_TYPE_ATTRS_CASELIST:
3903 if (!handleObjCPointerTypeAttr(state, attr, type))
3904 distributeObjCPointerTypeAttr(state, attr, type);
John McCalle82247a2011-10-01 05:17:03 +00003905 attr.setUsedAsTypeAttr();
Mike Stump24556362009-07-25 21:26:53 +00003906 break;
John Thompson6e132aa2009-12-04 21:51:28 +00003907 case AttributeList::AT_vector_size:
John McCall711c52b2011-01-05 12:14:39 +00003908 HandleVectorSizeAttr(type, attr, state.getSema());
John McCalle82247a2011-10-01 05:17:03 +00003909 attr.setUsedAsTypeAttr();
John McCall04a67a62010-02-05 21:31:56 +00003910 break;
Douglas Gregor4ac01402011-06-15 16:02:29 +00003911 case AttributeList::AT_ext_vector_type:
3912 if (state.getDeclarator().getDeclSpec().getStorageClassSpec()
3913 != DeclSpec::SCS_typedef)
3914 HandleExtVectorTypeAttr(type, attr, state.getSema());
John McCalle82247a2011-10-01 05:17:03 +00003915 attr.setUsedAsTypeAttr();
Douglas Gregor4ac01402011-06-15 16:02:29 +00003916 break;
Bob Wilson4211bb62010-11-16 00:32:24 +00003917 case AttributeList::AT_neon_vector_type:
John McCall711c52b2011-01-05 12:14:39 +00003918 HandleNeonVectorTypeAttr(type, attr, state.getSema(),
3919 VectorType::NeonVector, "neon_vector_type");
John McCalle82247a2011-10-01 05:17:03 +00003920 attr.setUsedAsTypeAttr();
Bob Wilson4211bb62010-11-16 00:32:24 +00003921 break;
3922 case AttributeList::AT_neon_polyvector_type:
John McCall711c52b2011-01-05 12:14:39 +00003923 HandleNeonVectorTypeAttr(type, attr, state.getSema(),
3924 VectorType::NeonPolyVector,
Bob Wilson4211bb62010-11-16 00:32:24 +00003925 "neon_polyvector_type");
John McCalle82247a2011-10-01 05:17:03 +00003926 attr.setUsedAsTypeAttr();
Bob Wilson4211bb62010-11-16 00:32:24 +00003927 break;
Peter Collingbourne207f4d82011-03-18 22:38:29 +00003928 case AttributeList::AT_opencl_image_access:
3929 HandleOpenCLImageAccessAttribute(type, attr, state.getSema());
John McCalle82247a2011-10-01 05:17:03 +00003930 attr.setUsedAsTypeAttr();
Peter Collingbourne207f4d82011-03-18 22:38:29 +00003931 break;
3932
John McCallf85e1932011-06-15 23:02:42 +00003933 case AttributeList::AT_ns_returns_retained:
3934 if (!state.getSema().getLangOptions().ObjCAutoRefCount)
3935 break;
3936 // fallthrough into the function attrs
3937
John McCall711c52b2011-01-05 12:14:39 +00003938 FUNCTION_TYPE_ATTRS_CASELIST:
John McCalle82247a2011-10-01 05:17:03 +00003939 attr.setUsedAsTypeAttr();
3940
John McCall711c52b2011-01-05 12:14:39 +00003941 // Never process function type attributes as part of the
3942 // declaration-specifiers.
3943 if (isDeclSpec)
3944 distributeFunctionTypeAttrFromDeclSpec(state, attr, type);
3945
3946 // Otherwise, handle the possible delays.
3947 else if (!handleFunctionTypeAttr(state, attr, type))
3948 distributeFunctionTypeAttr(state, attr, type);
John Thompson6e132aa2009-12-04 21:51:28 +00003949 break;
Chris Lattner232e8822008-02-21 01:08:11 +00003950 }
John McCall711c52b2011-01-05 12:14:39 +00003951 } while ((attrs = next));
Chris Lattner232e8822008-02-21 01:08:11 +00003952}
3953
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003954/// \brief Ensure that the type of the given expression is complete.
3955///
3956/// This routine checks whether the expression \p E has a complete type. If the
3957/// expression refers to an instantiable construct, that instantiation is
3958/// performed as needed to complete its type. Furthermore
3959/// Sema::RequireCompleteType is called for the expression's type (or in the
3960/// case of a reference type, the referred-to type).
3961///
3962/// \param E The expression whose type is required to be complete.
3963/// \param PD The partial diagnostic that will be printed out if the type cannot
3964/// be completed.
3965///
3966/// \returns \c true if the type of \p E is incomplete and diagnosed, \c false
3967/// otherwise.
3968bool Sema::RequireCompleteExprType(Expr *E, const PartialDiagnostic &PD,
3969 std::pair<SourceLocation,
3970 PartialDiagnostic> Note) {
3971 QualType T = E->getType();
3972
3973 // Fast path the case where the type is already complete.
3974 if (!T->isIncompleteType())
3975 return false;
3976
3977 // Incomplete array types may be completed by the initializer attached to
3978 // their definitions. For static data members of class templates we need to
3979 // instantiate the definition to get this initializer and complete the type.
3980 if (T->isIncompleteArrayType()) {
3981 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3982 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
3983 if (Var->isStaticDataMember() &&
3984 Var->getInstantiatedFromStaticDataMember()) {
Douglas Gregor36f255c2011-06-03 14:28:43 +00003985
3986 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
3987 assert(MSInfo && "Missing member specialization information?");
3988 if (MSInfo->getTemplateSpecializationKind()
3989 != TSK_ExplicitSpecialization) {
3990 // If we don't already have a point of instantiation, this is it.
3991 if (MSInfo->getPointOfInstantiation().isInvalid()) {
3992 MSInfo->setPointOfInstantiation(E->getLocStart());
3993
3994 // This is a modification of an existing AST node. Notify
3995 // listeners.
3996 if (ASTMutationListener *L = getASTMutationListener())
3997 L->StaticDataMemberInstantiated(Var);
3998 }
3999
4000 InstantiateStaticDataMemberDefinition(E->getExprLoc(), Var);
4001
4002 // Update the type to the newly instantiated definition's type both
4003 // here and within the expression.
4004 if (VarDecl *Def = Var->getDefinition()) {
4005 DRE->setDecl(Def);
4006 T = Def->getType();
4007 DRE->setType(T);
4008 E->setType(T);
4009 }
Douglas Gregorf15748a2011-06-03 03:35:07 +00004010 }
4011
Chandler Carruthe4d645c2011-05-27 01:33:31 +00004012 // We still go on to try to complete the type independently, as it
4013 // may also require instantiations or diagnostics if it remains
4014 // incomplete.
4015 }
4016 }
4017 }
4018 }
4019
4020 // FIXME: Are there other cases which require instantiating something other
4021 // than the type to complete the type of an expression?
4022
4023 // Look through reference types and complete the referred type.
4024 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
4025 T = Ref->getPointeeType();
4026
4027 return RequireCompleteType(E->getExprLoc(), T, PD, Note);
4028}
4029
Mike Stump1eb44332009-09-09 15:08:12 +00004030/// @brief Ensure that the type T is a complete type.
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004031///
4032/// This routine checks whether the type @p T is complete in any
4033/// context where a complete type is required. If @p T is a complete
Douglas Gregor86447ec2009-03-09 16:13:40 +00004034/// type, returns false. If @p T is a class template specialization,
4035/// this routine then attempts to perform class template
4036/// instantiation. If instantiation fails, or if @p T is incomplete
4037/// and cannot be completed, issues the diagnostic @p diag (giving it
4038/// the type @p T) and returns true.
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004039///
4040/// @param Loc The location in the source that the incomplete type
4041/// diagnostic should refer to.
4042///
4043/// @param T The type that this routine is examining for completeness.
4044///
Mike Stump1eb44332009-09-09 15:08:12 +00004045/// @param PD The partial diagnostic that will be printed out if T is not a
Anders Carlssonb7906612009-08-26 23:45:07 +00004046/// complete type.
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004047///
4048/// @returns @c true if @p T is incomplete and a diagnostic was emitted,
4049/// @c false otherwise.
Anders Carlsson91a0cc92009-08-26 22:33:56 +00004050bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
Anders Carlsson8c8d9192009-10-09 23:51:55 +00004051 const PartialDiagnostic &PD,
4052 std::pair<SourceLocation,
4053 PartialDiagnostic> Note) {
Anders Carlsson91a0cc92009-08-26 22:33:56 +00004054 unsigned diag = PD.getDiagID();
Mike Stump1eb44332009-09-09 15:08:12 +00004055
Douglas Gregor573d9c32009-10-21 23:19:44 +00004056 // FIXME: Add this assertion to make sure we always get instantiation points.
4057 // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
Douglas Gregor690dc7f2009-05-21 23:48:18 +00004058 // FIXME: Add this assertion to help us flush out problems with
4059 // checking for dependent types and type-dependent expressions.
4060 //
Mike Stump1eb44332009-09-09 15:08:12 +00004061 // assert(!T->isDependentType() &&
Douglas Gregor690dc7f2009-05-21 23:48:18 +00004062 // "Can't ask whether a dependent type is complete");
4063
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004064 // If we have a complete type, we're done.
4065 if (!T->isIncompleteType())
4066 return false;
Eli Friedman3c0eb162008-05-27 03:33:27 +00004067
Douglas Gregord475b8d2009-03-25 21:17:03 +00004068 // If we have a class template specialization or a class member of a
Sebastian Redl923d56d2009-11-05 15:52:31 +00004069 // class template specialization, or an array with known size of such,
4070 // try to instantiate it.
4071 QualType MaybeTemplate = T;
Douglas Gregor89c49f02009-11-09 22:08:55 +00004072 if (const ConstantArrayType *Array = Context.getAsConstantArrayType(T))
Sebastian Redl923d56d2009-11-05 15:52:31 +00004073 MaybeTemplate = Array->getElementType();
4074 if (const RecordType *Record = MaybeTemplate->getAs<RecordType>()) {
Douglas Gregor2943aed2009-03-03 04:44:36 +00004075 if (ClassTemplateSpecializationDecl *ClassTemplateSpec
Douglas Gregord475b8d2009-03-25 21:17:03 +00004076 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
Douglas Gregor972e6ce2009-10-27 06:26:26 +00004077 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared)
4078 return InstantiateClassTemplateSpecialization(Loc, ClassTemplateSpec,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00004079 TSK_ImplicitInstantiation,
Douglas Gregor5842ba92009-08-24 15:23:48 +00004080 /*Complain=*/diag != 0);
Mike Stump1eb44332009-09-09 15:08:12 +00004081 } else if (CXXRecordDecl *Rec
Douglas Gregord475b8d2009-03-25 21:17:03 +00004082 = dyn_cast<CXXRecordDecl>(Record->getDecl())) {
4083 if (CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass()) {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004084 MemberSpecializationInfo *MSInfo = Rec->getMemberSpecializationInfo();
4085 assert(MSInfo && "Missing member specialization information?");
Douglas Gregor357bbd02009-08-28 20:50:45 +00004086 // This record was instantiated from a class within a template.
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004087 if (MSInfo->getTemplateSpecializationKind()
Douglas Gregor972e6ce2009-10-27 06:26:26 +00004088 != TSK_ExplicitSpecialization)
Douglas Gregorf6b11852009-10-08 15:14:33 +00004089 return InstantiateClass(Loc, Rec, Pattern,
4090 getTemplateInstantiationArgs(Rec),
4091 TSK_ImplicitInstantiation,
4092 /*Complain=*/diag != 0);
Douglas Gregord475b8d2009-03-25 21:17:03 +00004093 }
4094 }
4095 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00004096
Douglas Gregor5842ba92009-08-24 15:23:48 +00004097 if (diag == 0)
4098 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004099
John McCall916c8702010-11-16 01:44:35 +00004100 const TagType *Tag = T->getAs<TagType>();
Douglas Gregorb3029962011-11-14 22:10:01 +00004101 const ObjCInterfaceType *IFace = 0;
4102
4103 if (Tag) {
4104 // Avoid diagnosing invalid decls as incomplete.
4105 if (Tag->getDecl()->isInvalidDecl())
4106 return true;
Rafael Espindola01620702010-03-21 22:56:43 +00004107
Douglas Gregorb3029962011-11-14 22:10:01 +00004108 // Give the external AST source a chance to complete the type.
4109 if (Tag->getDecl()->hasExternalLexicalStorage()) {
4110 Context.getExternalSource()->CompleteType(Tag->getDecl());
4111 if (!Tag->isIncompleteType())
4112 return false;
4113 }
John McCall916c8702010-11-16 01:44:35 +00004114 }
Douglas Gregorb3029962011-11-14 22:10:01 +00004115 else if ((IFace = T->getAs<ObjCInterfaceType>())) {
4116 // Avoid diagnosing invalid decls as incomplete.
4117 if (IFace->getDecl()->isInvalidDecl())
4118 return true;
4119
4120 // Give the external AST source a chance to complete the type.
4121 if (IFace->getDecl()->hasExternalLexicalStorage()) {
4122 Context.getExternalSource()->CompleteType(IFace->getDecl());
4123 if (!IFace->isIncompleteType())
4124 return false;
4125 }
4126 }
4127
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004128 // We have an incomplete type. Produce a diagnostic.
Anders Carlsson91a0cc92009-08-26 22:33:56 +00004129 Diag(Loc, PD) << T;
Douglas Gregorb3029962011-11-14 22:10:01 +00004130
Anders Carlsson8c8d9192009-10-09 23:51:55 +00004131 // If we have a note, produce it.
4132 if (!Note.first.isInvalid())
4133 Diag(Note.first, Note.second);
4134
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004135 // If the type was a forward declaration of a class/struct/union
Rafael Espindola01620702010-03-21 22:56:43 +00004136 // type, produce a note.
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004137 if (Tag && !Tag->getDecl()->isInvalidDecl())
Mike Stump1eb44332009-09-09 15:08:12 +00004138 Diag(Tag->getDecl()->getLocation(),
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004139 Tag->isBeingDefined() ? diag::note_type_being_defined
4140 : diag::note_forward_declaration)
Douglas Gregorb3029962011-11-14 22:10:01 +00004141 << QualType(Tag, 0);
4142
4143 // If the Objective-C class was a forward declaration, produce a note.
4144 if (IFace && !IFace->getDecl()->isInvalidDecl())
4145 Diag(IFace->getDecl()->getLocation(), diag::note_forward_class);
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004146
4147 return true;
4148}
Douglas Gregore6258932009-03-19 00:39:20 +00004149
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004150bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
4151 const PartialDiagnostic &PD) {
4152 return RequireCompleteType(Loc, T, PD,
4153 std::make_pair(SourceLocation(), PDiag(0)));
4154}
4155
4156bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
4157 unsigned DiagID) {
4158 return RequireCompleteType(Loc, T, PDiag(DiagID),
4159 std::make_pair(SourceLocation(), PDiag(0)));
4160}
4161
Richard Smith9f569cc2011-10-01 02:31:28 +00004162/// @brief Ensure that the type T is a literal type.
4163///
4164/// This routine checks whether the type @p T is a literal type. If @p T is an
4165/// incomplete type, an attempt is made to complete it. If @p T is a literal
4166/// type, or @p AllowIncompleteType is true and @p T is an incomplete type,
4167/// returns false. Otherwise, this routine issues the diagnostic @p PD (giving
4168/// it the type @p T), along with notes explaining why the type is not a
4169/// literal type, and returns true.
4170///
4171/// @param Loc The location in the source that the non-literal type
4172/// diagnostic should refer to.
4173///
4174/// @param T The type that this routine is examining for literalness.
4175///
4176/// @param PD The partial diagnostic that will be printed out if T is not a
4177/// literal type.
4178///
4179/// @param AllowIncompleteType If true, an incomplete type will be considered
4180/// acceptable.
4181///
4182/// @returns @c true if @p T is not a literal type and a diagnostic was emitted,
4183/// @c false otherwise.
4184bool Sema::RequireLiteralType(SourceLocation Loc, QualType T,
4185 const PartialDiagnostic &PD,
4186 bool AllowIncompleteType) {
4187 assert(!T->isDependentType() && "type should not be dependent");
4188
4189 bool Incomplete = RequireCompleteType(Loc, T, 0);
4190 if (T->isLiteralType() || (AllowIncompleteType && Incomplete))
4191 return false;
4192
4193 if (PD.getDiagID() == 0)
4194 return true;
4195
4196 Diag(Loc, PD) << T;
4197
4198 if (T->isVariableArrayType())
4199 return true;
4200
4201 const RecordType *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>();
4202 if (!RT)
4203 return true;
4204
4205 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4206
4207 // If the class has virtual base classes, then it's not an aggregate, and
4208 // cannot have any constexpr constructors, so is non-literal. This is better
4209 // to diagnose than the resulting absence of constexpr constructors.
4210 if (RD->getNumVBases()) {
4211 Diag(RD->getLocation(), diag::note_non_literal_virtual_base)
4212 << RD->isStruct() << RD->getNumVBases();
4213 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
4214 E = RD->vbases_end(); I != E; ++I)
4215 Diag(I->getSourceRange().getBegin(),
4216 diag::note_constexpr_virtual_base_here) << I->getSourceRange();
4217 } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor()) {
4218 Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD;
4219
4220 switch (RD->getTemplateSpecializationKind()) {
4221 case TSK_Undeclared:
4222 case TSK_ExplicitSpecialization:
4223 break;
4224
4225 case TSK_ImplicitInstantiation:
4226 case TSK_ExplicitInstantiationDeclaration:
4227 case TSK_ExplicitInstantiationDefinition:
4228 // If the base template had constexpr constructors which were
4229 // instantiated as non-constexpr constructors, explain why.
4230 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
4231 E = RD->ctor_end(); I != E; ++I) {
4232 if ((*I)->isCopyConstructor() || (*I)->isMoveConstructor())
4233 continue;
4234
4235 FunctionDecl *Base = (*I)->getInstantiatedFromMemberFunction();
4236 if (Base && Base->isConstexpr())
4237 CheckConstexprFunctionDecl(*I, CCK_NoteNonConstexprInstantiation);
4238 }
4239 }
4240 } else if (RD->hasNonLiteralTypeFieldsOrBases()) {
4241 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4242 E = RD->bases_end(); I != E; ++I) {
4243 if (!I->getType()->isLiteralType()) {
4244 Diag(I->getSourceRange().getBegin(),
4245 diag::note_non_literal_base_class)
4246 << RD << I->getType() << I->getSourceRange();
4247 return true;
4248 }
4249 }
4250 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
4251 E = RD->field_end(); I != E; ++I) {
4252 if (!(*I)->getType()->isLiteralType()) {
4253 Diag((*I)->getLocation(), diag::note_non_literal_field)
4254 << RD << (*I) << (*I)->getType();
4255 return true;
Richard Smith5fa6a042011-10-12 05:08:15 +00004256 } else if ((*I)->isMutable()) {
4257 Diag((*I)->getLocation(), diag::note_non_literal_mutable_field) << RD;
4258 return true;
Richard Smith9f569cc2011-10-01 02:31:28 +00004259 }
4260 }
4261 } else if (!RD->hasTrivialDestructor()) {
4262 // All fields and bases are of literal types, so have trivial destructors.
4263 // If this class's destructor is non-trivial it must be user-declared.
4264 CXXDestructorDecl *Dtor = RD->getDestructor();
4265 assert(Dtor && "class has literal fields and bases but no dtor?");
4266 if (!Dtor)
4267 return true;
4268
4269 Diag(Dtor->getLocation(), Dtor->isUserProvided() ?
4270 diag::note_non_literal_user_provided_dtor :
4271 diag::note_non_literal_nontrivial_dtor) << RD;
4272 }
4273
4274 return true;
4275}
4276
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004277/// \brief Retrieve a version of the type 'T' that is elaborated by Keyword
4278/// and qualified by the nested-name-specifier contained in SS.
4279QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword,
4280 const CXXScopeSpec &SS, QualType T) {
4281 if (T.isNull())
Douglas Gregore6258932009-03-19 00:39:20 +00004282 return T;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004283 NestedNameSpecifier *NNS;
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00004284 if (SS.isValid())
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004285 NNS = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4286 else {
4287 if (Keyword == ETK_None)
4288 return T;
4289 NNS = 0;
4290 }
4291 return Context.getElaboratedType(Keyword, NNS, T);
Douglas Gregore6258932009-03-19 00:39:20 +00004292}
Anders Carlssonaf017e62009-06-29 22:58:55 +00004293
John McCall2a984ca2010-10-12 00:20:44 +00004294QualType Sema::BuildTypeofExprType(Expr *E, SourceLocation Loc) {
John McCallfb8721c2011-04-10 19:13:55 +00004295 ExprResult ER = CheckPlaceholderExpr(E);
John McCall2a984ca2010-10-12 00:20:44 +00004296 if (ER.isInvalid()) return QualType();
4297 E = ER.take();
4298
Fariborz Jahanian2b1d51b2010-10-05 23:24:00 +00004299 if (!E->isTypeDependent()) {
4300 QualType T = E->getType();
Fariborz Jahanianaca7f7b2010-10-06 00:23:25 +00004301 if (const TagType *TT = T->getAs<TagType>())
4302 DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc());
Fariborz Jahanian2b1d51b2010-10-05 23:24:00 +00004303 }
Anders Carlssonaf017e62009-06-29 22:58:55 +00004304 return Context.getTypeOfExprType(E);
4305}
4306
John McCall2a984ca2010-10-12 00:20:44 +00004307QualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc) {
John McCallfb8721c2011-04-10 19:13:55 +00004308 ExprResult ER = CheckPlaceholderExpr(E);
John McCall2a984ca2010-10-12 00:20:44 +00004309 if (ER.isInvalid()) return QualType();
4310 E = ER.take();
Douglas Gregor4b52e252009-12-21 23:17:24 +00004311
Anders Carlssonaf017e62009-06-29 22:58:55 +00004312 return Context.getDecltypeType(E);
4313}
Sean Huntca63c202011-05-24 22:41:36 +00004314
4315QualType Sema::BuildUnaryTransformType(QualType BaseType,
4316 UnaryTransformType::UTTKind UKind,
4317 SourceLocation Loc) {
4318 switch (UKind) {
4319 case UnaryTransformType::EnumUnderlyingType:
4320 if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) {
4321 Diag(Loc, diag::err_only_enums_have_underlying_types);
4322 return QualType();
4323 } else {
4324 QualType Underlying = BaseType;
4325 if (!BaseType->isDependentType()) {
4326 EnumDecl *ED = BaseType->getAs<EnumType>()->getDecl();
4327 assert(ED && "EnumType has no EnumDecl");
4328 DiagnoseUseOfDecl(ED, Loc);
4329 Underlying = ED->getIntegerType();
4330 }
4331 assert(!Underlying.isNull());
4332 return Context.getUnaryTransformType(BaseType, Underlying,
4333 UnaryTransformType::EnumUnderlyingType);
4334 }
4335 }
4336 llvm_unreachable("unknown unary transform type");
4337}
Eli Friedmanb001de72011-10-06 23:00:33 +00004338
4339QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) {
4340 if (!T->isDependentType()) {
4341 int DisallowedKind = -1;
4342 if (T->isIncompleteType())
4343 // FIXME: It isn't entirely clear whether incomplete atomic types
4344 // are allowed or not; for simplicity, ban them for the moment.
4345 DisallowedKind = 0;
4346 else if (T->isArrayType())
4347 DisallowedKind = 1;
4348 else if (T->isFunctionType())
4349 DisallowedKind = 2;
4350 else if (T->isReferenceType())
4351 DisallowedKind = 3;
4352 else if (T->isAtomicType())
4353 DisallowedKind = 4;
4354 else if (T.hasQualifiers())
4355 DisallowedKind = 5;
4356 else if (!T.isTriviallyCopyableType(Context))
4357 // Some other non-trivially-copyable type (probably a C++ class)
4358 DisallowedKind = 6;
4359
4360 if (DisallowedKind != -1) {
4361 Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T;
4362 return QualType();
4363 }
4364
4365 // FIXME: Do we need any handling for ARC here?
4366 }
4367
4368 // Build the pointer type.
4369 return Context.getAtomicType(T);
4370}