blob: 2254821cb1085532132c045e5b7865861aab397c [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
Douglas Gregor2dc0e642009-03-23 23:06:20 +000034/// \brief Perform adjustment on the parameter type of a function.
35///
36/// This routine adjusts the given parameter type @p T to the actual
Mike Stump1eb44332009-09-09 15:08:12 +000037/// parameter type used by semantic analysis (C99 6.7.5.3p[7,8],
38/// C++ [dcl.fct]p3). The adjusted parameter type is returned.
Douglas Gregor2dc0e642009-03-23 23:06:20 +000039QualType Sema::adjustParameterType(QualType T) {
40 // C99 6.7.5.3p7:
Chris Lattner778ed742009-10-25 17:36:50 +000041 // A declaration of a parameter as "array of type" shall be
42 // adjusted to "qualified pointer to type", where the type
43 // qualifiers (if any) are those specified within the [ and ] of
44 // the array type derivation.
45 if (T->isArrayType())
Douglas Gregor2dc0e642009-03-23 23:06:20 +000046 return Context.getArrayDecayedType(T);
Chris Lattner778ed742009-10-25 17:36:50 +000047
48 // C99 6.7.5.3p8:
49 // A declaration of a parameter as "function returning type"
50 // shall be adjusted to "pointer to function returning type", as
51 // in 6.3.2.1.
52 if (T->isFunctionType())
Douglas Gregor2dc0e642009-03-23 23:06:20 +000053 return Context.getPointerType(T);
54
55 return T;
56}
57
Chris Lattner5db2bb12009-10-25 18:21:37 +000058
59
60/// isOmittedBlockReturnType - Return true if this declarator is missing a
61/// return type because this is a omitted return type on a block literal.
Sebastian Redl8ce35b02009-10-25 21:45:37 +000062static bool isOmittedBlockReturnType(const Declarator &D) {
Chris Lattner5db2bb12009-10-25 18:21:37 +000063 if (D.getContext() != Declarator::BlockLiteralContext ||
Sebastian Redl8ce35b02009-10-25 21:45:37 +000064 D.getDeclSpec().hasTypeSpecifier())
Chris Lattner5db2bb12009-10-25 18:21:37 +000065 return false;
66
67 if (D.getNumTypeObjects() == 0)
Chris Lattnera64ef0a2009-10-25 22:09:09 +000068 return true; // ^{ ... }
Chris Lattner5db2bb12009-10-25 18:21:37 +000069
70 if (D.getNumTypeObjects() == 1 &&
71 D.getTypeObject(0).Kind == DeclaratorChunk::Function)
Chris Lattnera64ef0a2009-10-25 22:09:09 +000072 return true; // ^(int X, float Y) { ... }
Chris Lattner5db2bb12009-10-25 18:21:37 +000073
74 return false;
75}
76
John McCall2792fa52011-03-08 04:17:03 +000077/// diagnoseBadTypeAttribute - Diagnoses a type attribute which
78/// doesn't apply to the given type.
79static void diagnoseBadTypeAttribute(Sema &S, const AttributeList &attr,
80 QualType type) {
81 bool useInstantiationLoc = false;
82
83 unsigned diagID = 0;
84 switch (attr.getKind()) {
85 case AttributeList::AT_objc_gc:
86 diagID = diag::warn_pointer_attribute_wrong_type;
87 useInstantiationLoc = true;
88 break;
89
90 default:
91 // Assume everything else was a function attribute.
92 diagID = diag::warn_function_attribute_wrong_type;
93 break;
94 }
95
96 SourceLocation loc = attr.getLoc();
97 llvm::StringRef name = attr.getName()->getName();
98
99 // The GC attributes are usually written with macros; special-case them.
100 if (useInstantiationLoc && loc.isMacroID() && attr.getParameterName()) {
John McCall834e3f62011-03-08 07:59:04 +0000101 if (attr.getParameterName()->isStr("strong")) {
102 if (S.findMacroSpelling(loc, "__strong")) name = "__strong";
103 } else if (attr.getParameterName()->isStr("weak")) {
104 if (S.findMacroSpelling(loc, "__weak")) name = "__weak";
John McCall2792fa52011-03-08 04:17:03 +0000105 }
106 }
107
108 S.Diag(loc, diagID) << name << type;
109}
110
John McCall711c52b2011-01-05 12:14:39 +0000111// objc_gc applies to Objective-C pointers or, otherwise, to the
112// smallest available pointer type (i.e. 'void*' in 'void**').
113#define OBJC_POINTER_TYPE_ATTRS_CASELIST \
John McCallf85e1932011-06-15 23:02:42 +0000114 case AttributeList::AT_objc_gc: \
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +0000115 case AttributeList::AT_objc_ownership
John McCall04a67a62010-02-05 21:31:56 +0000116
John McCall711c52b2011-01-05 12:14:39 +0000117// Function type attributes.
118#define FUNCTION_TYPE_ATTRS_CASELIST \
119 case AttributeList::AT_noreturn: \
120 case AttributeList::AT_cdecl: \
121 case AttributeList::AT_fastcall: \
122 case AttributeList::AT_stdcall: \
123 case AttributeList::AT_thiscall: \
124 case AttributeList::AT_pascal: \
Anton Korobeynikov414d8962011-04-14 20:06:49 +0000125 case AttributeList::AT_regparm: \
126 case AttributeList::AT_pcs \
John McCall04a67a62010-02-05 21:31:56 +0000127
John McCall711c52b2011-01-05 12:14:39 +0000128namespace {
129 /// An object which stores processing state for the entire
130 /// GetTypeForDeclarator process.
131 class TypeProcessingState {
132 Sema &sema;
133
134 /// The declarator being processed.
135 Declarator &declarator;
136
137 /// The index of the declarator chunk we're currently processing.
138 /// May be the total number of valid chunks, indicating the
139 /// DeclSpec.
140 unsigned chunkIndex;
141
142 /// Whether there are non-trivial modifications to the decl spec.
143 bool trivial;
144
John McCall7ea21932011-03-26 01:39:56 +0000145 /// Whether we saved the attributes in the decl spec.
146 bool hasSavedAttrs;
147
John McCall711c52b2011-01-05 12:14:39 +0000148 /// The original set of attributes on the DeclSpec.
149 llvm::SmallVector<AttributeList*, 2> savedAttrs;
150
151 /// A list of attributes to diagnose the uselessness of when the
152 /// processing is complete.
153 llvm::SmallVector<AttributeList*, 2> ignoredTypeAttrs;
154
155 public:
156 TypeProcessingState(Sema &sema, Declarator &declarator)
157 : sema(sema), declarator(declarator),
158 chunkIndex(declarator.getNumTypeObjects()),
John McCall7ea21932011-03-26 01:39:56 +0000159 trivial(true), hasSavedAttrs(false) {}
John McCall711c52b2011-01-05 12:14:39 +0000160
161 Sema &getSema() const {
162 return sema;
Abramo Bagnarae215f722010-04-30 13:10:51 +0000163 }
John McCall711c52b2011-01-05 12:14:39 +0000164
165 Declarator &getDeclarator() const {
166 return declarator;
167 }
168
169 unsigned getCurrentChunkIndex() const {
170 return chunkIndex;
171 }
172
173 void setCurrentChunkIndex(unsigned idx) {
174 assert(idx <= declarator.getNumTypeObjects());
175 chunkIndex = idx;
176 }
177
178 AttributeList *&getCurrentAttrListRef() const {
179 assert(chunkIndex <= declarator.getNumTypeObjects());
180 if (chunkIndex == declarator.getNumTypeObjects())
181 return getMutableDeclSpec().getAttributes().getListRef();
182 return declarator.getTypeObject(chunkIndex).getAttrListRef();
183 }
184
185 /// Save the current set of attributes on the DeclSpec.
186 void saveDeclSpecAttrs() {
187 // Don't try to save them multiple times.
John McCall7ea21932011-03-26 01:39:56 +0000188 if (hasSavedAttrs) return;
John McCall711c52b2011-01-05 12:14:39 +0000189
190 DeclSpec &spec = getMutableDeclSpec();
191 for (AttributeList *attr = spec.getAttributes().getList(); attr;
192 attr = attr->getNext())
193 savedAttrs.push_back(attr);
194 trivial &= savedAttrs.empty();
John McCall7ea21932011-03-26 01:39:56 +0000195 hasSavedAttrs = true;
John McCall711c52b2011-01-05 12:14:39 +0000196 }
197
198 /// Record that we had nowhere to put the given type attribute.
199 /// We will diagnose such attributes later.
200 void addIgnoredTypeAttr(AttributeList &attr) {
201 ignoredTypeAttrs.push_back(&attr);
202 }
203
204 /// Diagnose all the ignored type attributes, given that the
205 /// declarator worked out to the given type.
206 void diagnoseIgnoredTypeAttrs(QualType type) const {
207 for (llvm::SmallVectorImpl<AttributeList*>::const_iterator
208 i = ignoredTypeAttrs.begin(), e = ignoredTypeAttrs.end();
John McCall2792fa52011-03-08 04:17:03 +0000209 i != e; ++i)
210 diagnoseBadTypeAttribute(getSema(), **i, type);
John McCall711c52b2011-01-05 12:14:39 +0000211 }
212
213 ~TypeProcessingState() {
214 if (trivial) return;
215
216 restoreDeclSpecAttrs();
217 }
218
219 private:
220 DeclSpec &getMutableDeclSpec() const {
221 return const_cast<DeclSpec&>(declarator.getDeclSpec());
222 }
223
224 void restoreDeclSpecAttrs() {
John McCall7ea21932011-03-26 01:39:56 +0000225 assert(hasSavedAttrs);
226
227 if (savedAttrs.empty()) {
228 getMutableDeclSpec().getAttributes().set(0);
229 return;
230 }
231
John McCall711c52b2011-01-05 12:14:39 +0000232 getMutableDeclSpec().getAttributes().set(savedAttrs[0]);
233 for (unsigned i = 0, e = savedAttrs.size() - 1; i != e; ++i)
234 savedAttrs[i]->setNext(savedAttrs[i+1]);
235 savedAttrs.back()->setNext(0);
236 }
237 };
238
239 /// Basically std::pair except that we really want to avoid an
240 /// implicit operator= for safety concerns. It's also a minor
241 /// link-time optimization for this to be a private type.
242 struct AttrAndList {
243 /// The attribute.
244 AttributeList &first;
245
246 /// The head of the list the attribute is currently in.
247 AttributeList *&second;
248
249 AttrAndList(AttributeList &attr, AttributeList *&head)
250 : first(attr), second(head) {}
251 };
John McCall04a67a62010-02-05 21:31:56 +0000252}
253
John McCall711c52b2011-01-05 12:14:39 +0000254namespace llvm {
255 template <> struct isPodLike<AttrAndList> {
256 static const bool value = true;
257 };
258}
259
260static void spliceAttrIntoList(AttributeList &attr, AttributeList *&head) {
261 attr.setNext(head);
262 head = &attr;
263}
264
265static void spliceAttrOutOfList(AttributeList &attr, AttributeList *&head) {
266 if (head == &attr) {
267 head = attr.getNext();
268 return;
John McCall04a67a62010-02-05 21:31:56 +0000269 }
John McCall711c52b2011-01-05 12:14:39 +0000270
271 AttributeList *cur = head;
272 while (true) {
273 assert(cur && cur->getNext() && "ran out of attrs?");
274 if (cur->getNext() == &attr) {
275 cur->setNext(attr.getNext());
276 return;
277 }
278 cur = cur->getNext();
279 }
280}
281
282static void moveAttrFromListToList(AttributeList &attr,
283 AttributeList *&fromList,
284 AttributeList *&toList) {
285 spliceAttrOutOfList(attr, fromList);
286 spliceAttrIntoList(attr, toList);
287}
288
289static void processTypeAttrs(TypeProcessingState &state,
290 QualType &type, bool isDeclSpec,
291 AttributeList *attrs);
292
293static bool handleFunctionTypeAttr(TypeProcessingState &state,
294 AttributeList &attr,
295 QualType &type);
296
297static bool handleObjCGCTypeAttr(TypeProcessingState &state,
298 AttributeList &attr, QualType &type);
299
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +0000300static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
John McCallf85e1932011-06-15 23:02:42 +0000301 AttributeList &attr, QualType &type);
302
John McCall711c52b2011-01-05 12:14:39 +0000303static bool handleObjCPointerTypeAttr(TypeProcessingState &state,
304 AttributeList &attr, QualType &type) {
John McCallf85e1932011-06-15 23:02:42 +0000305 if (attr.getKind() == AttributeList::AT_objc_gc)
306 return handleObjCGCTypeAttr(state, attr, type);
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +0000307 assert(attr.getKind() == AttributeList::AT_objc_ownership);
308 return handleObjCOwnershipTypeAttr(state, attr, type);
John McCall711c52b2011-01-05 12:14:39 +0000309}
310
311/// Given that an objc_gc attribute was written somewhere on a
312/// declaration *other* than on the declarator itself (for which, use
313/// distributeObjCPointerTypeAttrFromDeclarator), and given that it
314/// didn't apply in whatever position it was written in, try to move
315/// it to a more appropriate position.
316static void distributeObjCPointerTypeAttr(TypeProcessingState &state,
317 AttributeList &attr,
318 QualType type) {
319 Declarator &declarator = state.getDeclarator();
320 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
321 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
322 switch (chunk.Kind) {
323 case DeclaratorChunk::Pointer:
324 case DeclaratorChunk::BlockPointer:
325 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
326 chunk.getAttrListRef());
327 return;
328
329 case DeclaratorChunk::Paren:
330 case DeclaratorChunk::Array:
331 continue;
332
333 // Don't walk through these.
334 case DeclaratorChunk::Reference:
335 case DeclaratorChunk::Function:
336 case DeclaratorChunk::MemberPointer:
337 goto error;
338 }
339 }
340 error:
John McCall2792fa52011-03-08 04:17:03 +0000341
342 diagnoseBadTypeAttribute(state.getSema(), attr, type);
John McCall711c52b2011-01-05 12:14:39 +0000343}
344
345/// Distribute an objc_gc type attribute that was written on the
346/// declarator.
347static void
348distributeObjCPointerTypeAttrFromDeclarator(TypeProcessingState &state,
349 AttributeList &attr,
350 QualType &declSpecType) {
351 Declarator &declarator = state.getDeclarator();
352
353 // objc_gc goes on the innermost pointer to something that's not a
354 // pointer.
355 unsigned innermost = -1U;
356 bool considerDeclSpec = true;
357 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
358 DeclaratorChunk &chunk = declarator.getTypeObject(i);
359 switch (chunk.Kind) {
360 case DeclaratorChunk::Pointer:
361 case DeclaratorChunk::BlockPointer:
362 innermost = i;
John McCallae278a32011-01-12 00:34:59 +0000363 continue;
John McCall711c52b2011-01-05 12:14:39 +0000364
365 case DeclaratorChunk::Reference:
366 case DeclaratorChunk::MemberPointer:
367 case DeclaratorChunk::Paren:
368 case DeclaratorChunk::Array:
369 continue;
370
371 case DeclaratorChunk::Function:
372 considerDeclSpec = false;
373 goto done;
374 }
375 }
376 done:
377
378 // That might actually be the decl spec if we weren't blocked by
379 // anything in the declarator.
380 if (considerDeclSpec) {
John McCall7ea21932011-03-26 01:39:56 +0000381 if (handleObjCPointerTypeAttr(state, attr, declSpecType)) {
382 // Splice the attribute into the decl spec. Prevents the
383 // attribute from being applied multiple times and gives
384 // the source-location-filler something to work with.
385 state.saveDeclSpecAttrs();
386 moveAttrFromListToList(attr, declarator.getAttrListRef(),
387 declarator.getMutableDeclSpec().getAttributes().getListRef());
John McCall711c52b2011-01-05 12:14:39 +0000388 return;
John McCall7ea21932011-03-26 01:39:56 +0000389 }
John McCall711c52b2011-01-05 12:14:39 +0000390 }
391
392 // Otherwise, if we found an appropriate chunk, splice the attribute
393 // into it.
394 if (innermost != -1U) {
395 moveAttrFromListToList(attr, declarator.getAttrListRef(),
396 declarator.getTypeObject(innermost).getAttrListRef());
397 return;
398 }
399
400 // Otherwise, diagnose when we're done building the type.
401 spliceAttrOutOfList(attr, declarator.getAttrListRef());
402 state.addIgnoredTypeAttr(attr);
403}
404
405/// A function type attribute was written somewhere in a declaration
406/// *other* than on the declarator itself or in the decl spec. Given
407/// that it didn't apply in whatever position it was written in, try
408/// to move it to a more appropriate position.
409static void distributeFunctionTypeAttr(TypeProcessingState &state,
410 AttributeList &attr,
411 QualType type) {
412 Declarator &declarator = state.getDeclarator();
413
414 // Try to push the attribute from the return type of a function to
415 // the function itself.
416 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
417 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
418 switch (chunk.Kind) {
419 case DeclaratorChunk::Function:
420 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
421 chunk.getAttrListRef());
422 return;
423
424 case DeclaratorChunk::Paren:
425 case DeclaratorChunk::Pointer:
426 case DeclaratorChunk::BlockPointer:
427 case DeclaratorChunk::Array:
428 case DeclaratorChunk::Reference:
429 case DeclaratorChunk::MemberPointer:
430 continue;
431 }
432 }
433
John McCall2792fa52011-03-08 04:17:03 +0000434 diagnoseBadTypeAttribute(state.getSema(), attr, type);
John McCall711c52b2011-01-05 12:14:39 +0000435}
436
437/// Try to distribute a function type attribute to the innermost
438/// function chunk or type. Returns true if the attribute was
439/// distributed, false if no location was found.
440static bool
441distributeFunctionTypeAttrToInnermost(TypeProcessingState &state,
442 AttributeList &attr,
443 AttributeList *&attrList,
444 QualType &declSpecType) {
445 Declarator &declarator = state.getDeclarator();
446
447 // Put it on the innermost function chunk, if there is one.
448 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
449 DeclaratorChunk &chunk = declarator.getTypeObject(i);
450 if (chunk.Kind != DeclaratorChunk::Function) continue;
451
452 moveAttrFromListToList(attr, attrList, chunk.getAttrListRef());
453 return true;
454 }
455
John McCallf85e1932011-06-15 23:02:42 +0000456 if (handleFunctionTypeAttr(state, attr, declSpecType)) {
457 spliceAttrOutOfList(attr, attrList);
458 return true;
459 }
460
461 return false;
John McCall711c52b2011-01-05 12:14:39 +0000462}
463
464/// A function type attribute was written in the decl spec. Try to
465/// apply it somewhere.
466static void
467distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state,
468 AttributeList &attr,
469 QualType &declSpecType) {
470 state.saveDeclSpecAttrs();
471
472 // Try to distribute to the innermost.
473 if (distributeFunctionTypeAttrToInnermost(state, attr,
474 state.getCurrentAttrListRef(),
475 declSpecType))
476 return;
477
478 // If that failed, diagnose the bad attribute when the declarator is
479 // fully built.
480 state.addIgnoredTypeAttr(attr);
481}
482
483/// A function type attribute was written on the declarator. Try to
484/// apply it somewhere.
485static void
486distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state,
487 AttributeList &attr,
488 QualType &declSpecType) {
489 Declarator &declarator = state.getDeclarator();
490
491 // Try to distribute to the innermost.
492 if (distributeFunctionTypeAttrToInnermost(state, attr,
493 declarator.getAttrListRef(),
494 declSpecType))
495 return;
496
497 // If that failed, diagnose the bad attribute when the declarator is
498 // fully built.
499 spliceAttrOutOfList(attr, declarator.getAttrListRef());
500 state.addIgnoredTypeAttr(attr);
501}
502
503/// \brief Given that there are attributes written on the declarator
504/// itself, try to distribute any type attributes to the appropriate
505/// declarator chunk.
506///
507/// These are attributes like the following:
508/// int f ATTR;
509/// int (f ATTR)();
510/// but not necessarily this:
511/// int f() ATTR;
512static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state,
513 QualType &declSpecType) {
514 // Collect all the type attributes from the declarator itself.
515 assert(state.getDeclarator().getAttributes() && "declarator has no attrs!");
516 AttributeList *attr = state.getDeclarator().getAttributes();
517 AttributeList *next;
518 do {
519 next = attr->getNext();
520
521 switch (attr->getKind()) {
522 OBJC_POINTER_TYPE_ATTRS_CASELIST:
523 distributeObjCPointerTypeAttrFromDeclarator(state, *attr, declSpecType);
524 break;
525
John McCallf85e1932011-06-15 23:02:42 +0000526 case AttributeList::AT_ns_returns_retained:
527 if (!state.getSema().getLangOptions().ObjCAutoRefCount)
528 break;
529 // fallthrough
530
John McCall711c52b2011-01-05 12:14:39 +0000531 FUNCTION_TYPE_ATTRS_CASELIST:
532 distributeFunctionTypeAttrFromDeclarator(state, *attr, declSpecType);
533 break;
534
535 default:
536 break;
537 }
538 } while ((attr = next));
539}
540
541/// Add a synthetic '()' to a block-literal declarator if it is
542/// required, given the return type.
543static void maybeSynthesizeBlockSignature(TypeProcessingState &state,
544 QualType declSpecType) {
545 Declarator &declarator = state.getDeclarator();
546
547 // First, check whether the declarator would produce a function,
548 // i.e. whether the innermost semantic chunk is a function.
549 if (declarator.isFunctionDeclarator()) {
550 // If so, make that declarator a prototyped declarator.
551 declarator.getFunctionTypeInfo().hasPrototype = true;
552 return;
553 }
554
John McCallda263792011-02-08 01:59:10 +0000555 // If there are any type objects, the type as written won't name a
556 // function, regardless of the decl spec type. This is because a
557 // block signature declarator is always an abstract-declarator, and
558 // abstract-declarators can't just be parentheses chunks. Therefore
559 // we need to build a function chunk unless there are no type
560 // objects and the decl spec type is a function.
John McCall711c52b2011-01-05 12:14:39 +0000561 if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType())
562 return;
563
John McCallda263792011-02-08 01:59:10 +0000564 // Note that there *are* cases with invalid declarators where
565 // declarators consist solely of parentheses. In general, these
566 // occur only in failed efforts to make function declarators, so
567 // faking up the function chunk is still the right thing to do.
John McCall711c52b2011-01-05 12:14:39 +0000568
569 // Otherwise, we need to fake up a function declarator.
570 SourceLocation loc = declarator.getSourceRange().getBegin();
571
572 // ...and *prepend* it to the declarator.
573 declarator.AddInnermostTypeInfo(DeclaratorChunk::getFunction(
John McCall711c52b2011-01-05 12:14:39 +0000574 /*proto*/ true,
575 /*variadic*/ false, SourceLocation(),
576 /*args*/ 0, 0,
577 /*type quals*/ 0,
Douglas Gregor83f51722011-01-26 03:43:54 +0000578 /*ref-qualifier*/true, SourceLocation(),
Sebastian Redl6e5d3192011-03-05 22:42:13 +0000579 /*EH*/ EST_None, SourceLocation(), 0, 0, 0, 0,
John McCall711c52b2011-01-05 12:14:39 +0000580 /*parens*/ loc, loc,
581 declarator));
582
583 // For consistency, make sure the state still has us as processing
584 // the decl spec.
585 assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1);
586 state.setCurrentChunkIndex(declarator.getNumTypeObjects());
John McCall04a67a62010-02-05 21:31:56 +0000587}
588
Douglas Gregor930d8b52009-01-30 22:09:00 +0000589/// \brief Convert the specified declspec to the appropriate type
590/// object.
Chris Lattner5db2bb12009-10-25 18:21:37 +0000591/// \param D the declarator containing the declaration specifier.
Chris Lattner5153ee62009-04-25 08:47:54 +0000592/// \returns The type described by the declaration specifiers. This function
593/// never returns null.
John McCall711c52b2011-01-05 12:14:39 +0000594static QualType ConvertDeclSpecToType(Sema &S, TypeProcessingState &state) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000595 // FIXME: Should move the logic from DeclSpec::Finish to here for validity
596 // checking.
John McCall711c52b2011-01-05 12:14:39 +0000597
598 Declarator &declarator = state.getDeclarator();
599 const DeclSpec &DS = declarator.getDeclSpec();
600 SourceLocation DeclLoc = declarator.getIdentifierLoc();
Chris Lattner5db2bb12009-10-25 18:21:37 +0000601 if (DeclLoc.isInvalid())
602 DeclLoc = DS.getSourceRange().getBegin();
Chris Lattner1564e392009-10-25 18:07:27 +0000603
John McCall711c52b2011-01-05 12:14:39 +0000604 ASTContext &Context = S.Context;
Mike Stump1eb44332009-09-09 15:08:12 +0000605
Chris Lattner5db2bb12009-10-25 18:21:37 +0000606 QualType Result;
Reid Spencer5f016e22007-07-11 17:01:13 +0000607 switch (DS.getTypeSpecType()) {
Chris Lattner96b77fc2008-04-02 06:50:17 +0000608 case DeclSpec::TST_void:
609 Result = Context.VoidTy;
610 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000611 case DeclSpec::TST_char:
612 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
Chris Lattnerfab5b452008-02-20 23:53:49 +0000613 Result = Context.CharTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000614 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed)
Chris Lattnerfab5b452008-02-20 23:53:49 +0000615 Result = Context.SignedCharTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000616 else {
617 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
618 "Unknown TSS value");
Chris Lattnerfab5b452008-02-20 23:53:49 +0000619 Result = Context.UnsignedCharTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000620 }
Chris Lattner958858e2008-02-20 21:40:32 +0000621 break;
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000622 case DeclSpec::TST_wchar:
623 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
624 Result = Context.WCharTy;
625 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) {
John McCall711c52b2011-01-05 12:14:39 +0000626 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000627 << DS.getSpecifierName(DS.getTypeSpecType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000628 Result = Context.getSignedWCharType();
629 } else {
630 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
631 "Unknown TSS value");
John McCall711c52b2011-01-05 12:14:39 +0000632 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000633 << DS.getSpecifierName(DS.getTypeSpecType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000634 Result = Context.getUnsignedWCharType();
635 }
636 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000637 case DeclSpec::TST_char16:
638 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
639 "Unknown TSS value");
640 Result = Context.Char16Ty;
641 break;
642 case DeclSpec::TST_char32:
643 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
644 "Unknown TSS value");
645 Result = Context.Char32Ty;
646 break;
Chris Lattnerd658b562008-04-05 06:32:51 +0000647 case DeclSpec::TST_unspecified:
Chris Lattner62f5f7f2008-07-26 00:46:50 +0000648 // "<proto1,proto2>" is an objc qualified ID with a missing id.
Chris Lattner097e9162008-10-20 02:01:50 +0000649 if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) {
John McCallc12c5bb2010-05-15 11:32:37 +0000650 Result = Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
651 (ObjCProtocolDecl**)PQ,
652 DS.getNumProtocolQualifiers());
653 Result = Context.getObjCObjectPointerType(Result);
Chris Lattner62f5f7f2008-07-26 00:46:50 +0000654 break;
655 }
Chris Lattner5db2bb12009-10-25 18:21:37 +0000656
657 // If this is a missing declspec in a block literal return context, then it
658 // is inferred from the return statements inside the block.
John McCall711c52b2011-01-05 12:14:39 +0000659 if (isOmittedBlockReturnType(declarator)) {
Chris Lattner5db2bb12009-10-25 18:21:37 +0000660 Result = Context.DependentTy;
661 break;
662 }
Mike Stump1eb44332009-09-09 15:08:12 +0000663
Chris Lattnerd658b562008-04-05 06:32:51 +0000664 // Unspecified typespec defaults to int in C90. However, the C90 grammar
665 // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
666 // type-qualifier, or storage-class-specifier. If not, emit an extwarn.
667 // Note that the one exception to this is function definitions, which are
668 // allowed to be completely missing a declspec. This is handled in the
669 // parser already though by it pretending to have seen an 'int' in this
670 // case.
John McCall711c52b2011-01-05 12:14:39 +0000671 if (S.getLangOptions().ImplicitInt) {
Chris Lattner35d276f2009-02-27 18:53:28 +0000672 // In C89 mode, we only warn if there is a completely missing declspec
673 // when one is not allowed.
Chris Lattner3f84ad22009-04-22 05:27:59 +0000674 if (DS.isEmpty()) {
John McCall711c52b2011-01-05 12:14:39 +0000675 S.Diag(DeclLoc, diag::ext_missing_declspec)
Chris Lattner3f84ad22009-04-22 05:27:59 +0000676 << DS.getSourceRange()
Douglas Gregor849b2432010-03-31 17:46:05 +0000677 << FixItHint::CreateInsertion(DS.getSourceRange().getBegin(), "int");
Chris Lattner3f84ad22009-04-22 05:27:59 +0000678 }
Douglas Gregor4310f4e2009-02-16 22:38:20 +0000679 } else if (!DS.hasTypeSpecifier()) {
Chris Lattnerd658b562008-04-05 06:32:51 +0000680 // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says:
681 // "At least one type specifier shall be given in the declaration
682 // specifiers in each declaration, and in the specifier-qualifier list in
683 // each struct declaration and type name."
Douglas Gregor4310f4e2009-02-16 22:38:20 +0000684 // FIXME: Does Microsoft really have the implicit int extension in C++?
John McCall711c52b2011-01-05 12:14:39 +0000685 if (S.getLangOptions().CPlusPlus &&
686 !S.getLangOptions().Microsoft) {
687 S.Diag(DeclLoc, diag::err_missing_type_specifier)
Chris Lattner3f84ad22009-04-22 05:27:59 +0000688 << DS.getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000689
Chris Lattnerb78d8332009-06-26 04:45:06 +0000690 // When this occurs in C++ code, often something is very broken with the
691 // value being declared, poison it as invalid so we don't get chains of
692 // errors.
John McCall711c52b2011-01-05 12:14:39 +0000693 declarator.setInvalidType(true);
Chris Lattnerb78d8332009-06-26 04:45:06 +0000694 } else {
John McCall711c52b2011-01-05 12:14:39 +0000695 S.Diag(DeclLoc, diag::ext_missing_type_specifier)
Chris Lattner3f84ad22009-04-22 05:27:59 +0000696 << DS.getSourceRange();
Chris Lattnerb78d8332009-06-26 04:45:06 +0000697 }
Chris Lattnerd658b562008-04-05 06:32:51 +0000698 }
Mike Stump1eb44332009-09-09 15:08:12 +0000699
700 // FALL THROUGH.
Chris Lattner3cbc38b2007-08-21 17:02:28 +0000701 case DeclSpec::TST_int: {
Reid Spencer5f016e22007-07-11 17:01:13 +0000702 if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) {
703 switch (DS.getTypeSpecWidth()) {
Chris Lattnerfab5b452008-02-20 23:53:49 +0000704 case DeclSpec::TSW_unspecified: Result = Context.IntTy; break;
705 case DeclSpec::TSW_short: Result = Context.ShortTy; break;
706 case DeclSpec::TSW_long: Result = Context.LongTy; break;
Chris Lattner311157f2009-10-25 18:25:04 +0000707 case DeclSpec::TSW_longlong:
708 Result = Context.LongLongTy;
709
710 // long long is a C99 feature.
John McCall711c52b2011-01-05 12:14:39 +0000711 if (!S.getLangOptions().C99 &&
712 !S.getLangOptions().CPlusPlus0x)
713 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_longlong);
Chris Lattner311157f2009-10-25 18:25:04 +0000714 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000715 }
716 } else {
717 switch (DS.getTypeSpecWidth()) {
Chris Lattnerfab5b452008-02-20 23:53:49 +0000718 case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break;
719 case DeclSpec::TSW_short: Result = Context.UnsignedShortTy; break;
720 case DeclSpec::TSW_long: Result = Context.UnsignedLongTy; break;
Chris Lattner311157f2009-10-25 18:25:04 +0000721 case DeclSpec::TSW_longlong:
722 Result = Context.UnsignedLongLongTy;
723
724 // long long is a C99 feature.
John McCall711c52b2011-01-05 12:14:39 +0000725 if (!S.getLangOptions().C99 &&
726 !S.getLangOptions().CPlusPlus0x)
727 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_longlong);
Chris Lattner311157f2009-10-25 18:25:04 +0000728 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000729 }
730 }
Chris Lattner958858e2008-02-20 21:40:32 +0000731 break;
Chris Lattner3cbc38b2007-08-21 17:02:28 +0000732 }
Chris Lattnerfab5b452008-02-20 23:53:49 +0000733 case DeclSpec::TST_float: Result = Context.FloatTy; break;
Chris Lattner958858e2008-02-20 21:40:32 +0000734 case DeclSpec::TST_double:
735 if (DS.getTypeSpecWidth() == DeclSpec::TSW_long)
Chris Lattnerfab5b452008-02-20 23:53:49 +0000736 Result = Context.LongDoubleTy;
Chris Lattner958858e2008-02-20 21:40:32 +0000737 else
Chris Lattnerfab5b452008-02-20 23:53:49 +0000738 Result = Context.DoubleTy;
Peter Collingbourne39d3e7a2011-02-15 19:46:23 +0000739
740 if (S.getLangOptions().OpenCL && !S.getOpenCLOptions().cl_khr_fp64) {
741 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_double_requires_fp64);
742 declarator.setInvalidType(true);
743 }
Chris Lattner958858e2008-02-20 21:40:32 +0000744 break;
Chris Lattnerfab5b452008-02-20 23:53:49 +0000745 case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool
Reid Spencer5f016e22007-07-11 17:01:13 +0000746 case DeclSpec::TST_decimal32: // _Decimal32
747 case DeclSpec::TST_decimal64: // _Decimal64
748 case DeclSpec::TST_decimal128: // _Decimal128
John McCall711c52b2011-01-05 12:14:39 +0000749 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
Chris Lattner8f12f652009-05-13 05:02:08 +0000750 Result = Context.IntTy;
John McCall711c52b2011-01-05 12:14:39 +0000751 declarator.setInvalidType(true);
Chris Lattner8f12f652009-05-13 05:02:08 +0000752 break;
Chris Lattner99dc9142008-04-13 18:59:07 +0000753 case DeclSpec::TST_class:
Reid Spencer5f016e22007-07-11 17:01:13 +0000754 case DeclSpec::TST_enum:
755 case DeclSpec::TST_union:
756 case DeclSpec::TST_struct: {
John McCallb3d87482010-08-24 05:47:05 +0000757 TypeDecl *D = dyn_cast_or_null<TypeDecl>(DS.getRepAsDecl());
John McCall6e247262009-10-10 05:48:19 +0000758 if (!D) {
759 // This can happen in C++ with ambiguous lookups.
760 Result = Context.IntTy;
John McCall711c52b2011-01-05 12:14:39 +0000761 declarator.setInvalidType(true);
John McCall6e247262009-10-10 05:48:19 +0000762 break;
763 }
764
Chris Lattnera64ef0a2009-10-25 22:09:09 +0000765 // If the type is deprecated or unavailable, diagnose it.
Abramo Bagnara0daaf322011-03-16 20:16:18 +0000766 S.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeNameLoc());
Chris Lattnera64ef0a2009-10-25 22:09:09 +0000767
Reid Spencer5f016e22007-07-11 17:01:13 +0000768 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
Chris Lattnera64ef0a2009-10-25 22:09:09 +0000769 DS.getTypeSpecSign() == 0 && "No qualifiers on tag names!");
770
Reid Spencer5f016e22007-07-11 17:01:13 +0000771 // TypeQuals handled by caller.
Chris Lattnera64ef0a2009-10-25 22:09:09 +0000772 Result = Context.getTypeDeclType(D);
John McCall2191b202009-09-05 06:31:47 +0000773
Abramo Bagnara0daaf322011-03-16 20:16:18 +0000774 // In both C and C++, make an ElaboratedType.
775 ElaboratedTypeKeyword Keyword
776 = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType());
777 Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result);
778
Chris Lattner5153ee62009-04-25 08:47:54 +0000779 if (D->isInvalidDecl())
John McCall711c52b2011-01-05 12:14:39 +0000780 declarator.setInvalidType(true);
Chris Lattner958858e2008-02-20 21:40:32 +0000781 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000782 }
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000783 case DeclSpec::TST_typename: {
Reid Spencer5f016e22007-07-11 17:01:13 +0000784 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
785 DS.getTypeSpecSign() == 0 &&
786 "Can't handle qualifiers on typedef names yet!");
John McCall711c52b2011-01-05 12:14:39 +0000787 Result = S.GetTypeFromParser(DS.getRepAsType());
John McCall27940d22010-07-30 05:17:22 +0000788 if (Result.isNull())
John McCall711c52b2011-01-05 12:14:39 +0000789 declarator.setInvalidType(true);
John McCall27940d22010-07-30 05:17:22 +0000790 else if (DeclSpec::ProtocolQualifierListTy PQ
791 = DS.getProtocolQualifiers()) {
John McCallc12c5bb2010-05-15 11:32:37 +0000792 if (const ObjCObjectType *ObjT = Result->getAs<ObjCObjectType>()) {
793 // Silently drop any existing protocol qualifiers.
794 // TODO: determine whether that's the right thing to do.
795 if (ObjT->getNumProtocols())
796 Result = ObjT->getBaseType();
797
798 if (DS.getNumProtocolQualifiers())
799 Result = Context.getObjCObjectType(Result,
800 (ObjCProtocolDecl**) PQ,
801 DS.getNumProtocolQualifiers());
802 } else if (Result->isObjCIdType()) {
Chris Lattnerae4da612008-07-26 01:53:50 +0000803 // id<protocol-list>
John McCallc12c5bb2010-05-15 11:32:37 +0000804 Result = Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
805 (ObjCProtocolDecl**) PQ,
806 DS.getNumProtocolQualifiers());
807 Result = Context.getObjCObjectPointerType(Result);
808 } else if (Result->isObjCClassType()) {
Steve Naroff4262a072009-02-23 18:53:24 +0000809 // Class<protocol-list>
John McCallc12c5bb2010-05-15 11:32:37 +0000810 Result = Context.getObjCObjectType(Context.ObjCBuiltinClassTy,
811 (ObjCProtocolDecl**) PQ,
812 DS.getNumProtocolQualifiers());
813 Result = Context.getObjCObjectPointerType(Result);
Chris Lattner3f84ad22009-04-22 05:27:59 +0000814 } else {
John McCall711c52b2011-01-05 12:14:39 +0000815 S.Diag(DeclLoc, diag::err_invalid_protocol_qualifiers)
Chris Lattner3f84ad22009-04-22 05:27:59 +0000816 << DS.getSourceRange();
John McCall711c52b2011-01-05 12:14:39 +0000817 declarator.setInvalidType(true);
Chris Lattner3f84ad22009-04-22 05:27:59 +0000818 }
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000819 }
Mike Stump1eb44332009-09-09 15:08:12 +0000820
Reid Spencer5f016e22007-07-11 17:01:13 +0000821 // TypeQuals handled by caller.
Chris Lattner958858e2008-02-20 21:40:32 +0000822 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000823 }
Chris Lattner958858e2008-02-20 21:40:32 +0000824 case DeclSpec::TST_typeofType:
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000825 // FIXME: Preserve type source info.
John McCall711c52b2011-01-05 12:14:39 +0000826 Result = S.GetTypeFromParser(DS.getRepAsType());
Chris Lattner958858e2008-02-20 21:40:32 +0000827 assert(!Result.isNull() && "Didn't get a type for typeof?");
Fariborz Jahanian730e1752010-10-06 17:00:02 +0000828 if (!Result->isDependentType())
829 if (const TagType *TT = Result->getAs<TagType>())
John McCall711c52b2011-01-05 12:14:39 +0000830 S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc());
Steve Naroffd1861fd2007-07-31 12:34:36 +0000831 // TypeQuals handled by caller.
Chris Lattnerfab5b452008-02-20 23:53:49 +0000832 Result = Context.getTypeOfType(Result);
Chris Lattner958858e2008-02-20 21:40:32 +0000833 break;
Steve Naroffd1861fd2007-07-31 12:34:36 +0000834 case DeclSpec::TST_typeofExpr: {
John McCallb3d87482010-08-24 05:47:05 +0000835 Expr *E = DS.getRepAsExpr();
Steve Naroffd1861fd2007-07-31 12:34:36 +0000836 assert(E && "Didn't get an expression for typeof?");
837 // TypeQuals handled by caller.
John McCall711c52b2011-01-05 12:14:39 +0000838 Result = S.BuildTypeofExprType(E, DS.getTypeSpecTypeLoc());
Douglas Gregor4b52e252009-12-21 23:17:24 +0000839 if (Result.isNull()) {
840 Result = Context.IntTy;
John McCall711c52b2011-01-05 12:14:39 +0000841 declarator.setInvalidType(true);
Douglas Gregor4b52e252009-12-21 23:17:24 +0000842 }
Chris Lattner958858e2008-02-20 21:40:32 +0000843 break;
Steve Naroffd1861fd2007-07-31 12:34:36 +0000844 }
Anders Carlsson6fd634f2009-06-24 17:47:40 +0000845 case DeclSpec::TST_decltype: {
John McCallb3d87482010-08-24 05:47:05 +0000846 Expr *E = DS.getRepAsExpr();
Anders Carlsson6fd634f2009-06-24 17:47:40 +0000847 assert(E && "Didn't get an expression for decltype?");
848 // TypeQuals handled by caller.
John McCall711c52b2011-01-05 12:14:39 +0000849 Result = S.BuildDecltypeType(E, DS.getTypeSpecTypeLoc());
Anders Carlssonaf017e62009-06-29 22:58:55 +0000850 if (Result.isNull()) {
851 Result = Context.IntTy;
John McCall711c52b2011-01-05 12:14:39 +0000852 declarator.setInvalidType(true);
Anders Carlssonaf017e62009-06-29 22:58:55 +0000853 }
Anders Carlsson6fd634f2009-06-24 17:47:40 +0000854 break;
855 }
Sean Huntca63c202011-05-24 22:41:36 +0000856 case DeclSpec::TST_underlyingType:
Sean Huntdb5d44b2011-05-19 05:37:45 +0000857 Result = S.GetTypeFromParser(DS.getRepAsType());
858 assert(!Result.isNull() && "Didn't get a type for __underlying_type?");
Sean Huntca63c202011-05-24 22:41:36 +0000859 Result = S.BuildUnaryTransformType(Result,
860 UnaryTransformType::EnumUnderlyingType,
861 DS.getTypeSpecTypeLoc());
862 if (Result.isNull()) {
863 Result = Context.IntTy;
864 declarator.setInvalidType(true);
Sean Huntdb5d44b2011-05-19 05:37:45 +0000865 }
866 break;
867
Anders Carlssone89d1592009-06-26 18:41:36 +0000868 case DeclSpec::TST_auto: {
869 // TypeQuals handled by caller.
Richard Smith34b41d92011-02-20 03:19:35 +0000870 Result = Context.getAutoType(QualType());
Anders Carlssone89d1592009-06-26 18:41:36 +0000871 break;
872 }
Mike Stump1eb44332009-09-09 15:08:12 +0000873
John McCalla5fc4722011-04-09 22:50:59 +0000874 case DeclSpec::TST_unknown_anytype:
875 Result = Context.UnknownAnyTy;
876 break;
877
Douglas Gregor809070a2009-02-18 17:45:20 +0000878 case DeclSpec::TST_error:
Chris Lattner5153ee62009-04-25 08:47:54 +0000879 Result = Context.IntTy;
John McCall711c52b2011-01-05 12:14:39 +0000880 declarator.setInvalidType(true);
Chris Lattner5153ee62009-04-25 08:47:54 +0000881 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000882 }
Mike Stump1eb44332009-09-09 15:08:12 +0000883
Chris Lattner958858e2008-02-20 21:40:32 +0000884 // Handle complex types.
Douglas Gregorf244cd72009-02-14 21:06:05 +0000885 if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
John McCall711c52b2011-01-05 12:14:39 +0000886 if (S.getLangOptions().Freestanding)
887 S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
Chris Lattnerfab5b452008-02-20 23:53:49 +0000888 Result = Context.getComplexType(Result);
John Thompson82287d12010-02-05 00:12:22 +0000889 } else if (DS.isTypeAltiVecVector()) {
890 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result));
891 assert(typeSize > 0 && "type size for vector must be greater than 0 bits");
Bob Wilsone86d78c2010-11-10 21:56:12 +0000892 VectorType::VectorKind VecKind = VectorType::AltiVecVector;
Chris Lattner788b0fd2010-06-23 06:00:24 +0000893 if (DS.isTypeAltiVecPixel())
Bob Wilsone86d78c2010-11-10 21:56:12 +0000894 VecKind = VectorType::AltiVecPixel;
Chris Lattner788b0fd2010-06-23 06:00:24 +0000895 else if (DS.isTypeAltiVecBool())
Bob Wilsone86d78c2010-11-10 21:56:12 +0000896 VecKind = VectorType::AltiVecBool;
897 Result = Context.getVectorType(Result, 128/typeSize, VecKind);
Douglas Gregorf244cd72009-02-14 21:06:05 +0000898 }
Mike Stump1eb44332009-09-09 15:08:12 +0000899
Argyrios Kyrtzidis47423bd2010-09-23 09:40:31 +0000900 // FIXME: Imaginary.
901 if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary)
John McCall711c52b2011-01-05 12:14:39 +0000902 S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported);
Mike Stump1eb44332009-09-09 15:08:12 +0000903
John McCall711c52b2011-01-05 12:14:39 +0000904 // Before we process any type attributes, synthesize a block literal
905 // function declarator if necessary.
906 if (declarator.getContext() == Declarator::BlockLiteralContext)
907 maybeSynthesizeBlockSignature(state, Result);
908
909 // Apply any type attributes from the decl spec. This may cause the
910 // list of type attributes to be temporarily saved while the type
911 // attributes are pushed around.
912 if (AttributeList *attrs = DS.getAttributes().getList())
913 processTypeAttrs(state, Result, true, attrs);
Mike Stump1eb44332009-09-09 15:08:12 +0000914
Chris Lattner96b77fc2008-04-02 06:50:17 +0000915 // Apply const/volatile/restrict qualifiers to T.
916 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
917
918 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
919 // or incomplete types shall not be restrict-qualified." C++ also allows
920 // restrict-qualified references.
John McCall0953e762009-09-24 19:53:00 +0000921 if (TypeQuals & DeclSpec::TQ_restrict) {
Fariborz Jahanian2b5ff1a2009-12-07 18:08:58 +0000922 if (Result->isAnyPointerType() || Result->isReferenceType()) {
923 QualType EltTy;
924 if (Result->isObjCObjectPointerType())
925 EltTy = Result;
926 else
927 EltTy = Result->isPointerType() ?
928 Result->getAs<PointerType>()->getPointeeType() :
929 Result->getAs<ReferenceType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +0000930
Douglas Gregorbad0e652009-03-24 20:32:41 +0000931 // If we have a pointer or reference, the pointee must have an object
Chris Lattnerbdcd6372008-04-02 17:35:06 +0000932 // incomplete type.
933 if (!EltTy->isIncompleteOrObjectType()) {
John McCall711c52b2011-01-05 12:14:39 +0000934 S.Diag(DS.getRestrictSpecLoc(),
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000935 diag::err_typecheck_invalid_restrict_invalid_pointee)
Chris Lattnerd1625842008-11-24 06:25:27 +0000936 << EltTy << DS.getSourceRange();
John McCall0953e762009-09-24 19:53:00 +0000937 TypeQuals &= ~DeclSpec::TQ_restrict; // Remove the restrict qualifier.
Chris Lattnerbdcd6372008-04-02 17:35:06 +0000938 }
939 } else {
John McCall711c52b2011-01-05 12:14:39 +0000940 S.Diag(DS.getRestrictSpecLoc(),
941 diag::err_typecheck_invalid_restrict_not_pointer)
Chris Lattnerd1625842008-11-24 06:25:27 +0000942 << Result << DS.getSourceRange();
John McCall0953e762009-09-24 19:53:00 +0000943 TypeQuals &= ~DeclSpec::TQ_restrict; // Remove the restrict qualifier.
Chris Lattner96b77fc2008-04-02 06:50:17 +0000944 }
Chris Lattner96b77fc2008-04-02 06:50:17 +0000945 }
Mike Stump1eb44332009-09-09 15:08:12 +0000946
Chris Lattner96b77fc2008-04-02 06:50:17 +0000947 // Warn about CV qualifiers on functions: C99 6.7.3p8: "If the specification
948 // of a function type includes any type qualifiers, the behavior is
949 // undefined."
950 if (Result->isFunctionType() && TypeQuals) {
951 // Get some location to point at, either the C or V location.
952 SourceLocation Loc;
John McCall0953e762009-09-24 19:53:00 +0000953 if (TypeQuals & DeclSpec::TQ_const)
Chris Lattner96b77fc2008-04-02 06:50:17 +0000954 Loc = DS.getConstSpecLoc();
John McCall0953e762009-09-24 19:53:00 +0000955 else if (TypeQuals & DeclSpec::TQ_volatile)
Chris Lattner96b77fc2008-04-02 06:50:17 +0000956 Loc = DS.getVolatileSpecLoc();
John McCall0953e762009-09-24 19:53:00 +0000957 else {
958 assert((TypeQuals & DeclSpec::TQ_restrict) &&
959 "Has CVR quals but not C, V, or R?");
960 Loc = DS.getRestrictSpecLoc();
Chris Lattner96b77fc2008-04-02 06:50:17 +0000961 }
John McCall711c52b2011-01-05 12:14:39 +0000962 S.Diag(Loc, diag::warn_typecheck_function_qualifiers)
Chris Lattnerd1625842008-11-24 06:25:27 +0000963 << Result << DS.getSourceRange();
Chris Lattner96b77fc2008-04-02 06:50:17 +0000964 }
Mike Stump1eb44332009-09-09 15:08:12 +0000965
Douglas Gregorf1f9b4e2008-11-03 15:51:28 +0000966 // C++ [dcl.ref]p1:
967 // Cv-qualified references are ill-formed except when the
968 // cv-qualifiers are introduced through the use of a typedef
969 // (7.1.3) or of a template type argument (14.3), in which
970 // case the cv-qualifiers are ignored.
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000971 // FIXME: Shouldn't we be checking SCS_typedef here?
972 if (DS.getTypeSpecType() == DeclSpec::TST_typename &&
Douglas Gregorf1f9b4e2008-11-03 15:51:28 +0000973 TypeQuals && Result->isReferenceType()) {
John McCall0953e762009-09-24 19:53:00 +0000974 TypeQuals &= ~DeclSpec::TQ_const;
975 TypeQuals &= ~DeclSpec::TQ_volatile;
Mike Stump1eb44332009-09-09 15:08:12 +0000976 }
977
John McCall0953e762009-09-24 19:53:00 +0000978 Qualifiers Quals = Qualifiers::fromCVRMask(TypeQuals);
979 Result = Context.getQualifiedType(Result, Quals);
Chris Lattner96b77fc2008-04-02 06:50:17 +0000980 }
John McCall0953e762009-09-24 19:53:00 +0000981
Chris Lattnerf1d705c2008-02-21 01:07:18 +0000982 return Result;
983}
984
Douglas Gregorcd281c32009-02-28 00:25:32 +0000985static std::string getPrintableNameForEntity(DeclarationName Entity) {
986 if (Entity)
987 return Entity.getAsString();
Mike Stump1eb44332009-09-09 15:08:12 +0000988
Douglas Gregorcd281c32009-02-28 00:25:32 +0000989 return "type name";
990}
991
John McCall28654742010-06-05 06:41:15 +0000992QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
993 Qualifiers Qs) {
994 // Enforce C99 6.7.3p2: "Types other than pointer types derived from
995 // object or incomplete types shall not be restrict-qualified."
996 if (Qs.hasRestrict()) {
997 unsigned DiagID = 0;
998 QualType ProblemTy;
999
1000 const Type *Ty = T->getCanonicalTypeInternal().getTypePtr();
1001 if (const ReferenceType *RTy = dyn_cast<ReferenceType>(Ty)) {
1002 if (!RTy->getPointeeType()->isIncompleteOrObjectType()) {
1003 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1004 ProblemTy = T->getAs<ReferenceType>()->getPointeeType();
1005 }
1006 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
1007 if (!PTy->getPointeeType()->isIncompleteOrObjectType()) {
1008 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1009 ProblemTy = T->getAs<PointerType>()->getPointeeType();
1010 }
1011 } else if (const MemberPointerType *PTy = dyn_cast<MemberPointerType>(Ty)) {
1012 if (!PTy->getPointeeType()->isIncompleteOrObjectType()) {
1013 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1014 ProblemTy = T->getAs<PointerType>()->getPointeeType();
1015 }
1016 } else if (!Ty->isDependentType()) {
1017 // FIXME: this deserves a proper diagnostic
1018 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1019 ProblemTy = T;
1020 }
1021
1022 if (DiagID) {
1023 Diag(Loc, DiagID) << ProblemTy;
1024 Qs.removeRestrict();
1025 }
1026 }
1027
1028 return Context.getQualifiedType(T, Qs);
1029}
1030
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001031/// \brief Build a paren type including \p T.
1032QualType Sema::BuildParenType(QualType T) {
1033 return Context.getParenType(T);
1034}
1035
John McCallf85e1932011-06-15 23:02:42 +00001036/// Given that we're building a pointer or reference to the given
1037static QualType inferARCLifetimeForPointee(Sema &S, QualType type,
1038 SourceLocation loc,
1039 bool isReference) {
1040 // Bail out if retention is unrequired or already specified.
1041 if (!type->isObjCLifetimeType() ||
1042 type.getObjCLifetime() != Qualifiers::OCL_None)
1043 return type;
1044
1045 Qualifiers::ObjCLifetime implicitLifetime = Qualifiers::OCL_None;
1046
1047 // If the object type is const-qualified, we can safely use
1048 // __unsafe_unretained. This is safe (because there are no read
1049 // barriers), and it'll be safe to coerce anything but __weak* to
1050 // the resulting type.
1051 if (type.isConstQualified()) {
1052 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1053
1054 // Otherwise, check whether the static type does not require
1055 // retaining. This currently only triggers for Class (possibly
1056 // protocol-qualifed, and arrays thereof).
1057 } else if (type->isObjCARCImplicitlyUnretainedType()) {
1058 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1059
1060 // If that failed, give an error and recover using __autoreleasing.
1061 } else {
1062 // These types can show up in private ivars in system headers, so
1063 // we need this to not be an error in those cases. Instead we
1064 // want to delay.
1065 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
1066 S.DelayedDiagnostics.add(
1067 sema::DelayedDiagnostic::makeForbiddenType(loc,
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00001068 diag::err_arc_indirect_no_ownership, type, isReference));
John McCallf85e1932011-06-15 23:02:42 +00001069 } else {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00001070 S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference;
John McCallf85e1932011-06-15 23:02:42 +00001071 }
1072 implicitLifetime = Qualifiers::OCL_Autoreleasing;
1073 }
1074 assert(implicitLifetime && "didn't infer any lifetime!");
1075
1076 Qualifiers qs;
1077 qs.addObjCLifetime(implicitLifetime);
1078 return S.Context.getQualifiedType(type, qs);
1079}
1080
Douglas Gregorcd281c32009-02-28 00:25:32 +00001081/// \brief Build a pointer type.
1082///
1083/// \param T The type to which we'll be building a pointer.
1084///
Douglas Gregorcd281c32009-02-28 00:25:32 +00001085/// \param Loc The location of the entity whose type involves this
1086/// pointer type or, if there is no such entity, the location of the
1087/// type that will have pointer type.
1088///
1089/// \param Entity The name of the entity that involves the pointer
1090/// type, if known.
1091///
1092/// \returns A suitable pointer type, if there are no
1093/// errors. Otherwise, returns a NULL type.
John McCall28654742010-06-05 06:41:15 +00001094QualType Sema::BuildPointerType(QualType T,
Douglas Gregorcd281c32009-02-28 00:25:32 +00001095 SourceLocation Loc, DeclarationName Entity) {
1096 if (T->isReferenceType()) {
1097 // C++ 8.3.2p4: There shall be no ... pointers to references ...
1098 Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
John McCallac406052009-10-30 00:37:20 +00001099 << getPrintableNameForEntity(Entity) << T;
Douglas Gregorcd281c32009-02-28 00:25:32 +00001100 return QualType();
1101 }
1102
John McCallc12c5bb2010-05-15 11:32:37 +00001103 assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType");
Douglas Gregor92e986e2010-04-22 16:44:27 +00001104
John McCallf85e1932011-06-15 23:02:42 +00001105 // In ARC, it is forbidden to build pointers to unqualified pointers.
1106 if (getLangOptions().ObjCAutoRefCount)
1107 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false);
1108
Douglas Gregorcd281c32009-02-28 00:25:32 +00001109 // Build the pointer type.
John McCall28654742010-06-05 06:41:15 +00001110 return Context.getPointerType(T);
Douglas Gregorcd281c32009-02-28 00:25:32 +00001111}
1112
1113/// \brief Build a reference type.
1114///
1115/// \param T The type to which we'll be building a reference.
1116///
Douglas Gregorcd281c32009-02-28 00:25:32 +00001117/// \param Loc The location of the entity whose type involves this
1118/// reference type or, if there is no such entity, the location of the
1119/// type that will have reference type.
1120///
1121/// \param Entity The name of the entity that involves the reference
1122/// type, if known.
1123///
1124/// \returns A suitable reference type, if there are no
1125/// errors. Otherwise, returns a NULL type.
John McCall54e14c42009-10-22 22:37:11 +00001126QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue,
John McCall28654742010-06-05 06:41:15 +00001127 SourceLocation Loc,
John McCall54e14c42009-10-22 22:37:11 +00001128 DeclarationName Entity) {
Douglas Gregor9625e442011-05-21 22:16:50 +00001129 assert(Context.getCanonicalType(T) != Context.OverloadTy &&
1130 "Unresolved overloaded function type");
1131
Douglas Gregor69d83162011-01-20 16:08:06 +00001132 // C++0x [dcl.ref]p6:
1133 // If a typedef (7.1.3), a type template-parameter (14.3.1), or a
1134 // decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a
1135 // type T, an attempt to create the type "lvalue reference to cv TR" creates
1136 // the type "lvalue reference to T", while an attempt to create the type
1137 // "rvalue reference to cv TR" creates the type TR.
John McCall54e14c42009-10-22 22:37:11 +00001138 bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
1139
John McCall54e14c42009-10-22 22:37:11 +00001140 // C++ [dcl.ref]p4: There shall be no references to references.
1141 //
1142 // According to C++ DR 106, references to references are only
1143 // diagnosed when they are written directly (e.g., "int & &"),
1144 // but not when they happen via a typedef:
1145 //
1146 // typedef int& intref;
1147 // typedef intref& intref2;
1148 //
1149 // Parser::ParseDeclaratorInternal diagnoses the case where
1150 // references are written directly; here, we handle the
Douglas Gregor69d83162011-01-20 16:08:06 +00001151 // collapsing of references-to-references as described in C++0x.
1152 // DR 106 and 540 introduce reference-collapsing into C++98/03.
Douglas Gregorcd281c32009-02-28 00:25:32 +00001153
1154 // C++ [dcl.ref]p1:
Eli Friedman33a31382009-08-05 19:21:58 +00001155 // A declarator that specifies the type "reference to cv void"
Douglas Gregorcd281c32009-02-28 00:25:32 +00001156 // is ill-formed.
1157 if (T->isVoidType()) {
1158 Diag(Loc, diag::err_reference_to_void);
1159 return QualType();
1160 }
1161
John McCallf85e1932011-06-15 23:02:42 +00001162 // In ARC, it is forbidden to build references to unqualified pointers.
1163 if (getLangOptions().ObjCAutoRefCount)
1164 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true);
1165
Douglas Gregorcd281c32009-02-28 00:25:32 +00001166 // Handle restrict on references.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001167 if (LValueRef)
John McCall28654742010-06-05 06:41:15 +00001168 return Context.getLValueReferenceType(T, SpelledAsLValue);
1169 return Context.getRValueReferenceType(T);
Douglas Gregorcd281c32009-02-28 00:25:32 +00001170}
1171
Chris Lattnere1eed382011-06-14 06:38:10 +00001172/// Check whether the specified array size makes the array type a VLA. If so,
1173/// return true, if not, return the size of the array in SizeVal.
1174static bool isArraySizeVLA(Expr *ArraySize, llvm::APSInt &SizeVal, Sema &S) {
1175 // If the size is an ICE, it certainly isn't a VLA.
1176 if (ArraySize->isIntegerConstantExpr(SizeVal, S.Context))
1177 return false;
1178
1179 // If we're in a GNU mode (like gnu99, but not c99) accept any evaluatable
1180 // value as an extension.
1181 Expr::EvalResult Result;
1182 if (S.LangOpts.GNUMode && ArraySize->Evaluate(Result, S.Context)) {
1183 if (!Result.hasSideEffects() && Result.Val.isInt()) {
1184 SizeVal = Result.Val.getInt();
1185 S.Diag(ArraySize->getLocStart(), diag::ext_vla_folded_to_constant);
1186 return false;
1187 }
1188 }
1189
1190 return true;
1191}
1192
1193
Douglas Gregorcd281c32009-02-28 00:25:32 +00001194/// \brief Build an array type.
1195///
1196/// \param T The type of each element in the array.
1197///
1198/// \param ASM C99 array size modifier (e.g., '*', 'static').
Mike Stump1eb44332009-09-09 15:08:12 +00001199///
1200/// \param ArraySize Expression describing the size of the array.
Douglas Gregorcd281c32009-02-28 00:25:32 +00001201///
Douglas Gregorcd281c32009-02-28 00:25:32 +00001202/// \param Loc The location of the entity whose type involves this
1203/// array type or, if there is no such entity, the location of the
1204/// type that will have array type.
1205///
1206/// \param Entity The name of the entity that involves the array
1207/// type, if known.
1208///
1209/// \returns A suitable array type, if there are no errors. Otherwise,
1210/// returns a NULL type.
1211QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1212 Expr *ArraySize, unsigned Quals,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001213 SourceRange Brackets, DeclarationName Entity) {
John McCall0953e762009-09-24 19:53:00 +00001214
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001215 SourceLocation Loc = Brackets.getBegin();
Sebastian Redl923d56d2009-11-05 15:52:31 +00001216 if (getLangOptions().CPlusPlus) {
Douglas Gregor138bb232010-04-27 19:38:14 +00001217 // C++ [dcl.array]p1:
1218 // T is called the array element type; this type shall not be a reference
1219 // type, the (possibly cv-qualified) type void, a function type or an
1220 // abstract class type.
1221 //
1222 // Note: function types are handled in the common path with C.
1223 if (T->isReferenceType()) {
1224 Diag(Loc, diag::err_illegal_decl_array_of_references)
1225 << getPrintableNameForEntity(Entity) << T;
1226 return QualType();
1227 }
1228
Sebastian Redl923d56d2009-11-05 15:52:31 +00001229 if (T->isVoidType()) {
1230 Diag(Loc, diag::err_illegal_decl_array_incomplete_type) << T;
1231 return QualType();
1232 }
Douglas Gregor138bb232010-04-27 19:38:14 +00001233
1234 if (RequireNonAbstractType(Brackets.getBegin(), T,
1235 diag::err_array_of_abstract_type))
1236 return QualType();
1237
Sebastian Redl923d56d2009-11-05 15:52:31 +00001238 } else {
Douglas Gregor138bb232010-04-27 19:38:14 +00001239 // C99 6.7.5.2p1: If the element type is an incomplete or function type,
1240 // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
Sebastian Redl923d56d2009-11-05 15:52:31 +00001241 if (RequireCompleteType(Loc, T,
1242 diag::err_illegal_decl_array_incomplete_type))
1243 return QualType();
1244 }
Douglas Gregorcd281c32009-02-28 00:25:32 +00001245
1246 if (T->isFunctionType()) {
1247 Diag(Loc, diag::err_illegal_decl_array_of_functions)
John McCallac406052009-10-30 00:37:20 +00001248 << getPrintableNameForEntity(Entity) << T;
Douglas Gregorcd281c32009-02-28 00:25:32 +00001249 return QualType();
1250 }
Mike Stump1eb44332009-09-09 15:08:12 +00001251
Richard Smith34b41d92011-02-20 03:19:35 +00001252 if (T->getContainedAutoType()) {
1253 Diag(Loc, diag::err_illegal_decl_array_of_auto)
1254 << getPrintableNameForEntity(Entity) << T;
Anders Carlssone7cf07d2009-06-26 19:33:28 +00001255 return QualType();
1256 }
Mike Stump1eb44332009-09-09 15:08:12 +00001257
Ted Kremenek6217b802009-07-29 21:53:49 +00001258 if (const RecordType *EltTy = T->getAs<RecordType>()) {
Douglas Gregorcd281c32009-02-28 00:25:32 +00001259 // If the element type is a struct or union that contains a variadic
1260 // array, accept it as a GNU extension: C99 6.7.2.1p2.
1261 if (EltTy->getDecl()->hasFlexibleArrayMember())
1262 Diag(Loc, diag::ext_flexible_array_in_array) << T;
John McCallc12c5bb2010-05-15 11:32:37 +00001263 } else if (T->isObjCObjectType()) {
Chris Lattnerc7c11b12009-04-27 01:55:56 +00001264 Diag(Loc, diag::err_objc_array_of_interfaces) << T;
1265 return QualType();
Douglas Gregorcd281c32009-02-28 00:25:32 +00001266 }
Mike Stump1eb44332009-09-09 15:08:12 +00001267
John McCall5e3c67b2010-12-15 04:42:30 +00001268 // Do lvalue-to-rvalue conversions on the array size expression.
John Wiegley429bb272011-04-08 18:41:53 +00001269 if (ArraySize && !ArraySize->isRValue()) {
1270 ExprResult Result = DefaultLvalueConversion(ArraySize);
1271 if (Result.isInvalid())
1272 return QualType();
1273
1274 ArraySize = Result.take();
1275 }
John McCall5e3c67b2010-12-15 04:42:30 +00001276
Douglas Gregorcd281c32009-02-28 00:25:32 +00001277 // C99 6.7.5.2p1: The size expression shall have integer type.
John McCall5e3c67b2010-12-15 04:42:30 +00001278 // TODO: in theory, if we were insane, we could allow contextual
1279 // conversions to integer type here.
Douglas Gregorcd281c32009-02-28 00:25:32 +00001280 if (ArraySize && !ArraySize->isTypeDependent() &&
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001281 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
Douglas Gregorcd281c32009-02-28 00:25:32 +00001282 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
1283 << ArraySize->getType() << ArraySize->getSourceRange();
Douglas Gregorcd281c32009-02-28 00:25:32 +00001284 return QualType();
1285 }
Douglas Gregor2767ce22010-08-18 00:39:00 +00001286 llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType()));
Douglas Gregorcd281c32009-02-28 00:25:32 +00001287 if (!ArraySize) {
Eli Friedmanf91f5c82009-04-26 21:57:51 +00001288 if (ASM == ArrayType::Star)
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001289 T = Context.getVariableArrayType(T, 0, ASM, Quals, Brackets);
Eli Friedmanf91f5c82009-04-26 21:57:51 +00001290 else
1291 T = Context.getIncompleteArrayType(T, ASM, Quals);
Douglas Gregorac06a0e2010-05-18 23:01:22 +00001292 } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) {
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001293 T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets);
Chris Lattnere1eed382011-06-14 06:38:10 +00001294 } else if (!T->isDependentType() && !T->isIncompleteType() &&
1295 !T->isConstantSizeType()) {
1296 // C99: an array with an element type that has a non-constant-size is a VLA.
1297 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
1298 } else if (isArraySizeVLA(ArraySize, ConstVal, *this)) {
1299 // C99: an array with a non-ICE size is a VLA. We accept any expression
1300 // that we can fold to a non-zero positive value as an extension.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001301 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
Douglas Gregorcd281c32009-02-28 00:25:32 +00001302 } else {
1303 // C99 6.7.5.2p1: If the expression is a constant expression, it shall
1304 // have a value greater than zero.
Sebastian Redl923d56d2009-11-05 15:52:31 +00001305 if (ConstVal.isSigned() && ConstVal.isNegative()) {
Chandler Carruthb2b5cc02011-01-04 04:44:35 +00001306 if (Entity)
1307 Diag(ArraySize->getLocStart(), diag::err_decl_negative_array_size)
1308 << getPrintableNameForEntity(Entity) << ArraySize->getSourceRange();
1309 else
1310 Diag(ArraySize->getLocStart(), diag::err_typecheck_negative_array_size)
1311 << ArraySize->getSourceRange();
Sebastian Redl923d56d2009-11-05 15:52:31 +00001312 return QualType();
1313 }
1314 if (ConstVal == 0) {
Douglas Gregor02024a92010-03-28 02:42:43 +00001315 // GCC accepts zero sized static arrays. We allow them when
1316 // we're not in a SFINAE context.
1317 Diag(ArraySize->getLocStart(),
1318 isSFINAEContext()? diag::err_typecheck_zero_array_size
1319 : diag::ext_typecheck_zero_array_size)
Sebastian Redl923d56d2009-11-05 15:52:31 +00001320 << ArraySize->getSourceRange();
Douglas Gregor2767ce22010-08-18 00:39:00 +00001321 } else if (!T->isDependentType() && !T->isVariablyModifiedType() &&
1322 !T->isIncompleteType()) {
1323 // Is the array too large?
1324 unsigned ActiveSizeBits
1325 = ConstantArrayType::getNumAddressingBits(Context, T, ConstVal);
1326 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
1327 Diag(ArraySize->getLocStart(), diag::err_array_too_large)
1328 << ConstVal.toString(10)
1329 << ArraySize->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001330 }
Douglas Gregor2767ce22010-08-18 00:39:00 +00001331
John McCall46a617a2009-10-16 00:14:28 +00001332 T = Context.getConstantArrayType(T, ConstVal, ASM, Quals);
Douglas Gregorcd281c32009-02-28 00:25:32 +00001333 }
David Chisnallaf407762010-01-11 23:08:08 +00001334 // If this is not C99, extwarn about VLA's and C99 array size modifiers.
1335 if (!getLangOptions().C99) {
Douglas Gregor0fddb972010-05-22 16:17:30 +00001336 if (T->isVariableArrayType()) {
1337 // Prohibit the use of non-POD types in VLAs.
John McCallf85e1932011-06-15 23:02:42 +00001338 QualType BaseT = Context.getBaseElementType(T);
Douglas Gregor204ce172010-05-24 20:42:30 +00001339 if (!T->isDependentType() &&
John McCallf85e1932011-06-15 23:02:42 +00001340 !BaseT.isPODType(Context) &&
1341 !BaseT->isObjCLifetimeType()) {
Douglas Gregor0fddb972010-05-22 16:17:30 +00001342 Diag(Loc, diag::err_vla_non_pod)
John McCallf85e1932011-06-15 23:02:42 +00001343 << BaseT;
Douglas Gregor0fddb972010-05-22 16:17:30 +00001344 return QualType();
1345 }
Douglas Gregora481ec42010-05-23 19:57:01 +00001346 // Prohibit the use of VLAs during template argument deduction.
1347 else if (isSFINAEContext()) {
1348 Diag(Loc, diag::err_vla_in_sfinae);
1349 return QualType();
1350 }
Douglas Gregor0fddb972010-05-22 16:17:30 +00001351 // Just extwarn about VLAs.
1352 else
1353 Diag(Loc, diag::ext_vla);
1354 } else if (ASM != ArrayType::Normal || Quals != 0)
Douglas Gregor043cad22009-09-11 00:18:58 +00001355 Diag(Loc,
1356 getLangOptions().CPlusPlus? diag::err_c99_array_usage_cxx
1357 : diag::ext_c99_array_usage);
Douglas Gregorcd281c32009-02-28 00:25:32 +00001358 }
1359
1360 return T;
1361}
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001362
1363/// \brief Build an ext-vector type.
1364///
1365/// Run the required checks for the extended vector type.
John McCall9ae2f072010-08-23 23:25:46 +00001366QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize,
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001367 SourceLocation AttrLoc) {
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001368 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1369 // in conjunction with complex types (pointers, arrays, functions, etc.).
Mike Stump1eb44332009-09-09 15:08:12 +00001370 if (!T->isDependentType() &&
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001371 !T->isIntegerType() && !T->isRealFloatingType()) {
1372 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
1373 return QualType();
1374 }
1375
John McCall9ae2f072010-08-23 23:25:46 +00001376 if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) {
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001377 llvm::APSInt vecSize(32);
John McCall9ae2f072010-08-23 23:25:46 +00001378 if (!ArraySize->isIntegerConstantExpr(vecSize, Context)) {
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001379 Diag(AttrLoc, diag::err_attribute_argument_not_int)
John McCall9ae2f072010-08-23 23:25:46 +00001380 << "ext_vector_type" << ArraySize->getSourceRange();
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001381 return QualType();
1382 }
Mike Stump1eb44332009-09-09 15:08:12 +00001383
1384 // unlike gcc's vector_size attribute, the size is specified as the
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001385 // number of elements, not the number of bytes.
Mike Stump1eb44332009-09-09 15:08:12 +00001386 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
1387
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001388 if (vectorSize == 0) {
1389 Diag(AttrLoc, diag::err_attribute_zero_size)
John McCall9ae2f072010-08-23 23:25:46 +00001390 << ArraySize->getSourceRange();
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001391 return QualType();
1392 }
Mike Stump1eb44332009-09-09 15:08:12 +00001393
Douglas Gregor4ac01402011-06-15 16:02:29 +00001394 return Context.getExtVectorType(T, vectorSize);
Mike Stump1eb44332009-09-09 15:08:12 +00001395 }
1396
John McCall9ae2f072010-08-23 23:25:46 +00001397 return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc);
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001398}
Mike Stump1eb44332009-09-09 15:08:12 +00001399
Douglas Gregor724651c2009-02-28 01:04:19 +00001400/// \brief Build a function type.
1401///
1402/// This routine checks the function type according to C++ rules and
1403/// under the assumption that the result type and parameter types have
1404/// just been instantiated from a template. It therefore duplicates
Douglas Gregor2943aed2009-03-03 04:44:36 +00001405/// some of the behavior of GetTypeForDeclarator, but in a much
Douglas Gregor724651c2009-02-28 01:04:19 +00001406/// simpler form that is only suitable for this narrow use case.
1407///
1408/// \param T The return type of the function.
1409///
1410/// \param ParamTypes The parameter types of the function. This array
1411/// will be modified to account for adjustments to the types of the
1412/// function parameters.
1413///
1414/// \param NumParamTypes The number of parameter types in ParamTypes.
1415///
1416/// \param Variadic Whether this is a variadic function type.
1417///
1418/// \param Quals The cvr-qualifiers to be applied to the function type.
1419///
1420/// \param Loc The location of the entity whose type involves this
1421/// function type or, if there is no such entity, the location of the
1422/// type that will have function type.
1423///
1424/// \param Entity The name of the entity that involves the function
1425/// type, if known.
1426///
1427/// \returns A suitable function type, if there are no
1428/// errors. Otherwise, returns a NULL type.
1429QualType Sema::BuildFunctionType(QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00001430 QualType *ParamTypes,
Douglas Gregor724651c2009-02-28 01:04:19 +00001431 unsigned NumParamTypes,
1432 bool Variadic, unsigned Quals,
Douglas Gregorc938c162011-01-26 05:01:58 +00001433 RefQualifierKind RefQualifier,
Eli Friedmanfa869542010-08-05 02:54:05 +00001434 SourceLocation Loc, DeclarationName Entity,
John McCalle23cf432010-12-14 08:05:40 +00001435 FunctionType::ExtInfo Info) {
Douglas Gregor724651c2009-02-28 01:04:19 +00001436 if (T->isArrayType() || T->isFunctionType()) {
Douglas Gregor58408bc2010-01-11 18:46:21 +00001437 Diag(Loc, diag::err_func_returning_array_function)
1438 << T->isFunctionType() << T;
Douglas Gregor724651c2009-02-28 01:04:19 +00001439 return QualType();
1440 }
Douglas Gregor5291c3c2010-07-13 08:18:22 +00001441
Douglas Gregor724651c2009-02-28 01:04:19 +00001442 bool Invalid = false;
1443 for (unsigned Idx = 0; Idx < NumParamTypes; ++Idx) {
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001444 QualType ParamType = adjustParameterType(ParamTypes[Idx]);
1445 if (ParamType->isVoidType()) {
Douglas Gregor724651c2009-02-28 01:04:19 +00001446 Diag(Loc, diag::err_param_with_void_type);
1447 Invalid = true;
1448 }
Douglas Gregorcd281c32009-02-28 00:25:32 +00001449
John McCall54e14c42009-10-22 22:37:11 +00001450 ParamTypes[Idx] = ParamType;
Douglas Gregor724651c2009-02-28 01:04:19 +00001451 }
1452
1453 if (Invalid)
1454 return QualType();
1455
John McCalle23cf432010-12-14 08:05:40 +00001456 FunctionProtoType::ExtProtoInfo EPI;
1457 EPI.Variadic = Variadic;
1458 EPI.TypeQuals = Quals;
Douglas Gregorc938c162011-01-26 05:01:58 +00001459 EPI.RefQualifier = RefQualifier;
John McCalle23cf432010-12-14 08:05:40 +00001460 EPI.ExtInfo = Info;
1461
1462 return Context.getFunctionType(T, ParamTypes, NumParamTypes, EPI);
Douglas Gregor724651c2009-02-28 01:04:19 +00001463}
Mike Stump1eb44332009-09-09 15:08:12 +00001464
Douglas Gregor949bf692009-06-09 22:17:39 +00001465/// \brief Build a member pointer type \c T Class::*.
1466///
1467/// \param T the type to which the member pointer refers.
1468/// \param Class the class type into which the member pointer points.
John McCall0953e762009-09-24 19:53:00 +00001469/// \param CVR Qualifiers applied to the member pointer type
Douglas Gregor949bf692009-06-09 22:17:39 +00001470/// \param Loc the location where this type begins
1471/// \param Entity the name of the entity that will have this member pointer type
1472///
1473/// \returns a member pointer type, if successful, or a NULL type if there was
1474/// an error.
Mike Stump1eb44332009-09-09 15:08:12 +00001475QualType Sema::BuildMemberPointerType(QualType T, QualType Class,
John McCall28654742010-06-05 06:41:15 +00001476 SourceLocation Loc,
Douglas Gregor949bf692009-06-09 22:17:39 +00001477 DeclarationName Entity) {
1478 // Verify that we're not building a pointer to pointer to function with
1479 // exception specification.
1480 if (CheckDistantExceptionSpec(T)) {
1481 Diag(Loc, diag::err_distant_exception_spec);
1482
1483 // FIXME: If we're doing this as part of template instantiation,
1484 // we should return immediately.
1485
1486 // Build the type anyway, but use the canonical type so that the
1487 // exception specifiers are stripped off.
1488 T = Context.getCanonicalType(T);
1489 }
1490
Sebastian Redl73780122010-06-09 21:19:43 +00001491 // C++ 8.3.3p3: A pointer to member shall not point to ... a member
Douglas Gregor949bf692009-06-09 22:17:39 +00001492 // with reference type, or "cv void."
1493 if (T->isReferenceType()) {
Anders Carlsson8d4655d2009-06-30 00:06:57 +00001494 Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
John McCallac406052009-10-30 00:37:20 +00001495 << (Entity? Entity.getAsString() : "type name") << T;
Douglas Gregor949bf692009-06-09 22:17:39 +00001496 return QualType();
1497 }
1498
1499 if (T->isVoidType()) {
1500 Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
1501 << (Entity? Entity.getAsString() : "type name");
1502 return QualType();
1503 }
1504
Douglas Gregor949bf692009-06-09 22:17:39 +00001505 if (!Class->isDependentType() && !Class->isRecordType()) {
1506 Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
1507 return QualType();
1508 }
1509
Charles Davisd18f9f92010-08-16 04:01:50 +00001510 // In the Microsoft ABI, the class is allowed to be an incomplete
1511 // type. In such cases, the compiler makes a worst-case assumption.
1512 // We make no such assumption right now, so emit an error if the
1513 // class isn't a complete type.
Charles Davis20cf7172010-08-19 02:18:14 +00001514 if (Context.Target.getCXXABI() == CXXABI_Microsoft &&
Charles Davisd18f9f92010-08-16 04:01:50 +00001515 RequireCompleteType(Loc, Class, diag::err_incomplete_type))
1516 return QualType();
1517
John McCall28654742010-06-05 06:41:15 +00001518 return Context.getMemberPointerType(T, Class.getTypePtr());
Douglas Gregor949bf692009-06-09 22:17:39 +00001519}
Mike Stump1eb44332009-09-09 15:08:12 +00001520
Anders Carlsson9a917e42009-06-12 22:56:54 +00001521/// \brief Build a block pointer type.
1522///
1523/// \param T The type to which we'll be building a block pointer.
1524///
John McCall0953e762009-09-24 19:53:00 +00001525/// \param CVR The cvr-qualifiers to be applied to the block pointer type.
Anders Carlsson9a917e42009-06-12 22:56:54 +00001526///
1527/// \param Loc The location of the entity whose type involves this
1528/// block pointer type or, if there is no such entity, the location of the
1529/// type that will have block pointer type.
1530///
1531/// \param Entity The name of the entity that involves the block pointer
1532/// type, if known.
1533///
1534/// \returns A suitable block pointer type, if there are no
1535/// errors. Otherwise, returns a NULL type.
John McCall28654742010-06-05 06:41:15 +00001536QualType Sema::BuildBlockPointerType(QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00001537 SourceLocation Loc,
Anders Carlsson9a917e42009-06-12 22:56:54 +00001538 DeclarationName Entity) {
John McCall0953e762009-09-24 19:53:00 +00001539 if (!T->isFunctionType()) {
Anders Carlsson9a917e42009-06-12 22:56:54 +00001540 Diag(Loc, diag::err_nonfunction_block_type);
1541 return QualType();
1542 }
Mike Stump1eb44332009-09-09 15:08:12 +00001543
John McCall28654742010-06-05 06:41:15 +00001544 return Context.getBlockPointerType(T);
Anders Carlsson9a917e42009-06-12 22:56:54 +00001545}
1546
John McCallb3d87482010-08-24 05:47:05 +00001547QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) {
1548 QualType QT = Ty.get();
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001549 if (QT.isNull()) {
John McCalla93c9342009-12-07 02:54:59 +00001550 if (TInfo) *TInfo = 0;
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001551 return QualType();
1552 }
1553
John McCalla93c9342009-12-07 02:54:59 +00001554 TypeSourceInfo *DI = 0;
John McCallf4c73712011-01-19 06:33:43 +00001555 if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001556 QT = LIT->getType();
John McCalla93c9342009-12-07 02:54:59 +00001557 DI = LIT->getTypeSourceInfo();
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001558 }
Mike Stump1eb44332009-09-09 15:08:12 +00001559
John McCalla93c9342009-12-07 02:54:59 +00001560 if (TInfo) *TInfo = DI;
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001561 return QT;
1562}
1563
John McCallf85e1932011-06-15 23:02:42 +00001564/// Given that this is the declaration of a parameter under ARC,
1565/// attempt to infer attributes and such for pointer-to-whatever
1566/// types.
1567static void inferARCWriteback(TypeProcessingState &state,
1568 QualType &declSpecType) {
1569 Sema &S = state.getSema();
1570 Declarator &declarator = state.getDeclarator();
1571
1572 // TODO: should we care about decl qualifiers?
1573
1574 // Check whether the declarator has the expected form. We walk
1575 // from the inside out in order to make the block logic work.
1576 unsigned outermostPointerIndex = 0;
1577 bool isBlockPointer = false;
1578 unsigned numPointers = 0;
1579 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
1580 unsigned chunkIndex = i;
1581 DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex);
1582 switch (chunk.Kind) {
1583 case DeclaratorChunk::Paren:
1584 // Ignore parens.
1585 break;
1586
1587 case DeclaratorChunk::Reference:
1588 case DeclaratorChunk::Pointer:
1589 // Count the number of pointers. Treat references
1590 // interchangeably as pointers; if they're mis-ordered, normal
1591 // type building will discover that.
1592 outermostPointerIndex = chunkIndex;
1593 numPointers++;
1594 break;
1595
1596 case DeclaratorChunk::BlockPointer:
1597 // If we have a pointer to block pointer, that's an acceptable
1598 // indirect reference; anything else is not an application of
1599 // the rules.
1600 if (numPointers != 1) return;
1601 numPointers++;
1602 outermostPointerIndex = chunkIndex;
1603 isBlockPointer = true;
1604
1605 // We don't care about pointer structure in return values here.
1606 goto done;
1607
1608 case DeclaratorChunk::Array: // suppress if written (id[])?
1609 case DeclaratorChunk::Function:
1610 case DeclaratorChunk::MemberPointer:
1611 return;
1612 }
1613 }
1614 done:
1615
1616 // If we have *one* pointer, then we want to throw the qualifier on
1617 // the declaration-specifiers, which means that it needs to be a
1618 // retainable object type.
1619 if (numPointers == 1) {
1620 // If it's not a retainable object type, the rule doesn't apply.
1621 if (!declSpecType->isObjCRetainableType()) return;
1622
1623 // If it already has lifetime, don't do anything.
1624 if (declSpecType.getObjCLifetime()) return;
1625
1626 // Otherwise, modify the type in-place.
1627 Qualifiers qs;
1628
1629 if (declSpecType->isObjCARCImplicitlyUnretainedType())
1630 qs.addObjCLifetime(Qualifiers::OCL_ExplicitNone);
1631 else
1632 qs.addObjCLifetime(Qualifiers::OCL_Autoreleasing);
1633 declSpecType = S.Context.getQualifiedType(declSpecType, qs);
1634
1635 // If we have *two* pointers, then we want to throw the qualifier on
1636 // the outermost pointer.
1637 } else if (numPointers == 2) {
1638 // If we don't have a block pointer, we need to check whether the
1639 // declaration-specifiers gave us something that will turn into a
1640 // retainable object pointer after we slap the first pointer on it.
1641 if (!isBlockPointer && !declSpecType->isObjCObjectType())
1642 return;
1643
1644 // Look for an explicit lifetime attribute there.
1645 DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex);
1646 assert(chunk.Kind == DeclaratorChunk::Pointer ||
1647 chunk.Kind == DeclaratorChunk::BlockPointer);
1648 for (const AttributeList *attr = chunk.getAttrs(); attr;
1649 attr = attr->getNext())
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00001650 if (attr->getKind() == AttributeList::AT_objc_ownership)
John McCallf85e1932011-06-15 23:02:42 +00001651 return;
1652
1653 // If there wasn't one, add one (with an invalid source location
1654 // so that we don't make an AttributedType for it).
1655 AttributeList *attr = declarator.getAttributePool()
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00001656 .create(&S.Context.Idents.get("objc_ownership"), SourceLocation(),
John McCallf85e1932011-06-15 23:02:42 +00001657 /*scope*/ 0, SourceLocation(),
1658 &S.Context.Idents.get("autoreleasing"), SourceLocation(),
1659 /*args*/ 0, 0,
1660 /*declspec*/ false, /*C++0x*/ false);
1661 spliceAttrIntoList(*attr, chunk.getAttrListRef());
1662
1663 // Any other number of pointers/references does not trigger the rule.
1664 } else return;
1665
1666 // TODO: mark whether we did this inference?
1667}
1668
Chandler Carruthd067c072011-02-23 18:51:59 +00001669static void DiagnoseIgnoredQualifiers(unsigned Quals,
1670 SourceLocation ConstQualLoc,
1671 SourceLocation VolatileQualLoc,
1672 SourceLocation RestrictQualLoc,
1673 Sema& S) {
1674 std::string QualStr;
1675 unsigned NumQuals = 0;
1676 SourceLocation Loc;
1677
1678 FixItHint ConstFixIt;
1679 FixItHint VolatileFixIt;
1680 FixItHint RestrictFixIt;
1681
Hans Wennborga08fcb82011-06-03 17:37:26 +00001682 const SourceManager &SM = S.getSourceManager();
1683
Chandler Carruthd067c072011-02-23 18:51:59 +00001684 // FIXME: The locations here are set kind of arbitrarily. It'd be nicer to
1685 // find a range and grow it to encompass all the qualifiers, regardless of
1686 // the order in which they textually appear.
1687 if (Quals & Qualifiers::Const) {
1688 ConstFixIt = FixItHint::CreateRemoval(ConstQualLoc);
Chandler Carruthd067c072011-02-23 18:51:59 +00001689 QualStr = "const";
Hans Wennborga08fcb82011-06-03 17:37:26 +00001690 ++NumQuals;
1691 if (!Loc.isValid() || SM.isBeforeInTranslationUnit(ConstQualLoc, Loc))
1692 Loc = ConstQualLoc;
Chandler Carruthd067c072011-02-23 18:51:59 +00001693 }
1694 if (Quals & Qualifiers::Volatile) {
1695 VolatileFixIt = FixItHint::CreateRemoval(VolatileQualLoc);
Hans Wennborga08fcb82011-06-03 17:37:26 +00001696 QualStr += (NumQuals == 0 ? "volatile" : " volatile");
Chandler Carruthd067c072011-02-23 18:51:59 +00001697 ++NumQuals;
Hans Wennborga08fcb82011-06-03 17:37:26 +00001698 if (!Loc.isValid() || SM.isBeforeInTranslationUnit(VolatileQualLoc, Loc))
1699 Loc = VolatileQualLoc;
Chandler Carruthd067c072011-02-23 18:51:59 +00001700 }
1701 if (Quals & Qualifiers::Restrict) {
1702 RestrictFixIt = FixItHint::CreateRemoval(RestrictQualLoc);
Hans Wennborga08fcb82011-06-03 17:37:26 +00001703 QualStr += (NumQuals == 0 ? "restrict" : " restrict");
Chandler Carruthd067c072011-02-23 18:51:59 +00001704 ++NumQuals;
Hans Wennborga08fcb82011-06-03 17:37:26 +00001705 if (!Loc.isValid() || SM.isBeforeInTranslationUnit(RestrictQualLoc, Loc))
1706 Loc = RestrictQualLoc;
Chandler Carruthd067c072011-02-23 18:51:59 +00001707 }
1708
1709 assert(NumQuals > 0 && "No known qualifiers?");
1710
1711 S.Diag(Loc, diag::warn_qual_return_type)
Hans Wennborga08fcb82011-06-03 17:37:26 +00001712 << QualStr << NumQuals << ConstFixIt << VolatileFixIt << RestrictFixIt;
Chandler Carruthd067c072011-02-23 18:51:59 +00001713}
1714
Mike Stump98eb8a72009-02-04 22:31:32 +00001715/// GetTypeForDeclarator - Convert the type for the specified
Sebastian Redl8ce35b02009-10-25 21:45:37 +00001716/// declarator to Type instances.
Douglas Gregor402abb52009-05-28 23:31:59 +00001717///
1718/// If OwnedDecl is non-NULL, and this declarator's decl-specifier-seq
1719/// owns the declaration of a type (e.g., the definition of a struct
1720/// type), then *OwnedDecl will receive the owned declaration.
John McCallbf1a0282010-06-04 23:28:52 +00001721///
1722/// The result of this call will never be null, but the associated
1723/// type may be a null type if there's an unrecoverable error.
Argyrios Kyrtzidis0b8c98f2011-06-28 03:01:23 +00001724TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) {
Douglas Gregor930d8b52009-01-30 22:09:00 +00001725 // Determine the type of the declarator. Not all forms of declarator
1726 // have a type.
1727 QualType T;
Douglas Gregor05baacb2010-04-12 23:19:01 +00001728 TypeSourceInfo *ReturnTypeInfo = 0;
Argyrios Kyrtzidisd3880f82011-06-28 03:01:18 +00001729 TagDecl *OwnedTagDecl = 0;
John McCall711c52b2011-01-05 12:14:39 +00001730
1731 TypeProcessingState state(*this, D);
John McCall04a67a62010-02-05 21:31:56 +00001732
Sebastian Redl8999fe12011-03-14 18:08:30 +00001733 // In C++0x, deallocation functions (normal and array operator delete)
1734 // are implicitly noexcept.
1735 bool ImplicitlyNoexcept = false;
1736
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001737 switch (D.getName().getKind()) {
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001738 case UnqualifiedId::IK_OperatorFunctionId:
Sebastian Redl8999fe12011-03-14 18:08:30 +00001739 if (getLangOptions().CPlusPlus0x) {
1740 OverloadedOperatorKind OO = D.getName().OperatorFunctionId.Operator;
1741 if (OO == OO_Delete || OO == OO_Array_Delete)
1742 ImplicitlyNoexcept = true;
1743 }
1744 // Intentional fall-through.
1745 case UnqualifiedId::IK_Identifier:
Sean Hunt0486d742009-11-28 04:44:28 +00001746 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001747 case UnqualifiedId::IK_TemplateId:
John McCall711c52b2011-01-05 12:14:39 +00001748 T = ConvertDeclSpecToType(*this, state);
Chris Lattner5db2bb12009-10-25 18:21:37 +00001749
Douglas Gregor591bd3c2010-02-08 22:07:33 +00001750 if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) {
Argyrios Kyrtzidisd3880f82011-06-28 03:01:18 +00001751 OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
Abramo Bagnara15987972011-03-08 22:33:38 +00001752 // Owned declaration is embedded in declarator.
Argyrios Kyrtzidisd3880f82011-06-28 03:01:18 +00001753 OwnedTagDecl->setEmbeddedInDeclarator(true);
Douglas Gregor591bd3c2010-02-08 22:07:33 +00001754 }
Douglas Gregor930d8b52009-01-30 22:09:00 +00001755 break;
1756
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001757 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00001758 case UnqualifiedId::IK_ConstructorTemplateId:
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001759 case UnqualifiedId::IK_DestructorName:
Douglas Gregor930d8b52009-01-30 22:09:00 +00001760 // Constructors and destructors don't have return types. Use
Douglas Gregor48026d22010-01-11 18:40:55 +00001761 // "void" instead.
Douglas Gregor930d8b52009-01-30 22:09:00 +00001762 T = Context.VoidTy;
1763 break;
Douglas Gregor48026d22010-01-11 18:40:55 +00001764
1765 case UnqualifiedId::IK_ConversionFunctionId:
1766 // The result type of a conversion function is the type that it
1767 // converts to.
Douglas Gregor05baacb2010-04-12 23:19:01 +00001768 T = GetTypeFromParser(D.getName().ConversionFunctionId,
John McCallbf1a0282010-06-04 23:28:52 +00001769 &ReturnTypeInfo);
Douglas Gregor48026d22010-01-11 18:40:55 +00001770 break;
Douglas Gregor930d8b52009-01-30 22:09:00 +00001771 }
Douglas Gregordab60ad2010-10-01 18:44:50 +00001772
John McCall711c52b2011-01-05 12:14:39 +00001773 if (D.getAttributes())
1774 distributeTypeAttrsFromDeclarator(state, T);
1775
John McCallf85e1932011-06-15 23:02:42 +00001776 if (D.isPrototypeContext() && getLangOptions().ObjCAutoRefCount)
1777 inferARCWriteback(state, T);
1778
Richard Smithe7397c62011-02-22 00:36:53 +00001779 // C++0x [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context.
Richard Smith8110f042011-02-22 01:22:29 +00001780 // In C++0x, a function declarator using 'auto' must have a trailing return
1781 // type (this is checked later) and we can skip this. In other languages
1782 // using auto, we need to check regardless.
Richard Smith34b41d92011-02-20 03:19:35 +00001783 if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto &&
Richard Smith8110f042011-02-22 01:22:29 +00001784 (!getLangOptions().CPlusPlus0x || !D.isFunctionDeclarator())) {
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001785 int Error = -1;
Mike Stump1eb44332009-09-09 15:08:12 +00001786
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001787 switch (D.getContext()) {
1788 case Declarator::KNRTypeListContext:
1789 assert(0 && "K&R type lists aren't allowed in C++");
1790 break;
John McCallc05a94b2011-03-23 23:43:04 +00001791 case Declarator::ObjCPrototypeContext:
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;
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001798 switch (cast<TagDecl>(CurContext)->getTagKind()) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001799 case TTK_Enum: assert(0 && "unhandled tag kind"); break;
1800 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.
Richard Smith8110f042011-02-22 01:22:29 +00001844 if (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) {
1860 Diag(D.getDeclSpec().getTypeSpecTypeLoc(), diag::err_auto_not_allowed)
1861 << Error;
1862 T = Context.IntTy;
1863 D.setInvalidType(true);
1864 }
1865 }
Richard Smithe7397c62011-02-22 00:36:53 +00001866
Richard Smith34b41d92011-02-20 03:19:35 +00001867 if (T.isNull())
1868 return Context.getNullTypeSourceInfo();
1869
Douglas Gregorcd281c32009-02-28 00:25:32 +00001870 // The name we're declaring, if any.
1871 DeclarationName Name;
1872 if (D.getIdentifier())
1873 Name = D.getIdentifier();
Mike Stump1eb44332009-09-09 15:08:12 +00001874
Richard Smith162e1c12011-04-15 14:24:37 +00001875 // Does this declaration declare a typedef-name?
1876 bool IsTypedefName =
1877 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef ||
Richard Smith3e4c6c42011-05-05 21:57:07 +00001878 D.getContext() == Declarator::AliasDeclContext ||
1879 D.getContext() == Declarator::AliasTemplateContext;
Richard Smith162e1c12011-04-15 14:24:37 +00001880
Mike Stump98eb8a72009-02-04 22:31:32 +00001881 // Walk the DeclTypeInfo, building the recursive type as we go.
1882 // DeclTypeInfos are ordered from the identifier out, which is
1883 // opposite of what we want :).
Sebastian Redl8ce35b02009-10-25 21:45:37 +00001884 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
John McCall711c52b2011-01-05 12:14:39 +00001885 unsigned chunkIndex = e - i - 1;
1886 state.setCurrentChunkIndex(chunkIndex);
1887 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001888 switch (DeclType.Kind) {
1889 default: assert(0 && "Unknown decltype!");
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001890 case DeclaratorChunk::Paren:
1891 T = BuildParenType(T);
1892 break;
Steve Naroff5618bd42008-08-27 16:04:49 +00001893 case DeclaratorChunk::BlockPointer:
Chris Lattner9af55002009-03-27 04:18:06 +00001894 // If blocks are disabled, emit an error.
1895 if (!LangOpts.Blocks)
1896 Diag(DeclType.Loc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +00001897
John McCall28654742010-06-05 06:41:15 +00001898 T = BuildBlockPointerType(T, D.getIdentifierLoc(), Name);
1899 if (DeclType.Cls.TypeQuals)
1900 T = BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals);
Steve Naroff5618bd42008-08-27 16:04:49 +00001901 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001902 case DeclaratorChunk::Pointer:
Sebastian Redl6a7330c2009-05-29 15:01:05 +00001903 // Verify that we're not building a pointer to pointer to function with
1904 // exception specification.
1905 if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) {
1906 Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
1907 D.setInvalidType(true);
1908 // Build the type anyway.
1909 }
John McCallc12c5bb2010-05-15 11:32:37 +00001910 if (getLangOptions().ObjC1 && T->getAs<ObjCObjectType>()) {
1911 T = Context.getObjCObjectPointerType(T);
John McCall28654742010-06-05 06:41:15 +00001912 if (DeclType.Ptr.TypeQuals)
1913 T = BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
Steve Naroff14108da2009-07-10 23:34:53 +00001914 break;
1915 }
John McCall28654742010-06-05 06:41:15 +00001916 T = BuildPointerType(T, DeclType.Loc, Name);
1917 if (DeclType.Ptr.TypeQuals)
1918 T = BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
John McCall711c52b2011-01-05 12:14:39 +00001919
Reid Spencer5f016e22007-07-11 17:01:13 +00001920 break;
John McCall0953e762009-09-24 19:53:00 +00001921 case DeclaratorChunk::Reference: {
Sebastian Redl6a7330c2009-05-29 15:01:05 +00001922 // Verify that we're not building a reference to pointer to function with
1923 // exception specification.
1924 if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) {
1925 Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
1926 D.setInvalidType(true);
1927 // Build the type anyway.
1928 }
John McCall28654742010-06-05 06:41:15 +00001929 T = BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name);
1930
1931 Qualifiers Quals;
1932 if (DeclType.Ref.HasRestrict)
1933 T = BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict);
Reid Spencer5f016e22007-07-11 17:01:13 +00001934 break;
John McCall0953e762009-09-24 19:53:00 +00001935 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001936 case DeclaratorChunk::Array: {
Sebastian Redl6a7330c2009-05-29 15:01:05 +00001937 // Verify that we're not building an array of pointers to function with
1938 // exception specification.
1939 if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) {
1940 Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
1941 D.setInvalidType(true);
1942 // Build the type anyway.
1943 }
Chris Lattnerfd89bc82008-04-02 01:05:10 +00001944 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
Chris Lattner94f81fd2007-08-28 16:54:00 +00001945 Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
Reid Spencer5f016e22007-07-11 17:01:13 +00001946 ArrayType::ArraySizeModifier ASM;
1947 if (ATI.isStar)
1948 ASM = ArrayType::Star;
1949 else if (ATI.hasStatic)
1950 ASM = ArrayType::Static;
1951 else
1952 ASM = ArrayType::Normal;
John McCallc05a94b2011-03-23 23:43:04 +00001953 if (ASM == ArrayType::Star && !D.isPrototypeContext()) {
Eli Friedmanf91f5c82009-04-26 21:57:51 +00001954 // FIXME: This check isn't quite right: it allows star in prototypes
1955 // for function definitions, and disallows some edge cases detailed
1956 // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
1957 Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
1958 ASM = ArrayType::Normal;
1959 D.setInvalidType(true);
1960 }
John McCall0953e762009-09-24 19:53:00 +00001961 T = BuildArrayType(T, ASM, ArraySize,
1962 Qualifiers::fromCVRMask(ATI.TypeQuals),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001963 SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
Reid Spencer5f016e22007-07-11 17:01:13 +00001964 break;
1965 }
Sebastian Redlf30208a2009-01-24 21:16:55 +00001966 case DeclaratorChunk::Function: {
Reid Spencer5f016e22007-07-11 17:01:13 +00001967 // If the function declarator has a prototype (i.e. it is not () and
1968 // does not have a K&R-style identifier list), then the arguments are part
1969 // of the type, otherwise the argument list is ().
1970 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
Sebastian Redl3cc97262009-05-31 11:47:27 +00001971
Richard Smithe7397c62011-02-22 00:36:53 +00001972 // Check for auto functions and trailing return type and adjust the
1973 // return type accordingly.
1974 if (!D.isInvalidType()) {
1975 // trailing-return-type is only required if we're declaring a function,
1976 // and not, for instance, a pointer to a function.
1977 if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto &&
1978 !FTI.TrailingReturnType && chunkIndex == 0) {
1979 Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
1980 diag::err_auto_missing_trailing_return);
1981 T = Context.IntTy;
1982 D.setInvalidType(true);
1983 } else if (FTI.TrailingReturnType) {
1984 // T must be exactly 'auto' at this point. See CWG issue 681.
1985 if (isa<ParenType>(T)) {
1986 Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
1987 diag::err_trailing_return_in_parens)
1988 << T << D.getDeclSpec().getSourceRange();
1989 D.setInvalidType(true);
1990 } else if (T.hasQualifiers() || !isa<AutoType>(T)) {
1991 Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
1992 diag::err_trailing_return_without_auto)
1993 << T << D.getDeclSpec().getSourceRange();
1994 D.setInvalidType(true);
1995 }
1996
1997 T = GetTypeFromParser(
1998 ParsedType::getFromOpaquePtr(FTI.TrailingReturnType),
1999 &ReturnTypeInfo);
2000 }
2001 }
2002
Chris Lattnercd881292007-12-19 05:31:29 +00002003 // C99 6.7.5.3p1: The return type may not be a function or array type.
Douglas Gregor58408bc2010-01-11 18:46:21 +00002004 // For conversion functions, we'll diagnose this particular error later.
Douglas Gregor48026d22010-01-11 18:40:55 +00002005 if ((T->isArrayType() || T->isFunctionType()) &&
2006 (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId)) {
Argyrios Kyrtzidis98650442011-01-25 23:16:33 +00002007 unsigned diagID = diag::err_func_returning_array_function;
Argyrios Kyrtzidisa4356ad2011-01-26 01:26:44 +00002008 // Last processing chunk in block context means this function chunk
2009 // represents the block.
2010 if (chunkIndex == 0 &&
2011 D.getContext() == Declarator::BlockLiteralContext)
Argyrios Kyrtzidis98650442011-01-25 23:16:33 +00002012 diagID = diag::err_block_returning_array_function;
2013 Diag(DeclType.Loc, diagID) << T->isFunctionType() << T;
Chris Lattnercd881292007-12-19 05:31:29 +00002014 T = Context.IntTy;
2015 D.setInvalidType(true);
2016 }
Sebastian Redl465226e2009-05-27 22:11:52 +00002017
Douglas Gregor5291c3c2010-07-13 08:18:22 +00002018 // cv-qualifiers on return types are pointless except when the type is a
2019 // class type in C++.
Douglas Gregorfff95132011-03-01 17:04:42 +00002020 if (isa<PointerType>(T) && T.getLocalCVRQualifiers() &&
Rafael Espindola1e153942011-03-11 04:56:58 +00002021 (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId) &&
Chandler Carruthd067c072011-02-23 18:51:59 +00002022 (!getLangOptions().CPlusPlus || !T->isDependentType())) {
2023 assert(chunkIndex + 1 < e && "No DeclaratorChunk for the return type?");
2024 DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1);
2025 assert(ReturnTypeChunk.Kind == DeclaratorChunk::Pointer);
2026
2027 DeclaratorChunk::PointerTypeInfo &PTI = ReturnTypeChunk.Ptr;
2028
2029 DiagnoseIgnoredQualifiers(PTI.TypeQuals,
2030 SourceLocation::getFromRawEncoding(PTI.ConstQualLoc),
2031 SourceLocation::getFromRawEncoding(PTI.VolatileQualLoc),
2032 SourceLocation::getFromRawEncoding(PTI.RestrictQualLoc),
2033 *this);
2034
2035 } else if (T.getCVRQualifiers() && D.getDeclSpec().getTypeQualifiers() &&
Douglas Gregor5291c3c2010-07-13 08:18:22 +00002036 (!getLangOptions().CPlusPlus ||
2037 (!T->isDependentType() && !T->isRecordType()))) {
Chandler Carruthd067c072011-02-23 18:51:59 +00002038
2039 DiagnoseIgnoredQualifiers(D.getDeclSpec().getTypeQualifiers(),
2040 D.getDeclSpec().getConstSpecLoc(),
2041 D.getDeclSpec().getVolatileSpecLoc(),
2042 D.getDeclSpec().getRestrictSpecLoc(),
2043 *this);
Douglas Gregor5291c3c2010-07-13 08:18:22 +00002044 }
Chandler Carruthd067c072011-02-23 18:51:59 +00002045
Douglas Gregor402abb52009-05-28 23:31:59 +00002046 if (getLangOptions().CPlusPlus && D.getDeclSpec().isTypeSpecOwned()) {
2047 // C++ [dcl.fct]p6:
2048 // Types shall not be defined in return or parameter types.
John McCallb3d87482010-08-24 05:47:05 +00002049 TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
Douglas Gregor402abb52009-05-28 23:31:59 +00002050 if (Tag->isDefinition())
2051 Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
2052 << Context.getTypeDeclType(Tag);
2053 }
2054
Sebastian Redl3cc97262009-05-31 11:47:27 +00002055 // Exception specs are not allowed in typedefs. Complain, but add it
2056 // anyway.
Richard Smith162e1c12011-04-15 14:24:37 +00002057 if (IsTypedefName && FTI.getExceptionSpecType())
2058 Diag(FTI.getExceptionSpecLoc(), diag::err_exception_spec_in_typedef)
Richard Smith3e4c6c42011-05-05 21:57:07 +00002059 << (D.getContext() == Declarator::AliasDeclContext ||
2060 D.getContext() == Declarator::AliasTemplateContext);
Sebastian Redl3cc97262009-05-31 11:47:27 +00002061
John McCall28654742010-06-05 06:41:15 +00002062 if (!FTI.NumArgs && !FTI.isVariadic && !getLangOptions().CPlusPlus) {
2063 // Simple void foo(), where the incoming T is the result type.
2064 T = Context.getFunctionNoProtoType(T);
2065 } else {
2066 // We allow a zero-parameter variadic function in C if the
2067 // function is marked with the "overloadable" attribute. Scan
2068 // for this attribute now.
2069 if (!FTI.NumArgs && FTI.isVariadic && !getLangOptions().CPlusPlus) {
Douglas Gregor965acbb2009-02-18 07:07:28 +00002070 bool Overloadable = false;
2071 for (const AttributeList *Attrs = D.getAttributes();
2072 Attrs; Attrs = Attrs->getNext()) {
2073 if (Attrs->getKind() == AttributeList::AT_overloadable) {
2074 Overloadable = true;
2075 break;
2076 }
2077 }
2078
2079 if (!Overloadable)
2080 Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_arg);
Argyrios Kyrtzidisc6f73452008-10-16 17:31:08 +00002081 }
John McCall28654742010-06-05 06:41:15 +00002082
2083 if (FTI.NumArgs && FTI.ArgInfo[0].Param == 0) {
Chris Lattner788b0fd2010-06-23 06:00:24 +00002084 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function
2085 // definition.
John McCall28654742010-06-05 06:41:15 +00002086 Diag(FTI.ArgInfo[0].IdentLoc, diag::err_ident_list_in_fn_declaration);
2087 D.setInvalidType(true);
2088 break;
2089 }
2090
John McCalle23cf432010-12-14 08:05:40 +00002091 FunctionProtoType::ExtProtoInfo EPI;
2092 EPI.Variadic = FTI.isVariadic;
2093 EPI.TypeQuals = FTI.TypeQuals;
Douglas Gregorc938c162011-01-26 05:01:58 +00002094 EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None
2095 : FTI.RefQualifierIsLValueRef? RQ_LValue
2096 : RQ_RValue;
2097
Reid Spencer5f016e22007-07-11 17:01:13 +00002098 // Otherwise, we have a function with an argument list that is
2099 // potentially variadic.
2100 llvm::SmallVector<QualType, 16> ArgTys;
John McCall28654742010-06-05 06:41:15 +00002101 ArgTys.reserve(FTI.NumArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002102
John McCallf85e1932011-06-15 23:02:42 +00002103 llvm::SmallVector<bool, 16> ConsumedArguments;
2104 ConsumedArguments.reserve(FTI.NumArgs);
2105 bool HasAnyConsumedArguments = false;
2106
Reid Spencer5f016e22007-07-11 17:01:13 +00002107 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
John McCalld226f652010-08-21 09:40:31 +00002108 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
Chris Lattner8123a952008-04-10 02:22:51 +00002109 QualType ArgTy = Param->getType();
Chris Lattner78c75fb2007-07-21 05:30:18 +00002110 assert(!ArgTy.isNull() && "Couldn't parse type?");
Douglas Gregor2dc0e642009-03-23 23:06:20 +00002111
2112 // Adjust the parameter type.
Douglas Gregorbeb58cb2009-03-23 23:17:00 +00002113 assert((ArgTy == adjustParameterType(ArgTy)) && "Unadjusted type?");
Douglas Gregor2dc0e642009-03-23 23:06:20 +00002114
Reid Spencer5f016e22007-07-11 17:01:13 +00002115 // Look for 'void'. void is allowed only as a single argument to a
2116 // function with no other parameters (C99 6.7.5.3p10). We record
Douglas Gregor72564e72009-02-26 23:50:07 +00002117 // int(void) as a FunctionProtoType with an empty argument list.
Douglas Gregor2dc0e642009-03-23 23:06:20 +00002118 if (ArgTy->isVoidType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002119 // If this is something like 'float(int, void)', reject it. 'void'
2120 // is an incomplete type (C99 6.2.5p19) and function decls cannot
2121 // have arguments of incomplete type.
2122 if (FTI.NumArgs != 1 || FTI.isVariadic) {
2123 Diag(DeclType.Loc, diag::err_void_only_param);
Chris Lattner2ff54262007-07-21 05:18:12 +00002124 ArgTy = Context.IntTy;
Chris Lattner8123a952008-04-10 02:22:51 +00002125 Param->setType(ArgTy);
Chris Lattner2ff54262007-07-21 05:18:12 +00002126 } else if (FTI.ArgInfo[i].Ident) {
2127 // Reject, but continue to parse 'int(void abc)'.
Reid Spencer5f016e22007-07-11 17:01:13 +00002128 Diag(FTI.ArgInfo[i].IdentLoc,
Chris Lattner4565d4e2007-07-21 05:26:43 +00002129 diag::err_param_with_void_type);
Chris Lattner2ff54262007-07-21 05:18:12 +00002130 ArgTy = Context.IntTy;
Chris Lattner8123a952008-04-10 02:22:51 +00002131 Param->setType(ArgTy);
Chris Lattner2ff54262007-07-21 05:18:12 +00002132 } else {
2133 // Reject, but continue to parse 'float(const void)'.
John McCall0953e762009-09-24 19:53:00 +00002134 if (ArgTy.hasQualifiers())
Chris Lattner2ff54262007-07-21 05:18:12 +00002135 Diag(DeclType.Loc, diag::err_void_param_qualified);
Mike Stump1eb44332009-09-09 15:08:12 +00002136
Chris Lattner2ff54262007-07-21 05:18:12 +00002137 // Do not add 'void' to the ArgTys list.
2138 break;
2139 }
Eli Friedmaneb4b7052008-08-25 21:31:01 +00002140 } else if (!FTI.hasPrototype) {
2141 if (ArgTy->isPromotableIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00002142 ArgTy = Context.getPromotedIntegerType(ArgTy);
John McCalleecf5fa2011-03-09 04:22:44 +00002143 Param->setKNRPromoted(true);
John McCall183700f2009-09-21 23:43:11 +00002144 } else if (const BuiltinType* BTy = ArgTy->getAs<BuiltinType>()) {
John McCalleecf5fa2011-03-09 04:22:44 +00002145 if (BTy->getKind() == BuiltinType::Float) {
Eli Friedmaneb4b7052008-08-25 21:31:01 +00002146 ArgTy = Context.DoubleTy;
John McCalleecf5fa2011-03-09 04:22:44 +00002147 Param->setKNRPromoted(true);
2148 }
Eli Friedmaneb4b7052008-08-25 21:31:01 +00002149 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002150 }
Fariborz Jahanian56a965c2010-09-08 21:36:35 +00002151
John McCallf85e1932011-06-15 23:02:42 +00002152 if (getLangOptions().ObjCAutoRefCount) {
2153 bool Consumed = Param->hasAttr<NSConsumedAttr>();
2154 ConsumedArguments.push_back(Consumed);
2155 HasAnyConsumedArguments |= Consumed;
2156 }
2157
John McCall54e14c42009-10-22 22:37:11 +00002158 ArgTys.push_back(ArgTy);
Reid Spencer5f016e22007-07-11 17:01:13 +00002159 }
Sebastian Redl465226e2009-05-27 22:11:52 +00002160
John McCallf85e1932011-06-15 23:02:42 +00002161 if (HasAnyConsumedArguments)
2162 EPI.ConsumedArguments = ConsumedArguments.data();
2163
Sebastian Redl465226e2009-05-27 22:11:52 +00002164 llvm::SmallVector<QualType, 4> Exceptions;
Sebastian Redl8b5b4092011-03-06 10:52:04 +00002165 EPI.ExceptionSpecType = FTI.getExceptionSpecType();
2166 if (FTI.getExceptionSpecType() == EST_Dynamic) {
John McCalle23cf432010-12-14 08:05:40 +00002167 Exceptions.reserve(FTI.NumExceptions);
2168 for (unsigned ei = 0, ee = FTI.NumExceptions; ei != ee; ++ei) {
2169 // FIXME: Preserve type source info.
2170 QualType ET = GetTypeFromParser(FTI.Exceptions[ei].Ty);
2171 // Check that the type is valid for an exception spec, and
2172 // drop it if not.
2173 if (!CheckSpecifiedExceptionType(ET, FTI.Exceptions[ei].Range))
2174 Exceptions.push_back(ET);
2175 }
John McCall373920b2010-12-14 16:45:57 +00002176 EPI.NumExceptions = Exceptions.size();
John McCalle23cf432010-12-14 08:05:40 +00002177 EPI.Exceptions = Exceptions.data();
Sebastian Redl8b5b4092011-03-06 10:52:04 +00002178 } else if (FTI.getExceptionSpecType() == EST_ComputedNoexcept) {
Sebastian Redl60618fa2011-03-12 11:50:43 +00002179 // If an error occurred, there's no expression here.
2180 if (Expr *NoexceptExpr = FTI.NoexceptExpr) {
2181 assert((NoexceptExpr->isTypeDependent() ||
2182 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
2183 Context.BoolTy) &&
2184 "Parser should have made sure that the expression is boolean");
2185 SourceLocation ErrLoc;
2186 llvm::APSInt Dummy;
2187 if (!NoexceptExpr->isValueDependent() &&
2188 !NoexceptExpr->isIntegerConstantExpr(Dummy, Context, &ErrLoc,
2189 /*evaluated*/false))
2190 Diag(ErrLoc, diag::err_noexcept_needs_constant_expression)
2191 << NoexceptExpr->getSourceRange();
2192 else
2193 EPI.NoexceptExpr = NoexceptExpr;
2194 }
Sebastian Redl8999fe12011-03-14 18:08:30 +00002195 } else if (FTI.getExceptionSpecType() == EST_None &&
2196 ImplicitlyNoexcept && chunkIndex == 0) {
2197 // Only the outermost chunk is marked noexcept, of course.
2198 EPI.ExceptionSpecType = EST_BasicNoexcept;
Sebastian Redlef65f062009-05-29 18:02:33 +00002199 }
Sebastian Redl465226e2009-05-27 22:11:52 +00002200
John McCalle23cf432010-12-14 08:05:40 +00002201 T = Context.getFunctionType(T, ArgTys.data(), ArgTys.size(), EPI);
Reid Spencer5f016e22007-07-11 17:01:13 +00002202 }
John McCall04a67a62010-02-05 21:31:56 +00002203
Reid Spencer5f016e22007-07-11 17:01:13 +00002204 break;
2205 }
Sebastian Redlf30208a2009-01-24 21:16:55 +00002206 case DeclaratorChunk::MemberPointer:
2207 // The scope spec must refer to a class, or be dependent.
Abramo Bagnara7bd06762010-08-13 12:56:25 +00002208 CXXScopeSpec &SS = DeclType.Mem.Scope();
Sebastian Redlf30208a2009-01-24 21:16:55 +00002209 QualType ClsType;
Abramo Bagnara7bd06762010-08-13 12:56:25 +00002210 if (SS.isInvalid()) {
Jeffrey Yasskinedc28772010-04-07 23:29:58 +00002211 // Avoid emitting extra errors if we already errored on the scope.
2212 D.setInvalidType(true);
Abramo Bagnara7bd06762010-08-13 12:56:25 +00002213 } else if (isDependentScopeSpecifier(SS) ||
2214 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS))) {
Mike Stump1eb44332009-09-09 15:08:12 +00002215 NestedNameSpecifier *NNS
Abramo Bagnara7bd06762010-08-13 12:56:25 +00002216 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
Douglas Gregor87c12c42009-11-04 16:49:01 +00002217 NestedNameSpecifier *NNSPrefix = NNS->getPrefix();
2218 switch (NNS->getKind()) {
2219 case NestedNameSpecifier::Identifier:
Abramo Bagnara7bd06762010-08-13 12:56:25 +00002220 ClsType = Context.getDependentNameType(ETK_None, NNSPrefix,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002221 NNS->getAsIdentifier());
Douglas Gregor87c12c42009-11-04 16:49:01 +00002222 break;
2223
2224 case NestedNameSpecifier::Namespace:
Douglas Gregor14aba762011-02-24 02:36:08 +00002225 case NestedNameSpecifier::NamespaceAlias:
Douglas Gregor87c12c42009-11-04 16:49:01 +00002226 case NestedNameSpecifier::Global:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002227 llvm_unreachable("Nested-name-specifier must name a type");
Douglas Gregor87c12c42009-11-04 16:49:01 +00002228 break;
Abramo Bagnara7bd06762010-08-13 12:56:25 +00002229
Douglas Gregor87c12c42009-11-04 16:49:01 +00002230 case NestedNameSpecifier::TypeSpec:
2231 case NestedNameSpecifier::TypeSpecWithTemplate:
2232 ClsType = QualType(NNS->getAsType(), 0);
Abramo Bagnara91ce2c42011-03-10 10:18:27 +00002233 // Note: if the NNS has a prefix and ClsType is a nondependent
2234 // TemplateSpecializationType, then the NNS prefix is NOT included
2235 // in ClsType; hence we wrap ClsType into an ElaboratedType.
2236 // NOTE: in particular, no wrap occurs if ClsType already is an
2237 // Elaborated, DependentName, or DependentTemplateSpecialization.
2238 if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType()))
Abramo Bagnara7bd06762010-08-13 12:56:25 +00002239 ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType);
Douglas Gregor87c12c42009-11-04 16:49:01 +00002240 break;
2241 }
Sebastian Redlf30208a2009-01-24 21:16:55 +00002242 } else {
Douglas Gregor949bf692009-06-09 22:17:39 +00002243 Diag(DeclType.Mem.Scope().getBeginLoc(),
2244 diag::err_illegal_decl_mempointer_in_nonclass)
2245 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
2246 << DeclType.Mem.Scope().getRange();
Sebastian Redlf30208a2009-01-24 21:16:55 +00002247 D.setInvalidType(true);
Sebastian Redlf30208a2009-01-24 21:16:55 +00002248 }
2249
Douglas Gregor949bf692009-06-09 22:17:39 +00002250 if (!ClsType.isNull())
John McCall28654742010-06-05 06:41:15 +00002251 T = BuildMemberPointerType(T, ClsType, DeclType.Loc, D.getIdentifier());
Douglas Gregor949bf692009-06-09 22:17:39 +00002252 if (T.isNull()) {
2253 T = Context.IntTy;
Sebastian Redlf30208a2009-01-24 21:16:55 +00002254 D.setInvalidType(true);
John McCall28654742010-06-05 06:41:15 +00002255 } else if (DeclType.Mem.TypeQuals) {
2256 T = BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals);
Sebastian Redlf30208a2009-01-24 21:16:55 +00002257 }
Sebastian Redlf30208a2009-01-24 21:16:55 +00002258 break;
2259 }
2260
Douglas Gregorcd281c32009-02-28 00:25:32 +00002261 if (T.isNull()) {
2262 D.setInvalidType(true);
2263 T = Context.IntTy;
2264 }
2265
Chris Lattnerc9b346d2008-06-29 00:50:08 +00002266 // See if there are any attributes on this declarator chunk.
John McCall711c52b2011-01-05 12:14:39 +00002267 if (AttributeList *attrs = const_cast<AttributeList*>(DeclType.getAttrs()))
2268 processTypeAttrs(state, T, false, attrs);
Reid Spencer5f016e22007-07-11 17:01:13 +00002269 }
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00002270
2271 if (getLangOptions().CPlusPlus && T->isFunctionType()) {
John McCall183700f2009-09-21 23:43:11 +00002272 const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
Chris Lattner778ed742009-10-25 17:36:50 +00002273 assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00002274
Douglas Gregor708f3b82010-10-14 22:03:51 +00002275 // C++ 8.3.5p4:
2276 // A cv-qualifier-seq shall only be part of the function type
2277 // for a nonstatic member function, the function type to which a pointer
2278 // to member refers, or the top-level function type of a function typedef
2279 // declaration.
Douglas Gregor683a81f2011-01-31 16:09:46 +00002280 //
2281 // Core issue 547 also allows cv-qualifiers on function types that are
2282 // top-level template type arguments.
John McCall613ef3d2010-10-19 01:54:45 +00002283 bool FreeFunction;
2284 if (!D.getCXXScopeSpec().isSet()) {
2285 FreeFunction = (D.getContext() != Declarator::MemberContext ||
2286 D.getDeclSpec().isFriendSpecified());
2287 } else {
2288 DeclContext *DC = computeDeclContext(D.getCXXScopeSpec());
2289 FreeFunction = (DC && !DC->isRecord());
2290 }
2291
Douglas Gregorc938c162011-01-26 05:01:58 +00002292 // C++0x [dcl.fct]p6:
2293 // A ref-qualifier shall only be part of the function type for a
2294 // non-static member function, the function type to which a pointer to
2295 // member refers, or the top-level function type of a function typedef
2296 // declaration.
2297 if ((FnTy->getTypeQuals() != 0 || FnTy->getRefQualifier()) &&
Douglas Gregor683a81f2011-01-31 16:09:46 +00002298 !(D.getContext() == Declarator::TemplateTypeArgContext &&
Richard Smith162e1c12011-04-15 14:24:37 +00002299 !D.isFunctionDeclarator()) && !IsTypedefName &&
Sebastian Redlc61bb202010-07-09 21:26:08 +00002300 (FreeFunction ||
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00002301 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)) {
Douglas Gregor683a81f2011-01-31 16:09:46 +00002302 if (D.getContext() == Declarator::TemplateTypeArgContext) {
2303 // Accept qualified function types as template type arguments as a GNU
2304 // extension. This is also the subject of C++ core issue 547.
2305 std::string Quals;
2306 if (FnTy->getTypeQuals() != 0)
2307 Quals = Qualifiers::fromCVRMask(FnTy->getTypeQuals()).getAsString();
2308
2309 switch (FnTy->getRefQualifier()) {
2310 case RQ_None:
2311 break;
2312
2313 case RQ_LValue:
2314 if (!Quals.empty())
2315 Quals += ' ';
2316 Quals += '&';
2317 break;
Douglas Gregorc938c162011-01-26 05:01:58 +00002318
Douglas Gregor683a81f2011-01-31 16:09:46 +00002319 case RQ_RValue:
2320 if (!Quals.empty())
2321 Quals += ' ';
2322 Quals += "&&";
2323 break;
Douglas Gregorc938c162011-01-26 05:01:58 +00002324 }
Douglas Gregor683a81f2011-01-31 16:09:46 +00002325
2326 Diag(D.getIdentifierLoc(),
2327 diag::ext_qualified_function_type_template_arg)
2328 << Quals;
2329 } else {
2330 if (FnTy->getTypeQuals() != 0) {
2331 if (D.isFunctionDeclarator())
2332 Diag(D.getIdentifierLoc(),
2333 diag::err_invalid_qualified_function_type);
2334 else
2335 Diag(D.getIdentifierLoc(),
2336 diag::err_invalid_qualified_typedef_function_type_use)
2337 << FreeFunction;
2338 }
2339
2340 if (FnTy->getRefQualifier()) {
2341 if (D.isFunctionDeclarator()) {
2342 SourceLocation Loc = D.getIdentifierLoc();
2343 for (unsigned I = 0, N = D.getNumTypeObjects(); I != N; ++I) {
2344 const DeclaratorChunk &Chunk = D.getTypeObject(N-I-1);
2345 if (Chunk.Kind == DeclaratorChunk::Function &&
2346 Chunk.Fun.hasRefQualifier()) {
2347 Loc = Chunk.Fun.getRefQualifierLoc();
2348 break;
2349 }
2350 }
2351
2352 Diag(Loc, diag::err_invalid_ref_qualifier_function_type)
2353 << (FnTy->getRefQualifier() == RQ_LValue)
2354 << FixItHint::CreateRemoval(Loc);
2355 } else {
2356 Diag(D.getIdentifierLoc(),
2357 diag::err_invalid_ref_qualifier_typedef_function_type_use)
2358 << FreeFunction
2359 << (FnTy->getRefQualifier() == RQ_LValue);
2360 }
2361 }
2362
2363 // Strip the cv-qualifiers and ref-qualifiers from the type.
2364 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
2365 EPI.TypeQuals = 0;
2366 EPI.RefQualifier = RQ_None;
2367
2368 T = Context.getFunctionType(FnTy->getResultType(),
2369 FnTy->arg_type_begin(),
2370 FnTy->getNumArgs(), EPI);
Douglas Gregorc938c162011-01-26 05:01:58 +00002371 }
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00002372 }
2373 }
Mike Stump1eb44332009-09-09 15:08:12 +00002374
John McCall711c52b2011-01-05 12:14:39 +00002375 // Apply any undistributed attributes from the declarator.
2376 if (!T.isNull())
2377 if (AttributeList *attrs = D.getAttributes())
2378 processTypeAttrs(state, T, false, attrs);
2379
2380 // Diagnose any ignored type attributes.
2381 if (!T.isNull()) state.diagnoseIgnoredTypeAttrs(T);
2382
Peter Collingbourne148f1f72011-03-20 08:06:45 +00002383 // C++0x [dcl.constexpr]p9:
2384 // A constexpr specifier used in an object declaration declares the object
2385 // as const.
2386 if (D.getDeclSpec().isConstexprSpecified() && T->isObjectType()) {
Sebastian Redl73780122010-06-09 21:19:43 +00002387 T.addConst();
2388 }
2389
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002390 // If there was an ellipsis in the declarator, the declaration declares a
2391 // parameter pack whose type may be a pack expansion type.
2392 if (D.hasEllipsis() && !T.isNull()) {
2393 // C++0x [dcl.fct]p13:
2394 // A declarator-id or abstract-declarator containing an ellipsis shall
2395 // only be used in a parameter-declaration. Such a parameter-declaration
2396 // is a parameter pack (14.5.3). [...]
2397 switch (D.getContext()) {
2398 case Declarator::PrototypeContext:
2399 // C++0x [dcl.fct]p13:
2400 // [...] When it is part of a parameter-declaration-clause, the
2401 // parameter pack is a function parameter pack (14.5.3). The type T
2402 // of the declarator-id of the function parameter pack shall contain
2403 // a template parameter pack; each template parameter pack in T is
2404 // expanded by the function parameter pack.
2405 //
2406 // We represent function parameter packs as function parameters whose
2407 // type is a pack expansion.
2408 if (!T->containsUnexpandedParameterPack()) {
2409 Diag(D.getEllipsisLoc(),
2410 diag::err_function_parameter_pack_without_parameter_packs)
2411 << T << D.getSourceRange();
2412 D.setEllipsisLoc(SourceLocation());
2413 } else {
Douglas Gregorcded4f62011-01-14 17:04:44 +00002414 T = Context.getPackExpansionType(T, llvm::Optional<unsigned>());
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002415 }
2416 break;
2417
2418 case Declarator::TemplateParamContext:
2419 // C++0x [temp.param]p15:
2420 // If a template-parameter is a [...] is a parameter-declaration that
2421 // declares a parameter pack (8.3.5), then the template-parameter is a
2422 // template parameter pack (14.5.3).
2423 //
2424 // Note: core issue 778 clarifies that, if there are any unexpanded
2425 // parameter packs in the type of the non-type template parameter, then
2426 // it expands those parameter packs.
2427 if (T->containsUnexpandedParameterPack())
Douglas Gregorcded4f62011-01-14 17:04:44 +00002428 T = Context.getPackExpansionType(T, llvm::Optional<unsigned>());
Douglas Gregor10738d32010-12-23 23:51:58 +00002429 else if (!getLangOptions().CPlusPlus0x)
Douglas Gregor5ce5f522011-01-19 21:59:15 +00002430 Diag(D.getEllipsisLoc(), diag::ext_variadic_templates);
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002431 break;
2432
2433 case Declarator::FileContext:
2434 case Declarator::KNRTypeListContext:
John McCallc05a94b2011-03-23 23:43:04 +00002435 case Declarator::ObjCPrototypeContext: // FIXME: special diagnostic here?
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002436 case Declarator::TypeNameContext:
Argyrios Kyrtzidis0b8c98f2011-06-28 03:01:23 +00002437 case Declarator::CXXNewContext:
Richard Smith162e1c12011-04-15 14:24:37 +00002438 case Declarator::AliasDeclContext:
Richard Smith3e4c6c42011-05-05 21:57:07 +00002439 case Declarator::AliasTemplateContext:
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002440 case Declarator::MemberContext:
2441 case Declarator::BlockContext:
2442 case Declarator::ForContext:
2443 case Declarator::ConditionContext:
2444 case Declarator::CXXCatchContext:
Argyrios Kyrtzidis17b63992011-07-01 22:22:40 +00002445 case Declarator::ObjCCatchContext:
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002446 case Declarator::BlockLiteralContext:
Douglas Gregor683a81f2011-01-31 16:09:46 +00002447 case Declarator::TemplateTypeArgContext:
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002448 // FIXME: We may want to allow parameter packs in block-literal contexts
2449 // in the future.
2450 Diag(D.getEllipsisLoc(), diag::err_ellipsis_in_declarator_not_parameter);
2451 D.setEllipsisLoc(SourceLocation());
2452 break;
2453 }
2454 }
Richard Smithe7397c62011-02-22 00:36:53 +00002455
John McCallbf1a0282010-06-04 23:28:52 +00002456 if (T.isNull())
2457 return Context.getNullTypeSourceInfo();
2458 else if (D.isInvalidType())
2459 return Context.getTrivialTypeSourceInfo(T);
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +00002460
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +00002461 if (getLangOptions().CPlusPlus &&
Argyrios Kyrtzidisd3880f82011-06-28 03:01:18 +00002462 OwnedTagDecl && OwnedTagDecl->isDefinition()) {
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +00002463 // Check the contexts where C++ forbids the declaration of a new class
2464 // or enumeration in a type-specifier-seq.
2465 switch (D.getContext()) {
2466 case Declarator::FileContext:
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +00002467 case Declarator::MemberContext:
2468 case Declarator::BlockContext:
2469 case Declarator::ForContext:
Argyrios Kyrtzidisd3880f82011-06-28 03:01:18 +00002470 case Declarator::BlockLiteralContext:
2471 // C++0x [dcl.type]p3:
2472 // A type-specifier-seq shall not define a class or enumeration unless
2473 // it appears in the type-id of an alias-declaration (7.1.3) that is not
2474 // the declaration of a template-declaration.
2475 case Declarator::AliasDeclContext:
2476 break;
2477 case Declarator::AliasTemplateContext:
2478 Diag(OwnedTagDecl->getLocation(),diag::err_type_defined_in_alias_template)
2479 << Context.getTypeDeclType(OwnedTagDecl);
2480 break;
2481 case Declarator::TypeNameContext:
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +00002482 case Declarator::TemplateParamContext:
Argyrios Kyrtzidis0b8c98f2011-06-28 03:01:23 +00002483 case Declarator::CXXNewContext:
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +00002484 case Declarator::CXXCatchContext:
Argyrios Kyrtzidis17b63992011-07-01 22:22:40 +00002485 case Declarator::ObjCCatchContext:
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +00002486 case Declarator::TemplateTypeArgContext:
Argyrios Kyrtzidisd3880f82011-06-28 03:01:18 +00002487 Diag(OwnedTagDecl->getLocation(),diag::err_type_defined_in_type_specifier)
2488 << Context.getTypeDeclType(OwnedTagDecl);
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +00002489 break;
Argyrios Kyrtzidis32153982011-06-28 03:01:15 +00002490 case Declarator::PrototypeContext:
Argyrios Kyrtzidisd3880f82011-06-28 03:01:18 +00002491 case Declarator::ObjCPrototypeContext:
2492 case Declarator::KNRTypeListContext:
Argyrios Kyrtzidis32153982011-06-28 03:01:15 +00002493 // C++ [dcl.fct]p6:
2494 // Types shall not be defined in return or parameter types.
Argyrios Kyrtzidisd3880f82011-06-28 03:01:18 +00002495 Diag(OwnedTagDecl->getLocation(), diag::err_type_defined_in_param_type)
2496 << Context.getTypeDeclType(OwnedTagDecl);
Argyrios Kyrtzidis32153982011-06-28 03:01:15 +00002497 break;
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +00002498 case Declarator::ConditionContext:
2499 // C++ 6.4p2:
2500 // The type-specifier-seq shall not contain typedef and shall not declare
2501 // a new class or enumeration.
Argyrios Kyrtzidisd3880f82011-06-28 03:01:18 +00002502 Diag(OwnedTagDecl->getLocation(), diag::err_type_defined_in_condition);
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +00002503 break;
2504 }
2505 }
2506
John McCallbf1a0282010-06-04 23:28:52 +00002507 return GetTypeSourceInfoForDeclarator(D, T, ReturnTypeInfo);
Reid Spencer5f016e22007-07-11 17:01:13 +00002508}
2509
John McCall14aa2172011-03-04 04:00:19 +00002510/// Map an AttributedType::Kind to an AttributeList::Kind.
2511static AttributeList::Kind getAttrListKind(AttributedType::Kind kind) {
2512 switch (kind) {
2513 case AttributedType::attr_address_space:
2514 return AttributeList::AT_address_space;
2515 case AttributedType::attr_regparm:
2516 return AttributeList::AT_regparm;
2517 case AttributedType::attr_vector_size:
2518 return AttributeList::AT_vector_size;
2519 case AttributedType::attr_neon_vector_type:
2520 return AttributeList::AT_neon_vector_type;
2521 case AttributedType::attr_neon_polyvector_type:
2522 return AttributeList::AT_neon_polyvector_type;
2523 case AttributedType::attr_objc_gc:
2524 return AttributeList::AT_objc_gc;
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00002525 case AttributedType::attr_objc_ownership:
2526 return AttributeList::AT_objc_ownership;
John McCall14aa2172011-03-04 04:00:19 +00002527 case AttributedType::attr_noreturn:
2528 return AttributeList::AT_noreturn;
2529 case AttributedType::attr_cdecl:
2530 return AttributeList::AT_cdecl;
2531 case AttributedType::attr_fastcall:
2532 return AttributeList::AT_fastcall;
2533 case AttributedType::attr_stdcall:
2534 return AttributeList::AT_stdcall;
2535 case AttributedType::attr_thiscall:
2536 return AttributeList::AT_thiscall;
2537 case AttributedType::attr_pascal:
2538 return AttributeList::AT_pascal;
Anton Korobeynikov414d8962011-04-14 20:06:49 +00002539 case AttributedType::attr_pcs:
2540 return AttributeList::AT_pcs;
John McCall14aa2172011-03-04 04:00:19 +00002541 }
2542 llvm_unreachable("unexpected attribute kind!");
2543 return AttributeList::Kind();
2544}
2545
2546static void fillAttributedTypeLoc(AttributedTypeLoc TL,
2547 const AttributeList *attrs) {
2548 AttributedType::Kind kind = TL.getAttrKind();
2549
2550 assert(attrs && "no type attributes in the expected location!");
2551 AttributeList::Kind parsedKind = getAttrListKind(kind);
2552 while (attrs->getKind() != parsedKind) {
2553 attrs = attrs->getNext();
2554 assert(attrs && "no matching attribute in expected location!");
2555 }
2556
2557 TL.setAttrNameLoc(attrs->getLoc());
2558 if (TL.hasAttrExprOperand())
2559 TL.setAttrExprOperand(attrs->getArg(0));
2560 else if (TL.hasAttrEnumOperand())
2561 TL.setAttrEnumOperandLoc(attrs->getParameterLoc());
2562
2563 // FIXME: preserve this information to here.
2564 if (TL.hasAttrOperand())
2565 TL.setAttrOperandParensRange(SourceRange());
2566}
2567
John McCall51bd8032009-10-18 01:05:36 +00002568namespace {
2569 class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
Douglas Gregorc21c7e92011-01-25 19:13:18 +00002570 ASTContext &Context;
John McCall51bd8032009-10-18 01:05:36 +00002571 const DeclSpec &DS;
Argyrios Kyrtzidisf352bdd2009-09-29 19:43:35 +00002572
John McCall51bd8032009-10-18 01:05:36 +00002573 public:
Douglas Gregorc21c7e92011-01-25 19:13:18 +00002574 TypeSpecLocFiller(ASTContext &Context, const DeclSpec &DS)
2575 : Context(Context), DS(DS) {}
Argyrios Kyrtzidisf352bdd2009-09-29 19:43:35 +00002576
John McCall14aa2172011-03-04 04:00:19 +00002577 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
2578 fillAttributedTypeLoc(TL, DS.getAttributes().getList());
2579 Visit(TL.getModifiedLoc());
2580 }
John McCall51bd8032009-10-18 01:05:36 +00002581 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
2582 Visit(TL.getUnqualifiedLoc());
2583 }
2584 void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
2585 TL.setNameLoc(DS.getTypeSpecTypeLoc());
2586 }
2587 void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
2588 TL.setNameLoc(DS.getTypeSpecTypeLoc());
John McCallc12c5bb2010-05-15 11:32:37 +00002589 }
2590 void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
2591 // Handle the base type, which might not have been written explicitly.
2592 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
2593 TL.setHasBaseTypeAsWritten(false);
Douglas Gregorc21c7e92011-01-25 19:13:18 +00002594 TL.getBaseLoc().initialize(Context, SourceLocation());
John McCallc12c5bb2010-05-15 11:32:37 +00002595 } else {
2596 TL.setHasBaseTypeAsWritten(true);
2597 Visit(TL.getBaseLoc());
2598 }
Argyrios Kyrtzidiseb667592009-09-29 19:45:22 +00002599
John McCallc12c5bb2010-05-15 11:32:37 +00002600 // Protocol qualifiers.
John McCall54e14c42009-10-22 22:37:11 +00002601 if (DS.getProtocolQualifiers()) {
2602 assert(TL.getNumProtocols() > 0);
2603 assert(TL.getNumProtocols() == DS.getNumProtocolQualifiers());
2604 TL.setLAngleLoc(DS.getProtocolLAngleLoc());
2605 TL.setRAngleLoc(DS.getSourceRange().getEnd());
2606 for (unsigned i = 0, e = DS.getNumProtocolQualifiers(); i != e; ++i)
2607 TL.setProtocolLoc(i, DS.getProtocolLocs()[i]);
2608 } else {
2609 assert(TL.getNumProtocols() == 0);
2610 TL.setLAngleLoc(SourceLocation());
2611 TL.setRAngleLoc(SourceLocation());
2612 }
2613 }
2614 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCall54e14c42009-10-22 22:37:11 +00002615 TL.setStarLoc(SourceLocation());
John McCallc12c5bb2010-05-15 11:32:37 +00002616 Visit(TL.getPointeeLoc());
John McCall51bd8032009-10-18 01:05:36 +00002617 }
John McCall833ca992009-10-29 08:12:44 +00002618 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
John McCalla93c9342009-12-07 02:54:59 +00002619 TypeSourceInfo *TInfo = 0;
John McCallb3d87482010-08-24 05:47:05 +00002620 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
John McCall833ca992009-10-29 08:12:44 +00002621
2622 // If we got no declarator info from previous Sema routines,
2623 // just fill with the typespec loc.
John McCalla93c9342009-12-07 02:54:59 +00002624 if (!TInfo) {
Abramo Bagnara0daaf322011-03-16 20:16:18 +00002625 TL.initialize(Context, DS.getTypeSpecTypeNameLoc());
John McCall833ca992009-10-29 08:12:44 +00002626 return;
2627 }
2628
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00002629 TypeLoc OldTL = TInfo->getTypeLoc();
2630 if (TInfo->getType()->getAs<ElaboratedType>()) {
2631 ElaboratedTypeLoc ElabTL = cast<ElaboratedTypeLoc>(OldTL);
2632 TemplateSpecializationTypeLoc NamedTL =
2633 cast<TemplateSpecializationTypeLoc>(ElabTL.getNamedTypeLoc());
2634 TL.copy(NamedTL);
2635 }
2636 else
2637 TL.copy(cast<TemplateSpecializationTypeLoc>(OldTL));
John McCall833ca992009-10-29 08:12:44 +00002638 }
John McCallcfb708c2010-01-13 20:03:27 +00002639 void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
2640 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr);
2641 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
2642 TL.setParensRange(DS.getTypeofParensRange());
2643 }
2644 void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
2645 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType);
2646 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
2647 TL.setParensRange(DS.getTypeofParensRange());
John McCallb3d87482010-08-24 05:47:05 +00002648 assert(DS.getRepAsType());
John McCallcfb708c2010-01-13 20:03:27 +00002649 TypeSourceInfo *TInfo = 0;
John McCallb3d87482010-08-24 05:47:05 +00002650 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
John McCallcfb708c2010-01-13 20:03:27 +00002651 TL.setUnderlyingTInfo(TInfo);
2652 }
Sean Huntca63c202011-05-24 22:41:36 +00002653 void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
2654 // FIXME: This holds only because we only have one unary transform.
2655 assert(DS.getTypeSpecType() == DeclSpec::TST_underlyingType);
2656 TL.setKWLoc(DS.getTypeSpecTypeLoc());
2657 TL.setParensRange(DS.getTypeofParensRange());
2658 assert(DS.getRepAsType());
2659 TypeSourceInfo *TInfo = 0;
2660 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
2661 TL.setUnderlyingTInfo(TInfo);
2662 }
Douglas Gregorddf889a2010-01-18 18:04:31 +00002663 void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
2664 // By default, use the source location of the type specifier.
2665 TL.setBuiltinLoc(DS.getTypeSpecTypeLoc());
2666 if (TL.needsExtraLocalData()) {
2667 // Set info for the written builtin specifiers.
2668 TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs();
2669 // Try to have a meaningful source location.
2670 if (TL.getWrittenSignSpec() != TSS_unspecified)
2671 // Sign spec loc overrides the others (e.g., 'unsigned long').
2672 TL.setBuiltinLoc(DS.getTypeSpecSignLoc());
2673 else if (TL.getWrittenWidthSpec() != TSW_unspecified)
2674 // Width spec loc overrides type spec loc (e.g., 'short int').
2675 TL.setBuiltinLoc(DS.getTypeSpecWidthLoc());
2676 }
2677 }
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00002678 void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
2679 ElaboratedTypeKeyword Keyword
2680 = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
Nico Weber253e80b2010-11-22 10:30:56 +00002681 if (DS.getTypeSpecType() == TST_typename) {
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00002682 TypeSourceInfo *TInfo = 0;
John McCallb3d87482010-08-24 05:47:05 +00002683 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00002684 if (TInfo) {
2685 TL.copy(cast<ElaboratedTypeLoc>(TInfo->getTypeLoc()));
2686 return;
2687 }
2688 }
2689 TL.setKeywordLoc(Keyword != ETK_None
2690 ? DS.getTypeSpecTypeLoc()
2691 : SourceLocation());
2692 const CXXScopeSpec& SS = DS.getTypeSpecScope();
Douglas Gregor9e876872011-03-01 18:12:44 +00002693 TL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00002694 Visit(TL.getNextTypeLoc().getUnqualifiedLoc());
2695 }
2696 void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
2697 ElaboratedTypeKeyword Keyword
2698 = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
Nico Weber253e80b2010-11-22 10:30:56 +00002699 if (DS.getTypeSpecType() == TST_typename) {
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00002700 TypeSourceInfo *TInfo = 0;
John McCallb3d87482010-08-24 05:47:05 +00002701 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00002702 if (TInfo) {
2703 TL.copy(cast<DependentNameTypeLoc>(TInfo->getTypeLoc()));
2704 return;
2705 }
2706 }
2707 TL.setKeywordLoc(Keyword != ETK_None
2708 ? DS.getTypeSpecTypeLoc()
2709 : SourceLocation());
2710 const CXXScopeSpec& SS = DS.getTypeSpecScope();
Douglas Gregor2494dd02011-03-01 01:34:45 +00002711 TL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnara0daaf322011-03-16 20:16:18 +00002712 TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00002713 }
John McCall33500952010-06-11 00:33:02 +00002714 void VisitDependentTemplateSpecializationTypeLoc(
2715 DependentTemplateSpecializationTypeLoc TL) {
2716 ElaboratedTypeKeyword Keyword
2717 = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
2718 if (Keyword == ETK_Typename) {
2719 TypeSourceInfo *TInfo = 0;
John McCallb3d87482010-08-24 05:47:05 +00002720 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
John McCall33500952010-06-11 00:33:02 +00002721 if (TInfo) {
2722 TL.copy(cast<DependentTemplateSpecializationTypeLoc>(
2723 TInfo->getTypeLoc()));
2724 return;
2725 }
2726 }
Douglas Gregorc21c7e92011-01-25 19:13:18 +00002727 TL.initializeLocal(Context, SourceLocation());
John McCall33500952010-06-11 00:33:02 +00002728 TL.setKeywordLoc(Keyword != ETK_None
2729 ? DS.getTypeSpecTypeLoc()
2730 : SourceLocation());
2731 const CXXScopeSpec& SS = DS.getTypeSpecScope();
Douglas Gregor94fdffa2011-03-01 20:11:18 +00002732 TL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnara0daaf322011-03-16 20:16:18 +00002733 TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
2734 }
2735 void VisitTagTypeLoc(TagTypeLoc TL) {
2736 TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
John McCall33500952010-06-11 00:33:02 +00002737 }
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00002738
John McCall51bd8032009-10-18 01:05:36 +00002739 void VisitTypeLoc(TypeLoc TL) {
2740 // FIXME: add other typespec types and change this to an assert.
Douglas Gregorc21c7e92011-01-25 19:13:18 +00002741 TL.initialize(Context, DS.getTypeSpecTypeLoc());
John McCall51bd8032009-10-18 01:05:36 +00002742 }
2743 };
Argyrios Kyrtzidisf352bdd2009-09-29 19:43:35 +00002744
John McCall51bd8032009-10-18 01:05:36 +00002745 class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
Abramo Bagnarab6ab6c12011-03-05 14:42:21 +00002746 ASTContext &Context;
John McCall51bd8032009-10-18 01:05:36 +00002747 const DeclaratorChunk &Chunk;
2748
2749 public:
Abramo Bagnarab6ab6c12011-03-05 14:42:21 +00002750 DeclaratorLocFiller(ASTContext &Context, const DeclaratorChunk &Chunk)
2751 : Context(Context), Chunk(Chunk) {}
John McCall51bd8032009-10-18 01:05:36 +00002752
2753 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002754 llvm_unreachable("qualified type locs not expected here!");
John McCall51bd8032009-10-18 01:05:36 +00002755 }
2756
John McCallf85e1932011-06-15 23:02:42 +00002757 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
2758 fillAttributedTypeLoc(TL, Chunk.getAttrs());
2759 }
John McCall51bd8032009-10-18 01:05:36 +00002760 void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
2761 assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
2762 TL.setCaretLoc(Chunk.Loc);
2763 }
2764 void VisitPointerTypeLoc(PointerTypeLoc TL) {
2765 assert(Chunk.Kind == DeclaratorChunk::Pointer);
2766 TL.setStarLoc(Chunk.Loc);
2767 }
2768 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
2769 assert(Chunk.Kind == DeclaratorChunk::Pointer);
2770 TL.setStarLoc(Chunk.Loc);
2771 }
2772 void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
2773 assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
Abramo Bagnarab6ab6c12011-03-05 14:42:21 +00002774 const CXXScopeSpec& SS = Chunk.Mem.Scope();
2775 NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context);
2776
2777 const Type* ClsTy = TL.getClass();
2778 QualType ClsQT = QualType(ClsTy, 0);
2779 TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0);
2780 // Now copy source location info into the type loc component.
2781 TypeLoc ClsTL = ClsTInfo->getTypeLoc();
2782 switch (NNSLoc.getNestedNameSpecifier()->getKind()) {
2783 case NestedNameSpecifier::Identifier:
2784 assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc");
2785 {
Abramo Bagnarafd9c42e2011-03-06 22:48:24 +00002786 DependentNameTypeLoc DNTLoc = cast<DependentNameTypeLoc>(ClsTL);
Abramo Bagnarab6ab6c12011-03-05 14:42:21 +00002787 DNTLoc.setKeywordLoc(SourceLocation());
2788 DNTLoc.setQualifierLoc(NNSLoc.getPrefix());
2789 DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc());
2790 }
2791 break;
2792
2793 case NestedNameSpecifier::TypeSpec:
2794 case NestedNameSpecifier::TypeSpecWithTemplate:
2795 if (isa<ElaboratedType>(ClsTy)) {
2796 ElaboratedTypeLoc ETLoc = *cast<ElaboratedTypeLoc>(&ClsTL);
2797 ETLoc.setKeywordLoc(SourceLocation());
2798 ETLoc.setQualifierLoc(NNSLoc.getPrefix());
2799 TypeLoc NamedTL = ETLoc.getNamedTypeLoc();
2800 NamedTL.initializeFullCopy(NNSLoc.getTypeLoc());
2801 } else {
2802 ClsTL.initializeFullCopy(NNSLoc.getTypeLoc());
2803 }
2804 break;
2805
2806 case NestedNameSpecifier::Namespace:
2807 case NestedNameSpecifier::NamespaceAlias:
2808 case NestedNameSpecifier::Global:
2809 llvm_unreachable("Nested-name-specifier must name a type");
2810 break;
2811 }
2812
2813 // Finally fill in MemberPointerLocInfo fields.
John McCall51bd8032009-10-18 01:05:36 +00002814 TL.setStarLoc(Chunk.Loc);
Abramo Bagnarab6ab6c12011-03-05 14:42:21 +00002815 TL.setClassTInfo(ClsTInfo);
John McCall51bd8032009-10-18 01:05:36 +00002816 }
2817 void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
2818 assert(Chunk.Kind == DeclaratorChunk::Reference);
John McCall54e14c42009-10-22 22:37:11 +00002819 // 'Amp' is misleading: this might have been originally
2820 /// spelled with AmpAmp.
John McCall51bd8032009-10-18 01:05:36 +00002821 TL.setAmpLoc(Chunk.Loc);
2822 }
2823 void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
2824 assert(Chunk.Kind == DeclaratorChunk::Reference);
2825 assert(!Chunk.Ref.LValueRef);
2826 TL.setAmpAmpLoc(Chunk.Loc);
2827 }
2828 void VisitArrayTypeLoc(ArrayTypeLoc TL) {
2829 assert(Chunk.Kind == DeclaratorChunk::Array);
2830 TL.setLBracketLoc(Chunk.Loc);
2831 TL.setRBracketLoc(Chunk.EndLoc);
2832 TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
2833 }
2834 void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
2835 assert(Chunk.Kind == DeclaratorChunk::Function);
Abramo Bagnara796aa442011-03-12 11:17:06 +00002836 TL.setLocalRangeBegin(Chunk.Loc);
2837 TL.setLocalRangeEnd(Chunk.EndLoc);
Douglas Gregordab60ad2010-10-01 18:44:50 +00002838 TL.setTrailingReturn(!!Chunk.Fun.TrailingReturnType);
John McCall51bd8032009-10-18 01:05:36 +00002839
2840 const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
John McCall54e14c42009-10-22 22:37:11 +00002841 for (unsigned i = 0, e = TL.getNumArgs(), tpi = 0; i != e; ++i) {
John McCalld226f652010-08-21 09:40:31 +00002842 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
John McCall54e14c42009-10-22 22:37:11 +00002843 TL.setArg(tpi++, Param);
John McCall51bd8032009-10-18 01:05:36 +00002844 }
2845 // FIXME: exception specs
2846 }
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002847 void VisitParenTypeLoc(ParenTypeLoc TL) {
2848 assert(Chunk.Kind == DeclaratorChunk::Paren);
2849 TL.setLParenLoc(Chunk.Loc);
2850 TL.setRParenLoc(Chunk.EndLoc);
2851 }
John McCall51bd8032009-10-18 01:05:36 +00002852
2853 void VisitTypeLoc(TypeLoc TL) {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002854 llvm_unreachable("unsupported TypeLoc kind in declarator!");
John McCall51bd8032009-10-18 01:05:36 +00002855 }
2856 };
Argyrios Kyrtzidisf352bdd2009-09-29 19:43:35 +00002857}
2858
John McCalla93c9342009-12-07 02:54:59 +00002859/// \brief Create and instantiate a TypeSourceInfo with type source information.
Argyrios Kyrtzidis4adab7f2009-08-19 01:28:06 +00002860///
2861/// \param T QualType referring to the type as written in source code.
Douglas Gregor05baacb2010-04-12 23:19:01 +00002862///
2863/// \param ReturnTypeInfo For declarators whose return type does not show
2864/// up in the normal place in the declaration specifiers (such as a C++
2865/// conversion function), this pointer will refer to a type source information
2866/// for that return type.
John McCalla93c9342009-12-07 02:54:59 +00002867TypeSourceInfo *
Douglas Gregor05baacb2010-04-12 23:19:01 +00002868Sema::GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
2869 TypeSourceInfo *ReturnTypeInfo) {
John McCalla93c9342009-12-07 02:54:59 +00002870 TypeSourceInfo *TInfo = Context.CreateTypeSourceInfo(T);
2871 UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc();
Argyrios Kyrtzidis4adab7f2009-08-19 01:28:06 +00002872
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002873 // Handle parameter packs whose type is a pack expansion.
2874 if (isa<PackExpansionType>(T)) {
2875 cast<PackExpansionTypeLoc>(CurrTL).setEllipsisLoc(D.getEllipsisLoc());
2876 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
2877 }
2878
Sebastian Redl8ce35b02009-10-25 21:45:37 +00002879 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
John McCall14aa2172011-03-04 04:00:19 +00002880 while (isa<AttributedTypeLoc>(CurrTL)) {
2881 AttributedTypeLoc TL = cast<AttributedTypeLoc>(CurrTL);
2882 fillAttributedTypeLoc(TL, D.getTypeObject(i).getAttrs());
2883 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
2884 }
2885
Abramo Bagnarab6ab6c12011-03-05 14:42:21 +00002886 DeclaratorLocFiller(Context, D.getTypeObject(i)).Visit(CurrTL);
John McCall51bd8032009-10-18 01:05:36 +00002887 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
Argyrios Kyrtzidis4adab7f2009-08-19 01:28:06 +00002888 }
Argyrios Kyrtzidisf352bdd2009-09-29 19:43:35 +00002889
John McCallb3d87482010-08-24 05:47:05 +00002890 // If we have different source information for the return type, use
2891 // that. This really only applies to C++ conversion functions.
2892 if (ReturnTypeInfo) {
Douglas Gregor05baacb2010-04-12 23:19:01 +00002893 TypeLoc TL = ReturnTypeInfo->getTypeLoc();
2894 assert(TL.getFullDataSize() == CurrTL.getFullDataSize());
2895 memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize());
John McCallb3d87482010-08-24 05:47:05 +00002896 } else {
Douglas Gregorc21c7e92011-01-25 19:13:18 +00002897 TypeSpecLocFiller(Context, D.getDeclSpec()).Visit(CurrTL);
Douglas Gregor05baacb2010-04-12 23:19:01 +00002898 }
2899
John McCalla93c9342009-12-07 02:54:59 +00002900 return TInfo;
Argyrios Kyrtzidis4adab7f2009-08-19 01:28:06 +00002901}
2902
John McCalla93c9342009-12-07 02:54:59 +00002903/// \brief Create a LocInfoType to hold the given QualType and TypeSourceInfo.
John McCallb3d87482010-08-24 05:47:05 +00002904ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) {
Argyrios Kyrtzidis1bb8a452009-08-19 01:28:17 +00002905 // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
2906 // and Sema during declaration parsing. Try deallocating/caching them when
2907 // it's appropriate, instead of allocating them and keeping them around.
Douglas Gregoreb0eb492010-12-10 08:12:03 +00002908 LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType),
2909 TypeAlignment);
John McCalla93c9342009-12-07 02:54:59 +00002910 new (LocT) LocInfoType(T, TInfo);
Argyrios Kyrtzidis1bb8a452009-08-19 01:28:17 +00002911 assert(LocT->getTypeClass() != T->getTypeClass() &&
2912 "LocInfoType's TypeClass conflicts with an existing Type class");
John McCallb3d87482010-08-24 05:47:05 +00002913 return ParsedType::make(QualType(LocT, 0));
Argyrios Kyrtzidis1bb8a452009-08-19 01:28:17 +00002914}
2915
2916void LocInfoType::getAsStringInternal(std::string &Str,
2917 const PrintingPolicy &Policy) const {
Argyrios Kyrtzidis35d44e52009-08-19 01:46:06 +00002918 assert(false && "LocInfoType leaked into the type system; an opaque TypeTy*"
2919 " was used directly instead of getting the QualType through"
2920 " GetTypeFromParser");
Argyrios Kyrtzidis1bb8a452009-08-19 01:28:17 +00002921}
2922
John McCallf312b1e2010-08-26 23:41:50 +00002923TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002924 // C99 6.7.6: Type names have no identifier. This is already validated by
2925 // the parser.
2926 assert(D.getIdentifier() == 0 && "Type name should have no identifier!");
Mike Stump1eb44332009-09-09 15:08:12 +00002927
Argyrios Kyrtzidisd3880f82011-06-28 03:01:18 +00002928 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCallbf1a0282010-06-04 23:28:52 +00002929 QualType T = TInfo->getType();
Chris Lattner5153ee62009-04-25 08:47:54 +00002930 if (D.isInvalidType())
Douglas Gregor809070a2009-02-18 17:45:20 +00002931 return true;
Steve Naroff5912a352007-08-28 20:14:24 +00002932
Douglas Gregor402abb52009-05-28 23:31:59 +00002933 if (getLangOptions().CPlusPlus) {
2934 // Check that there are no default arguments (C++ only).
Douglas Gregor6d6eb572008-05-07 04:49:29 +00002935 CheckExtraCXXDefaultArguments(D);
Douglas Gregor402abb52009-05-28 23:31:59 +00002936 }
2937
John McCallb3d87482010-08-24 05:47:05 +00002938 return CreateParsedType(T, TInfo);
Reid Spencer5f016e22007-07-11 17:01:13 +00002939}
2940
Chris Lattnerc9b346d2008-06-29 00:50:08 +00002941//===----------------------------------------------------------------------===//
2942// Type Attribute Processing
2943//===----------------------------------------------------------------------===//
2944
2945/// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
2946/// specified type. The attribute contains 1 argument, the id of the address
2947/// space for the type.
Mike Stump1eb44332009-09-09 15:08:12 +00002948static void HandleAddressSpaceTypeAttribute(QualType &Type,
Chris Lattnerc9b346d2008-06-29 00:50:08 +00002949 const AttributeList &Attr, Sema &S){
John McCall0953e762009-09-24 19:53:00 +00002950
Chris Lattnerc9b346d2008-06-29 00:50:08 +00002951 // If this type is already address space qualified, reject it.
2952 // Clause 6.7.3 - Type qualifiers: "No type shall be qualified by qualifiers
2953 // for two or more different address spaces."
2954 if (Type.getAddressSpace()) {
2955 S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers);
Abramo Bagnarae215f722010-04-30 13:10:51 +00002956 Attr.setInvalid();
Chris Lattnerc9b346d2008-06-29 00:50:08 +00002957 return;
2958 }
Mike Stump1eb44332009-09-09 15:08:12 +00002959
Chris Lattnerc9b346d2008-06-29 00:50:08 +00002960 // Check the attribute arguments.
2961 if (Attr.getNumArgs() != 1) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002962 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
Abramo Bagnarae215f722010-04-30 13:10:51 +00002963 Attr.setInvalid();
Chris Lattnerc9b346d2008-06-29 00:50:08 +00002964 return;
2965 }
2966 Expr *ASArgExpr = static_cast<Expr *>(Attr.getArg(0));
2967 llvm::APSInt addrSpace(32);
Douglas Gregorac06a0e2010-05-18 23:01:22 +00002968 if (ASArgExpr->isTypeDependent() || ASArgExpr->isValueDependent() ||
2969 !ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00002970 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_not_int)
2971 << ASArgExpr->getSourceRange();
Abramo Bagnarae215f722010-04-30 13:10:51 +00002972 Attr.setInvalid();
Chris Lattnerc9b346d2008-06-29 00:50:08 +00002973 return;
2974 }
2975
John McCallefadb772009-07-28 06:52:18 +00002976 // Bounds checking.
2977 if (addrSpace.isSigned()) {
2978 if (addrSpace.isNegative()) {
2979 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_negative)
2980 << ASArgExpr->getSourceRange();
Abramo Bagnarae215f722010-04-30 13:10:51 +00002981 Attr.setInvalid();
John McCallefadb772009-07-28 06:52:18 +00002982 return;
2983 }
2984 addrSpace.setIsSigned(false);
2985 }
2986 llvm::APSInt max(addrSpace.getBitWidth());
John McCall0953e762009-09-24 19:53:00 +00002987 max = Qualifiers::MaxAddressSpace;
John McCallefadb772009-07-28 06:52:18 +00002988 if (addrSpace > max) {
2989 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_too_high)
John McCall0953e762009-09-24 19:53:00 +00002990 << Qualifiers::MaxAddressSpace << ASArgExpr->getSourceRange();
Abramo Bagnarae215f722010-04-30 13:10:51 +00002991 Attr.setInvalid();
John McCallefadb772009-07-28 06:52:18 +00002992 return;
2993 }
2994
Mike Stump1eb44332009-09-09 15:08:12 +00002995 unsigned ASIdx = static_cast<unsigned>(addrSpace.getZExtValue());
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00002996 Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
Chris Lattnerc9b346d2008-06-29 00:50:08 +00002997}
2998
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00002999/// handleObjCOwnershipTypeAttr - Process an objc_ownership
John McCallf85e1932011-06-15 23:02:42 +00003000/// attribute on the specified type.
3001///
3002/// Returns 'true' if the attribute was handled.
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00003003static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
John McCallf85e1932011-06-15 23:02:42 +00003004 AttributeList &attr,
3005 QualType &type) {
3006 if (!type->isObjCRetainableType() && !type->isDependentType())
3007 return false;
3008
3009 Sema &S = state.getSema();
3010
3011 if (type.getQualifiers().getObjCLifetime()) {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00003012 S.Diag(attr.getLoc(), diag::err_attr_objc_ownership_redundant)
John McCallf85e1932011-06-15 23:02:42 +00003013 << type;
3014 return true;
3015 }
3016
3017 if (!attr.getParameterName()) {
3018 S.Diag(attr.getLoc(), diag::err_attribute_argument_n_not_string)
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00003019 << "objc_ownership" << 1;
John McCallf85e1932011-06-15 23:02:42 +00003020 attr.setInvalid();
3021 return true;
3022 }
3023
3024 Qualifiers::ObjCLifetime lifetime;
3025 if (attr.getParameterName()->isStr("none"))
3026 lifetime = Qualifiers::OCL_ExplicitNone;
3027 else if (attr.getParameterName()->isStr("strong"))
3028 lifetime = Qualifiers::OCL_Strong;
3029 else if (attr.getParameterName()->isStr("weak"))
3030 lifetime = Qualifiers::OCL_Weak;
3031 else if (attr.getParameterName()->isStr("autoreleasing"))
3032 lifetime = Qualifiers::OCL_Autoreleasing;
3033 else {
3034 S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported)
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00003035 << "objc_ownership" << attr.getParameterName();
John McCallf85e1932011-06-15 23:02:42 +00003036 attr.setInvalid();
3037 return true;
3038 }
3039
3040 // Consume lifetime attributes without further comment outside of
3041 // ARC mode.
3042 if (!S.getLangOptions().ObjCAutoRefCount)
3043 return true;
3044
3045 Qualifiers qs;
3046 qs.setObjCLifetime(lifetime);
3047 QualType origType = type;
3048 type = S.Context.getQualifiedType(type, qs);
3049
3050 // If we have a valid source location for the attribute, use an
3051 // AttributedType instead.
3052 if (attr.getLoc().isValid())
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00003053 type = S.Context.getAttributedType(AttributedType::attr_objc_ownership,
John McCallf85e1932011-06-15 23:02:42 +00003054 origType, type);
3055
3056 // Forbid __weak if we don't have a runtime.
3057 if (lifetime == Qualifiers::OCL_Weak &&
3058 S.getLangOptions().ObjCNoAutoRefCountRuntime) {
3059
3060 // Actually, delay this until we know what we're parsing.
3061 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
3062 S.DelayedDiagnostics.add(
3063 sema::DelayedDiagnostic::makeForbiddenType(attr.getLoc(),
3064 diag::err_arc_weak_no_runtime, type, /*ignored*/ 0));
3065 } else {
3066 S.Diag(attr.getLoc(), diag::err_arc_weak_no_runtime);
3067 }
3068
3069 attr.setInvalid();
3070 return true;
3071 }
3072
3073 return true;
3074}
3075
John McCall711c52b2011-01-05 12:14:39 +00003076/// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type
3077/// attribute on the specified type. Returns true to indicate that
3078/// the attribute was handled, false to indicate that the type does
3079/// not permit the attribute.
3080static bool handleObjCGCTypeAttr(TypeProcessingState &state,
3081 AttributeList &attr,
3082 QualType &type) {
3083 Sema &S = state.getSema();
3084
3085 // Delay if this isn't some kind of pointer.
3086 if (!type->isPointerType() &&
3087 !type->isObjCObjectPointerType() &&
3088 !type->isBlockPointerType())
3089 return false;
3090
3091 if (type.getObjCGCAttr() != Qualifiers::GCNone) {
3092 S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc);
3093 attr.setInvalid();
3094 return true;
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00003095 }
Mike Stump1eb44332009-09-09 15:08:12 +00003096
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00003097 // Check the attribute arguments.
John McCall711c52b2011-01-05 12:14:39 +00003098 if (!attr.getParameterName()) {
3099 S.Diag(attr.getLoc(), diag::err_attribute_argument_n_not_string)
Fariborz Jahanianba372b82009-02-18 17:52:36 +00003100 << "objc_gc" << 1;
John McCall711c52b2011-01-05 12:14:39 +00003101 attr.setInvalid();
3102 return true;
Fariborz Jahanianba372b82009-02-18 17:52:36 +00003103 }
John McCall0953e762009-09-24 19:53:00 +00003104 Qualifiers::GC GCAttr;
John McCall711c52b2011-01-05 12:14:39 +00003105 if (attr.getNumArgs() != 0) {
3106 S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
3107 attr.setInvalid();
3108 return true;
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00003109 }
John McCall711c52b2011-01-05 12:14:39 +00003110 if (attr.getParameterName()->isStr("weak"))
John McCall0953e762009-09-24 19:53:00 +00003111 GCAttr = Qualifiers::Weak;
John McCall711c52b2011-01-05 12:14:39 +00003112 else if (attr.getParameterName()->isStr("strong"))
John McCall0953e762009-09-24 19:53:00 +00003113 GCAttr = Qualifiers::Strong;
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00003114 else {
John McCall711c52b2011-01-05 12:14:39 +00003115 S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported)
3116 << "objc_gc" << attr.getParameterName();
3117 attr.setInvalid();
3118 return true;
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00003119 }
Mike Stump1eb44332009-09-09 15:08:12 +00003120
John McCall14aa2172011-03-04 04:00:19 +00003121 QualType origType = type;
3122 type = S.Context.getObjCGCQualType(origType, GCAttr);
3123
3124 // Make an attributed type to preserve the source information.
3125 if (attr.getLoc().isValid())
3126 type = S.Context.getAttributedType(AttributedType::attr_objc_gc,
3127 origType, type);
3128
John McCall711c52b2011-01-05 12:14:39 +00003129 return true;
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00003130}
3131
John McCalle6a365d2010-12-19 02:44:49 +00003132namespace {
3133 /// A helper class to unwrap a type down to a function for the
3134 /// purposes of applying attributes there.
3135 ///
3136 /// Use:
3137 /// FunctionTypeUnwrapper unwrapped(SemaRef, T);
3138 /// if (unwrapped.isFunctionType()) {
3139 /// const FunctionType *fn = unwrapped.get();
3140 /// // change fn somehow
3141 /// T = unwrapped.wrap(fn);
3142 /// }
3143 struct FunctionTypeUnwrapper {
3144 enum WrapKind {
3145 Desugar,
3146 Parens,
3147 Pointer,
3148 BlockPointer,
3149 Reference,
3150 MemberPointer
3151 };
3152
3153 QualType Original;
3154 const FunctionType *Fn;
3155 llvm::SmallVector<unsigned char /*WrapKind*/, 8> Stack;
3156
3157 FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) {
3158 while (true) {
3159 const Type *Ty = T.getTypePtr();
3160 if (isa<FunctionType>(Ty)) {
3161 Fn = cast<FunctionType>(Ty);
3162 return;
3163 } else if (isa<ParenType>(Ty)) {
3164 T = cast<ParenType>(Ty)->getInnerType();
3165 Stack.push_back(Parens);
3166 } else if (isa<PointerType>(Ty)) {
3167 T = cast<PointerType>(Ty)->getPointeeType();
3168 Stack.push_back(Pointer);
3169 } else if (isa<BlockPointerType>(Ty)) {
3170 T = cast<BlockPointerType>(Ty)->getPointeeType();
3171 Stack.push_back(BlockPointer);
3172 } else if (isa<MemberPointerType>(Ty)) {
3173 T = cast<MemberPointerType>(Ty)->getPointeeType();
3174 Stack.push_back(MemberPointer);
3175 } else if (isa<ReferenceType>(Ty)) {
3176 T = cast<ReferenceType>(Ty)->getPointeeType();
3177 Stack.push_back(Reference);
3178 } else {
3179 const Type *DTy = Ty->getUnqualifiedDesugaredType();
3180 if (Ty == DTy) {
3181 Fn = 0;
3182 return;
3183 }
3184
3185 T = QualType(DTy, 0);
3186 Stack.push_back(Desugar);
3187 }
3188 }
3189 }
3190
3191 bool isFunctionType() const { return (Fn != 0); }
3192 const FunctionType *get() const { return Fn; }
3193
3194 QualType wrap(Sema &S, const FunctionType *New) {
3195 // If T wasn't modified from the unwrapped type, do nothing.
3196 if (New == get()) return Original;
3197
3198 Fn = New;
3199 return wrap(S.Context, Original, 0);
3200 }
3201
3202 private:
3203 QualType wrap(ASTContext &C, QualType Old, unsigned I) {
3204 if (I == Stack.size())
3205 return C.getQualifiedType(Fn, Old.getQualifiers());
3206
3207 // Build up the inner type, applying the qualifiers from the old
3208 // type to the new type.
3209 SplitQualType SplitOld = Old.split();
3210
3211 // As a special case, tail-recurse if there are no qualifiers.
3212 if (SplitOld.second.empty())
3213 return wrap(C, SplitOld.first, I);
3214 return C.getQualifiedType(wrap(C, SplitOld.first, I), SplitOld.second);
3215 }
3216
3217 QualType wrap(ASTContext &C, const Type *Old, unsigned I) {
3218 if (I == Stack.size()) return QualType(Fn, 0);
3219
3220 switch (static_cast<WrapKind>(Stack[I++])) {
3221 case Desugar:
3222 // This is the point at which we potentially lose source
3223 // information.
3224 return wrap(C, Old->getUnqualifiedDesugaredType(), I);
3225
3226 case Parens: {
3227 QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I);
3228 return C.getParenType(New);
3229 }
3230
3231 case Pointer: {
3232 QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I);
3233 return C.getPointerType(New);
3234 }
3235
3236 case BlockPointer: {
3237 QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I);
3238 return C.getBlockPointerType(New);
3239 }
3240
3241 case MemberPointer: {
3242 const MemberPointerType *OldMPT = cast<MemberPointerType>(Old);
3243 QualType New = wrap(C, OldMPT->getPointeeType(), I);
3244 return C.getMemberPointerType(New, OldMPT->getClass());
3245 }
3246
3247 case Reference: {
3248 const ReferenceType *OldRef = cast<ReferenceType>(Old);
3249 QualType New = wrap(C, OldRef->getPointeeType(), I);
3250 if (isa<LValueReferenceType>(OldRef))
3251 return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue());
3252 else
3253 return C.getRValueReferenceType(New);
3254 }
3255 }
3256
3257 llvm_unreachable("unknown wrapping kind");
3258 return QualType();
3259 }
3260 };
3261}
3262
John McCall711c52b2011-01-05 12:14:39 +00003263/// Process an individual function attribute. Returns true to
3264/// indicate that the attribute was handled, false if it wasn't.
3265static bool handleFunctionTypeAttr(TypeProcessingState &state,
3266 AttributeList &attr,
3267 QualType &type) {
3268 Sema &S = state.getSema();
John McCalle6a365d2010-12-19 02:44:49 +00003269
John McCall711c52b2011-01-05 12:14:39 +00003270 FunctionTypeUnwrapper unwrapped(S, type);
Mike Stump24556362009-07-25 21:26:53 +00003271
John McCall711c52b2011-01-05 12:14:39 +00003272 if (attr.getKind() == AttributeList::AT_noreturn) {
3273 if (S.CheckNoReturnAttr(attr))
John McCall04a67a62010-02-05 21:31:56 +00003274 return true;
John McCalle6a365d2010-12-19 02:44:49 +00003275
John McCall711c52b2011-01-05 12:14:39 +00003276 // Delay if this is not a function type.
3277 if (!unwrapped.isFunctionType())
3278 return false;
3279
John McCall04a67a62010-02-05 21:31:56 +00003280 // Otherwise we can process right away.
John McCall711c52b2011-01-05 12:14:39 +00003281 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true);
3282 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
3283 return true;
John McCall04a67a62010-02-05 21:31:56 +00003284 }
Mike Stump24556362009-07-25 21:26:53 +00003285
John McCallf85e1932011-06-15 23:02:42 +00003286 // ns_returns_retained is not always a type attribute, but if we got
3287 // here, we're treating it as one right now.
3288 if (attr.getKind() == AttributeList::AT_ns_returns_retained) {
3289 assert(S.getLangOptions().ObjCAutoRefCount &&
3290 "ns_returns_retained treated as type attribute in non-ARC");
3291 if (attr.getNumArgs()) return true;
3292
3293 // Delay if this is not a function type.
3294 if (!unwrapped.isFunctionType())
3295 return false;
3296
3297 FunctionType::ExtInfo EI
3298 = unwrapped.get()->getExtInfo().withProducesResult(true);
3299 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
3300 return true;
3301 }
3302
John McCall711c52b2011-01-05 12:14:39 +00003303 if (attr.getKind() == AttributeList::AT_regparm) {
3304 unsigned value;
3305 if (S.CheckRegparmAttr(attr, value))
Rafael Espindola425ef722010-03-30 22:15:11 +00003306 return true;
3307
John McCall711c52b2011-01-05 12:14:39 +00003308 // Delay if this is not a function type.
3309 if (!unwrapped.isFunctionType())
Rafael Espindola425ef722010-03-30 22:15:11 +00003310 return false;
3311
Argyrios Kyrtzidisce955662011-01-25 23:16:40 +00003312 // Diagnose regparm with fastcall.
3313 const FunctionType *fn = unwrapped.get();
3314 CallingConv CC = fn->getCallConv();
3315 if (CC == CC_X86FastCall) {
3316 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
3317 << FunctionType::getNameForCallConv(CC)
3318 << "regparm";
3319 attr.setInvalid();
3320 return true;
3321 }
3322
John McCalle6a365d2010-12-19 02:44:49 +00003323 FunctionType::ExtInfo EI =
John McCall711c52b2011-01-05 12:14:39 +00003324 unwrapped.get()->getExtInfo().withRegParm(value);
3325 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
3326 return true;
Rafael Espindola425ef722010-03-30 22:15:11 +00003327 }
3328
John McCall04a67a62010-02-05 21:31:56 +00003329 // Otherwise, a calling convention.
John McCall711c52b2011-01-05 12:14:39 +00003330 CallingConv CC;
3331 if (S.CheckCallingConvAttr(attr, CC))
3332 return true;
John McCallf82b4e82010-02-04 05:44:44 +00003333
John McCall04a67a62010-02-05 21:31:56 +00003334 // Delay if the type didn't work out to a function.
John McCall711c52b2011-01-05 12:14:39 +00003335 if (!unwrapped.isFunctionType()) return false;
John McCall04a67a62010-02-05 21:31:56 +00003336
John McCall711c52b2011-01-05 12:14:39 +00003337 const FunctionType *fn = unwrapped.get();
3338 CallingConv CCOld = fn->getCallConv();
Charles Davis064f7db2010-02-23 06:13:55 +00003339 if (S.Context.getCanonicalCallConv(CC) ==
Abramo Bagnarae215f722010-04-30 13:10:51 +00003340 S.Context.getCanonicalCallConv(CCOld)) {
Argyrios Kyrtzidisce955662011-01-25 23:16:40 +00003341 FunctionType::ExtInfo EI= unwrapped.get()->getExtInfo().withCallingConv(CC);
3342 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
John McCall711c52b2011-01-05 12:14:39 +00003343 return true;
Abramo Bagnarae215f722010-04-30 13:10:51 +00003344 }
John McCall04a67a62010-02-05 21:31:56 +00003345
3346 if (CCOld != CC_Default) {
3347 // Should we diagnose reapplications of the same convention?
John McCall711c52b2011-01-05 12:14:39 +00003348 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
John McCall04a67a62010-02-05 21:31:56 +00003349 << FunctionType::getNameForCallConv(CC)
3350 << FunctionType::getNameForCallConv(CCOld);
John McCall711c52b2011-01-05 12:14:39 +00003351 attr.setInvalid();
3352 return true;
John McCall04a67a62010-02-05 21:31:56 +00003353 }
3354
3355 // Diagnose the use of X86 fastcall on varargs or unprototyped functions.
3356 if (CC == CC_X86FastCall) {
John McCall711c52b2011-01-05 12:14:39 +00003357 if (isa<FunctionNoProtoType>(fn)) {
3358 S.Diag(attr.getLoc(), diag::err_cconv_knr)
John McCall04a67a62010-02-05 21:31:56 +00003359 << FunctionType::getNameForCallConv(CC);
John McCall711c52b2011-01-05 12:14:39 +00003360 attr.setInvalid();
3361 return true;
John McCall04a67a62010-02-05 21:31:56 +00003362 }
3363
John McCall711c52b2011-01-05 12:14:39 +00003364 const FunctionProtoType *FnP = cast<FunctionProtoType>(fn);
John McCall04a67a62010-02-05 21:31:56 +00003365 if (FnP->isVariadic()) {
John McCall711c52b2011-01-05 12:14:39 +00003366 S.Diag(attr.getLoc(), diag::err_cconv_varargs)
John McCall04a67a62010-02-05 21:31:56 +00003367 << FunctionType::getNameForCallConv(CC);
John McCall711c52b2011-01-05 12:14:39 +00003368 attr.setInvalid();
3369 return true;
John McCall04a67a62010-02-05 21:31:56 +00003370 }
Argyrios Kyrtzidisce955662011-01-25 23:16:40 +00003371
3372 // Also diagnose fastcall with regparm.
Eli Friedmana49218e2011-04-09 08:18:08 +00003373 if (fn->getHasRegParm()) {
Argyrios Kyrtzidisce955662011-01-25 23:16:40 +00003374 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
3375 << "regparm"
3376 << FunctionType::getNameForCallConv(CC);
3377 attr.setInvalid();
3378 return true;
3379 }
John McCall04a67a62010-02-05 21:31:56 +00003380 }
3381
John McCall711c52b2011-01-05 12:14:39 +00003382 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withCallingConv(CC);
3383 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
3384 return true;
John McCallf82b4e82010-02-04 05:44:44 +00003385}
3386
Peter Collingbourne207f4d82011-03-18 22:38:29 +00003387/// Handle OpenCL image access qualifiers: read_only, write_only, read_write
3388static void HandleOpenCLImageAccessAttribute(QualType& CurType,
3389 const AttributeList &Attr,
3390 Sema &S) {
3391 // Check the attribute arguments.
3392 if (Attr.getNumArgs() != 1) {
3393 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
3394 Attr.setInvalid();
3395 return;
3396 }
3397 Expr *sizeExpr = static_cast<Expr *>(Attr.getArg(0));
3398 llvm::APSInt arg(32);
3399 if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() ||
3400 !sizeExpr->isIntegerConstantExpr(arg, S.Context)) {
3401 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
3402 << "opencl_image_access" << sizeExpr->getSourceRange();
3403 Attr.setInvalid();
3404 return;
3405 }
3406 unsigned iarg = static_cast<unsigned>(arg.getZExtValue());
3407 switch (iarg) {
3408 case CLIA_read_only:
3409 case CLIA_write_only:
3410 case CLIA_read_write:
3411 // Implemented in a separate patch
3412 break;
3413 default:
3414 // Implemented in a separate patch
3415 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
3416 << sizeExpr->getSourceRange();
3417 Attr.setInvalid();
3418 break;
3419 }
3420}
3421
John Thompson6e132aa2009-12-04 21:51:28 +00003422/// HandleVectorSizeAttribute - this attribute is only applicable to integral
3423/// and float scalars, although arrays, pointers, and function return values are
3424/// allowed in conjunction with this construct. Aggregates with this attribute
3425/// are invalid, even if they are of the same size as a corresponding scalar.
3426/// The raw attribute should contain precisely 1 argument, the vector size for
3427/// the variable, measured in bytes. If curType and rawAttr are well formed,
3428/// this routine will return a new vector type.
Chris Lattner788b0fd2010-06-23 06:00:24 +00003429static void HandleVectorSizeAttr(QualType& CurType, const AttributeList &Attr,
3430 Sema &S) {
Bob Wilson56affbc2010-11-16 00:32:16 +00003431 // Check the attribute arguments.
John Thompson6e132aa2009-12-04 21:51:28 +00003432 if (Attr.getNumArgs() != 1) {
3433 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
Abramo Bagnarae215f722010-04-30 13:10:51 +00003434 Attr.setInvalid();
John Thompson6e132aa2009-12-04 21:51:28 +00003435 return;
3436 }
3437 Expr *sizeExpr = static_cast<Expr *>(Attr.getArg(0));
3438 llvm::APSInt vecSize(32);
Douglas Gregorac06a0e2010-05-18 23:01:22 +00003439 if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() ||
3440 !sizeExpr->isIntegerConstantExpr(vecSize, S.Context)) {
John Thompson6e132aa2009-12-04 21:51:28 +00003441 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
3442 << "vector_size" << sizeExpr->getSourceRange();
Abramo Bagnarae215f722010-04-30 13:10:51 +00003443 Attr.setInvalid();
John Thompson6e132aa2009-12-04 21:51:28 +00003444 return;
3445 }
3446 // the base type must be integer or float, and can't already be a vector.
Douglas Gregorf6094622010-07-23 15:58:24 +00003447 if (!CurType->isIntegerType() && !CurType->isRealFloatingType()) {
John Thompson6e132aa2009-12-04 21:51:28 +00003448 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
Abramo Bagnarae215f722010-04-30 13:10:51 +00003449 Attr.setInvalid();
John Thompson6e132aa2009-12-04 21:51:28 +00003450 return;
3451 }
3452 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
3453 // vecSize is specified in bytes - convert to bits.
3454 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
3455
3456 // the vector size needs to be an integral multiple of the type size.
3457 if (vectorSize % typeSize) {
3458 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
3459 << sizeExpr->getSourceRange();
Abramo Bagnarae215f722010-04-30 13:10:51 +00003460 Attr.setInvalid();
John Thompson6e132aa2009-12-04 21:51:28 +00003461 return;
3462 }
3463 if (vectorSize == 0) {
3464 S.Diag(Attr.getLoc(), diag::err_attribute_zero_size)
3465 << sizeExpr->getSourceRange();
Abramo Bagnarae215f722010-04-30 13:10:51 +00003466 Attr.setInvalid();
John Thompson6e132aa2009-12-04 21:51:28 +00003467 return;
3468 }
3469
3470 // Success! Instantiate the vector type, the number of elements is > 0, and
3471 // not required to be a power of 2, unlike GCC.
Chris Lattner788b0fd2010-06-23 06:00:24 +00003472 CurType = S.Context.getVectorType(CurType, vectorSize/typeSize,
Bob Wilsone86d78c2010-11-10 21:56:12 +00003473 VectorType::GenericVector);
John Thompson6e132aa2009-12-04 21:51:28 +00003474}
3475
Douglas Gregor4ac01402011-06-15 16:02:29 +00003476/// \brief Process the OpenCL-like ext_vector_type attribute when it occurs on
3477/// a type.
3478static void HandleExtVectorTypeAttr(QualType &CurType,
3479 const AttributeList &Attr,
3480 Sema &S) {
3481 Expr *sizeExpr;
3482
3483 // Special case where the argument is a template id.
3484 if (Attr.getParameterName()) {
3485 CXXScopeSpec SS;
3486 UnqualifiedId id;
3487 id.setIdentifier(Attr.getParameterName(), Attr.getLoc());
3488
3489 ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, id, false,
3490 false);
3491 if (Size.isInvalid())
3492 return;
3493
3494 sizeExpr = Size.get();
3495 } else {
3496 // check the attribute arguments.
3497 if (Attr.getNumArgs() != 1) {
3498 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
3499 return;
3500 }
3501 sizeExpr = Attr.getArg(0);
3502 }
3503
3504 // Create the vector type.
3505 QualType T = S.BuildExtVectorType(CurType, sizeExpr, Attr.getLoc());
3506 if (!T.isNull())
3507 CurType = T;
3508}
3509
Bob Wilson4211bb62010-11-16 00:32:24 +00003510/// HandleNeonVectorTypeAttr - The "neon_vector_type" and
3511/// "neon_polyvector_type" attributes are used to create vector types that
3512/// are mangled according to ARM's ABI. Otherwise, these types are identical
3513/// to those created with the "vector_size" attribute. Unlike "vector_size"
3514/// the argument to these Neon attributes is the number of vector elements,
3515/// not the vector size in bytes. The vector width and element type must
3516/// match one of the standard Neon vector types.
3517static void HandleNeonVectorTypeAttr(QualType& CurType,
3518 const AttributeList &Attr, Sema &S,
3519 VectorType::VectorKind VecKind,
3520 const char *AttrName) {
3521 // Check the attribute arguments.
3522 if (Attr.getNumArgs() != 1) {
3523 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
3524 Attr.setInvalid();
3525 return;
3526 }
3527 // The number of elements must be an ICE.
3528 Expr *numEltsExpr = static_cast<Expr *>(Attr.getArg(0));
3529 llvm::APSInt numEltsInt(32);
3530 if (numEltsExpr->isTypeDependent() || numEltsExpr->isValueDependent() ||
3531 !numEltsExpr->isIntegerConstantExpr(numEltsInt, S.Context)) {
3532 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
3533 << AttrName << numEltsExpr->getSourceRange();
3534 Attr.setInvalid();
3535 return;
3536 }
3537 // Only certain element types are supported for Neon vectors.
3538 const BuiltinType* BTy = CurType->getAs<BuiltinType>();
3539 if (!BTy ||
3540 (VecKind == VectorType::NeonPolyVector &&
3541 BTy->getKind() != BuiltinType::SChar &&
3542 BTy->getKind() != BuiltinType::Short) ||
3543 (BTy->getKind() != BuiltinType::SChar &&
3544 BTy->getKind() != BuiltinType::UChar &&
3545 BTy->getKind() != BuiltinType::Short &&
3546 BTy->getKind() != BuiltinType::UShort &&
3547 BTy->getKind() != BuiltinType::Int &&
3548 BTy->getKind() != BuiltinType::UInt &&
3549 BTy->getKind() != BuiltinType::LongLong &&
3550 BTy->getKind() != BuiltinType::ULongLong &&
3551 BTy->getKind() != BuiltinType::Float)) {
3552 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) <<CurType;
3553 Attr.setInvalid();
3554 return;
3555 }
3556 // The total size of the vector must be 64 or 128 bits.
3557 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
3558 unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue());
3559 unsigned vecSize = typeSize * numElts;
3560 if (vecSize != 64 && vecSize != 128) {
3561 S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType;
3562 Attr.setInvalid();
3563 return;
3564 }
3565
3566 CurType = S.Context.getVectorType(CurType, numElts, VecKind);
3567}
3568
John McCall711c52b2011-01-05 12:14:39 +00003569static void processTypeAttrs(TypeProcessingState &state, QualType &type,
3570 bool isDeclSpec, AttributeList *attrs) {
Chris Lattner232e8822008-02-21 01:08:11 +00003571 // Scan through and apply attributes to this type where it makes sense. Some
3572 // attributes (such as __address_space__, __vector_size__, etc) apply to the
3573 // type, but others can be present in the type specifiers even though they
Chris Lattnerfca0ddd2008-06-26 06:27:57 +00003574 // apply to the decl. Here we apply type attributes and ignore the rest.
John McCall711c52b2011-01-05 12:14:39 +00003575
3576 AttributeList *next;
3577 do {
3578 AttributeList &attr = *attrs;
3579 next = attr.getNext();
3580
Abramo Bagnarae215f722010-04-30 13:10:51 +00003581 // Skip attributes that were marked to be invalid.
John McCall711c52b2011-01-05 12:14:39 +00003582 if (attr.isInvalid())
Abramo Bagnarae215f722010-04-30 13:10:51 +00003583 continue;
3584
Abramo Bagnarab1f1b262010-04-30 09:13:03 +00003585 // If this is an attribute we can handle, do so now,
3586 // otherwise, add it to the FnAttrs list for rechaining.
John McCall711c52b2011-01-05 12:14:39 +00003587 switch (attr.getKind()) {
Chris Lattner232e8822008-02-21 01:08:11 +00003588 default: break;
John McCall04a67a62010-02-05 21:31:56 +00003589
Chris Lattner232e8822008-02-21 01:08:11 +00003590 case AttributeList::AT_address_space:
John McCall711c52b2011-01-05 12:14:39 +00003591 HandleAddressSpaceTypeAttribute(type, attr, state.getSema());
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003592 break;
John McCall711c52b2011-01-05 12:14:39 +00003593 OBJC_POINTER_TYPE_ATTRS_CASELIST:
3594 if (!handleObjCPointerTypeAttr(state, attr, type))
3595 distributeObjCPointerTypeAttr(state, attr, type);
Mike Stump24556362009-07-25 21:26:53 +00003596 break;
John Thompson6e132aa2009-12-04 21:51:28 +00003597 case AttributeList::AT_vector_size:
John McCall711c52b2011-01-05 12:14:39 +00003598 HandleVectorSizeAttr(type, attr, state.getSema());
John McCall04a67a62010-02-05 21:31:56 +00003599 break;
Douglas Gregor4ac01402011-06-15 16:02:29 +00003600 case AttributeList::AT_ext_vector_type:
3601 if (state.getDeclarator().getDeclSpec().getStorageClassSpec()
3602 != DeclSpec::SCS_typedef)
3603 HandleExtVectorTypeAttr(type, attr, state.getSema());
3604 break;
Bob Wilson4211bb62010-11-16 00:32:24 +00003605 case AttributeList::AT_neon_vector_type:
John McCall711c52b2011-01-05 12:14:39 +00003606 HandleNeonVectorTypeAttr(type, attr, state.getSema(),
3607 VectorType::NeonVector, "neon_vector_type");
Bob Wilson4211bb62010-11-16 00:32:24 +00003608 break;
3609 case AttributeList::AT_neon_polyvector_type:
John McCall711c52b2011-01-05 12:14:39 +00003610 HandleNeonVectorTypeAttr(type, attr, state.getSema(),
3611 VectorType::NeonPolyVector,
Bob Wilson4211bb62010-11-16 00:32:24 +00003612 "neon_polyvector_type");
3613 break;
Peter Collingbourne207f4d82011-03-18 22:38:29 +00003614 case AttributeList::AT_opencl_image_access:
3615 HandleOpenCLImageAccessAttribute(type, attr, state.getSema());
3616 break;
3617
John McCallf85e1932011-06-15 23:02:42 +00003618 case AttributeList::AT_ns_returns_retained:
3619 if (!state.getSema().getLangOptions().ObjCAutoRefCount)
3620 break;
3621 // fallthrough into the function attrs
3622
John McCall711c52b2011-01-05 12:14:39 +00003623 FUNCTION_TYPE_ATTRS_CASELIST:
3624 // Never process function type attributes as part of the
3625 // declaration-specifiers.
3626 if (isDeclSpec)
3627 distributeFunctionTypeAttrFromDeclSpec(state, attr, type);
3628
3629 // Otherwise, handle the possible delays.
3630 else if (!handleFunctionTypeAttr(state, attr, type))
3631 distributeFunctionTypeAttr(state, attr, type);
John Thompson6e132aa2009-12-04 21:51:28 +00003632 break;
Chris Lattner232e8822008-02-21 01:08:11 +00003633 }
John McCall711c52b2011-01-05 12:14:39 +00003634 } while ((attrs = next));
Chris Lattner232e8822008-02-21 01:08:11 +00003635}
3636
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003637/// \brief Ensure that the type of the given expression is complete.
3638///
3639/// This routine checks whether the expression \p E has a complete type. If the
3640/// expression refers to an instantiable construct, that instantiation is
3641/// performed as needed to complete its type. Furthermore
3642/// Sema::RequireCompleteType is called for the expression's type (or in the
3643/// case of a reference type, the referred-to type).
3644///
3645/// \param E The expression whose type is required to be complete.
3646/// \param PD The partial diagnostic that will be printed out if the type cannot
3647/// be completed.
3648///
3649/// \returns \c true if the type of \p E is incomplete and diagnosed, \c false
3650/// otherwise.
3651bool Sema::RequireCompleteExprType(Expr *E, const PartialDiagnostic &PD,
3652 std::pair<SourceLocation,
3653 PartialDiagnostic> Note) {
3654 QualType T = E->getType();
3655
3656 // Fast path the case where the type is already complete.
3657 if (!T->isIncompleteType())
3658 return false;
3659
3660 // Incomplete array types may be completed by the initializer attached to
3661 // their definitions. For static data members of class templates we need to
3662 // instantiate the definition to get this initializer and complete the type.
3663 if (T->isIncompleteArrayType()) {
3664 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3665 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
3666 if (Var->isStaticDataMember() &&
3667 Var->getInstantiatedFromStaticDataMember()) {
Douglas Gregor36f255c2011-06-03 14:28:43 +00003668
3669 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
3670 assert(MSInfo && "Missing member specialization information?");
3671 if (MSInfo->getTemplateSpecializationKind()
3672 != TSK_ExplicitSpecialization) {
3673 // If we don't already have a point of instantiation, this is it.
3674 if (MSInfo->getPointOfInstantiation().isInvalid()) {
3675 MSInfo->setPointOfInstantiation(E->getLocStart());
3676
3677 // This is a modification of an existing AST node. Notify
3678 // listeners.
3679 if (ASTMutationListener *L = getASTMutationListener())
3680 L->StaticDataMemberInstantiated(Var);
3681 }
3682
3683 InstantiateStaticDataMemberDefinition(E->getExprLoc(), Var);
3684
3685 // Update the type to the newly instantiated definition's type both
3686 // here and within the expression.
3687 if (VarDecl *Def = Var->getDefinition()) {
3688 DRE->setDecl(Def);
3689 T = Def->getType();
3690 DRE->setType(T);
3691 E->setType(T);
3692 }
Douglas Gregorf15748a2011-06-03 03:35:07 +00003693 }
3694
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003695 // We still go on to try to complete the type independently, as it
3696 // may also require instantiations or diagnostics if it remains
3697 // incomplete.
3698 }
3699 }
3700 }
3701 }
3702
3703 // FIXME: Are there other cases which require instantiating something other
3704 // than the type to complete the type of an expression?
3705
3706 // Look through reference types and complete the referred type.
3707 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
3708 T = Ref->getPointeeType();
3709
3710 return RequireCompleteType(E->getExprLoc(), T, PD, Note);
3711}
3712
Mike Stump1eb44332009-09-09 15:08:12 +00003713/// @brief Ensure that the type T is a complete type.
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003714///
3715/// This routine checks whether the type @p T is complete in any
3716/// context where a complete type is required. If @p T is a complete
Douglas Gregor86447ec2009-03-09 16:13:40 +00003717/// type, returns false. If @p T is a class template specialization,
3718/// this routine then attempts to perform class template
3719/// instantiation. If instantiation fails, or if @p T is incomplete
3720/// and cannot be completed, issues the diagnostic @p diag (giving it
3721/// the type @p T) and returns true.
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003722///
3723/// @param Loc The location in the source that the incomplete type
3724/// diagnostic should refer to.
3725///
3726/// @param T The type that this routine is examining for completeness.
3727///
Mike Stump1eb44332009-09-09 15:08:12 +00003728/// @param PD The partial diagnostic that will be printed out if T is not a
Anders Carlssonb7906612009-08-26 23:45:07 +00003729/// complete type.
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003730///
3731/// @returns @c true if @p T is incomplete and a diagnostic was emitted,
3732/// @c false otherwise.
Anders Carlsson91a0cc92009-08-26 22:33:56 +00003733bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
Anders Carlsson8c8d9192009-10-09 23:51:55 +00003734 const PartialDiagnostic &PD,
3735 std::pair<SourceLocation,
3736 PartialDiagnostic> Note) {
Anders Carlsson91a0cc92009-08-26 22:33:56 +00003737 unsigned diag = PD.getDiagID();
Mike Stump1eb44332009-09-09 15:08:12 +00003738
Douglas Gregor573d9c32009-10-21 23:19:44 +00003739 // FIXME: Add this assertion to make sure we always get instantiation points.
3740 // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
Douglas Gregor690dc7f2009-05-21 23:48:18 +00003741 // FIXME: Add this assertion to help us flush out problems with
3742 // checking for dependent types and type-dependent expressions.
3743 //
Mike Stump1eb44332009-09-09 15:08:12 +00003744 // assert(!T->isDependentType() &&
Douglas Gregor690dc7f2009-05-21 23:48:18 +00003745 // "Can't ask whether a dependent type is complete");
3746
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003747 // If we have a complete type, we're done.
3748 if (!T->isIncompleteType())
3749 return false;
Eli Friedman3c0eb162008-05-27 03:33:27 +00003750
Douglas Gregord475b8d2009-03-25 21:17:03 +00003751 // If we have a class template specialization or a class member of a
Sebastian Redl923d56d2009-11-05 15:52:31 +00003752 // class template specialization, or an array with known size of such,
3753 // try to instantiate it.
3754 QualType MaybeTemplate = T;
Douglas Gregor89c49f02009-11-09 22:08:55 +00003755 if (const ConstantArrayType *Array = Context.getAsConstantArrayType(T))
Sebastian Redl923d56d2009-11-05 15:52:31 +00003756 MaybeTemplate = Array->getElementType();
3757 if (const RecordType *Record = MaybeTemplate->getAs<RecordType>()) {
Douglas Gregor2943aed2009-03-03 04:44:36 +00003758 if (ClassTemplateSpecializationDecl *ClassTemplateSpec
Douglas Gregord475b8d2009-03-25 21:17:03 +00003759 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
Douglas Gregor972e6ce2009-10-27 06:26:26 +00003760 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared)
3761 return InstantiateClassTemplateSpecialization(Loc, ClassTemplateSpec,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00003762 TSK_ImplicitInstantiation,
Douglas Gregor5842ba92009-08-24 15:23:48 +00003763 /*Complain=*/diag != 0);
Mike Stump1eb44332009-09-09 15:08:12 +00003764 } else if (CXXRecordDecl *Rec
Douglas Gregord475b8d2009-03-25 21:17:03 +00003765 = dyn_cast<CXXRecordDecl>(Record->getDecl())) {
3766 if (CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass()) {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003767 MemberSpecializationInfo *MSInfo = Rec->getMemberSpecializationInfo();
3768 assert(MSInfo && "Missing member specialization information?");
Douglas Gregor357bbd02009-08-28 20:50:45 +00003769 // This record was instantiated from a class within a template.
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003770 if (MSInfo->getTemplateSpecializationKind()
Douglas Gregor972e6ce2009-10-27 06:26:26 +00003771 != TSK_ExplicitSpecialization)
Douglas Gregorf6b11852009-10-08 15:14:33 +00003772 return InstantiateClass(Loc, Rec, Pattern,
3773 getTemplateInstantiationArgs(Rec),
3774 TSK_ImplicitInstantiation,
3775 /*Complain=*/diag != 0);
Douglas Gregord475b8d2009-03-25 21:17:03 +00003776 }
3777 }
3778 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00003779
Douglas Gregor5842ba92009-08-24 15:23:48 +00003780 if (diag == 0)
3781 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003782
John McCall916c8702010-11-16 01:44:35 +00003783 const TagType *Tag = T->getAs<TagType>();
Rafael Espindola01620702010-03-21 22:56:43 +00003784
3785 // Avoid diagnosing invalid decls as incomplete.
3786 if (Tag && Tag->getDecl()->isInvalidDecl())
3787 return true;
3788
John McCall916c8702010-11-16 01:44:35 +00003789 // Give the external AST source a chance to complete the type.
3790 if (Tag && Tag->getDecl()->hasExternalLexicalStorage()) {
3791 Context.getExternalSource()->CompleteType(Tag->getDecl());
3792 if (!Tag->isIncompleteType())
3793 return false;
3794 }
3795
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003796 // We have an incomplete type. Produce a diagnostic.
Anders Carlsson91a0cc92009-08-26 22:33:56 +00003797 Diag(Loc, PD) << T;
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003798
Anders Carlsson8c8d9192009-10-09 23:51:55 +00003799 // If we have a note, produce it.
3800 if (!Note.first.isInvalid())
3801 Diag(Note.first, Note.second);
3802
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003803 // If the type was a forward declaration of a class/struct/union
Rafael Espindola01620702010-03-21 22:56:43 +00003804 // type, produce a note.
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003805 if (Tag && !Tag->getDecl()->isInvalidDecl())
Mike Stump1eb44332009-09-09 15:08:12 +00003806 Diag(Tag->getDecl()->getLocation(),
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003807 Tag->isBeingDefined() ? diag::note_type_being_defined
3808 : diag::note_forward_declaration)
3809 << QualType(Tag, 0);
3810
3811 return true;
3812}
Douglas Gregore6258932009-03-19 00:39:20 +00003813
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003814bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
3815 const PartialDiagnostic &PD) {
3816 return RequireCompleteType(Loc, T, PD,
3817 std::make_pair(SourceLocation(), PDiag(0)));
3818}
3819
3820bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
3821 unsigned DiagID) {
3822 return RequireCompleteType(Loc, T, PDiag(DiagID),
3823 std::make_pair(SourceLocation(), PDiag(0)));
3824}
3825
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003826/// \brief Retrieve a version of the type 'T' that is elaborated by Keyword
3827/// and qualified by the nested-name-specifier contained in SS.
3828QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword,
3829 const CXXScopeSpec &SS, QualType T) {
3830 if (T.isNull())
Douglas Gregore6258932009-03-19 00:39:20 +00003831 return T;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003832 NestedNameSpecifier *NNS;
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00003833 if (SS.isValid())
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003834 NNS = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3835 else {
3836 if (Keyword == ETK_None)
3837 return T;
3838 NNS = 0;
3839 }
3840 return Context.getElaboratedType(Keyword, NNS, T);
Douglas Gregore6258932009-03-19 00:39:20 +00003841}
Anders Carlssonaf017e62009-06-29 22:58:55 +00003842
John McCall2a984ca2010-10-12 00:20:44 +00003843QualType Sema::BuildTypeofExprType(Expr *E, SourceLocation Loc) {
John McCallfb8721c2011-04-10 19:13:55 +00003844 ExprResult ER = CheckPlaceholderExpr(E);
John McCall2a984ca2010-10-12 00:20:44 +00003845 if (ER.isInvalid()) return QualType();
3846 E = ER.take();
3847
Fariborz Jahanian2b1d51b2010-10-05 23:24:00 +00003848 if (!E->isTypeDependent()) {
3849 QualType T = E->getType();
Fariborz Jahanianaca7f7b2010-10-06 00:23:25 +00003850 if (const TagType *TT = T->getAs<TagType>())
3851 DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc());
Fariborz Jahanian2b1d51b2010-10-05 23:24:00 +00003852 }
Anders Carlssonaf017e62009-06-29 22:58:55 +00003853 return Context.getTypeOfExprType(E);
3854}
3855
John McCall2a984ca2010-10-12 00:20:44 +00003856QualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc) {
John McCallfb8721c2011-04-10 19:13:55 +00003857 ExprResult ER = CheckPlaceholderExpr(E);
John McCall2a984ca2010-10-12 00:20:44 +00003858 if (ER.isInvalid()) return QualType();
3859 E = ER.take();
Douglas Gregor4b52e252009-12-21 23:17:24 +00003860
Anders Carlssonaf017e62009-06-29 22:58:55 +00003861 return Context.getDecltypeType(E);
3862}
Sean Huntca63c202011-05-24 22:41:36 +00003863
3864QualType Sema::BuildUnaryTransformType(QualType BaseType,
3865 UnaryTransformType::UTTKind UKind,
3866 SourceLocation Loc) {
3867 switch (UKind) {
3868 case UnaryTransformType::EnumUnderlyingType:
3869 if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) {
3870 Diag(Loc, diag::err_only_enums_have_underlying_types);
3871 return QualType();
3872 } else {
3873 QualType Underlying = BaseType;
3874 if (!BaseType->isDependentType()) {
3875 EnumDecl *ED = BaseType->getAs<EnumType>()->getDecl();
3876 assert(ED && "EnumType has no EnumDecl");
3877 DiagnoseUseOfDecl(ED, Loc);
3878 Underlying = ED->getIntegerType();
3879 }
3880 assert(!Underlying.isNull());
3881 return Context.getUnaryTransformType(BaseType, Underlying,
3882 UnaryTransformType::EnumUnderlyingType);
3883 }
3884 }
3885 llvm_unreachable("unknown unary transform type");
3886}