1 //===--- SemaType.cpp - Semantic Analysis for Types -----------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements type-related semantic analysis.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "clang/Sema/SemaInternal.h"
15 #include "TypeLocBuilder.h"
16 #include "clang/AST/ASTConsumer.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/ASTMutationListener.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/Expr.h"
23 #include "clang/AST/TypeLoc.h"
24 #include "clang/AST/TypeLocVisitor.h"
25 #include "clang/Basic/PartialDiagnostic.h"
26 #include "clang/Basic/TargetInfo.h"
27 #include "clang/Parse/ParseDiagnostic.h"
28 #include "clang/Sema/DeclSpec.h"
29 #include "clang/Sema/DelayedDiagnostic.h"
30 #include "clang/Sema/Lookup.h"
31 #include "clang/Sema/ScopeInfo.h"
32 #include "clang/Sema/Template.h"
33 #include "llvm/ADT/SmallPtrSet.h"
34 #include "llvm/ADT/SmallString.h"
35 #include "llvm/Support/ErrorHandling.h"
36
37 using namespace clang;
38
39 enum TypeDiagSelector {
40 TDS_Function,
41 TDS_Pointer,
42 TDS_ObjCObjOrBlock
43 };
44
45 /// isOmittedBlockReturnType - Return true if this declarator is missing a
46 /// return type because this is a omitted return type on a block literal.
isOmittedBlockReturnType(const Declarator & D)47 static bool isOmittedBlockReturnType(const Declarator &D) {
48 if (D.getContext() != Declarator::BlockLiteralContext ||
49 D.getDeclSpec().hasTypeSpecifier())
50 return false;
51
52 if (D.getNumTypeObjects() == 0)
53 return true; // ^{ ... }
54
55 if (D.getNumTypeObjects() == 1 &&
56 D.getTypeObject(0).Kind == DeclaratorChunk::Function)
57 return true; // ^(int X, float Y) { ... }
58
59 return false;
60 }
61
62 /// diagnoseBadTypeAttribute - Diagnoses a type attribute which
63 /// doesn't apply to the given type.
diagnoseBadTypeAttribute(Sema & S,const AttributeList & attr,QualType type)64 static void diagnoseBadTypeAttribute(Sema &S, const AttributeList &attr,
65 QualType type) {
66 TypeDiagSelector WhichType;
67 bool useExpansionLoc = true;
68 switch (attr.getKind()) {
69 case AttributeList::AT_ObjCGC: WhichType = TDS_Pointer; break;
70 case AttributeList::AT_ObjCOwnership: WhichType = TDS_ObjCObjOrBlock; break;
71 default:
72 // Assume everything else was a function attribute.
73 WhichType = TDS_Function;
74 useExpansionLoc = false;
75 break;
76 }
77
78 SourceLocation loc = attr.getLoc();
79 StringRef name = attr.getName()->getName();
80
81 // The GC attributes are usually written with macros; special-case them.
82 IdentifierInfo *II = attr.isArgIdent(0) ? attr.getArgAsIdent(0)->Ident
83 : nullptr;
84 if (useExpansionLoc && loc.isMacroID() && II) {
85 if (II->isStr("strong")) {
86 if (S.findMacroSpelling(loc, "__strong")) name = "__strong";
87 } else if (II->isStr("weak")) {
88 if (S.findMacroSpelling(loc, "__weak")) name = "__weak";
89 }
90 }
91
92 S.Diag(loc, diag::warn_type_attribute_wrong_type) << name << WhichType
93 << type;
94 }
95
96 // objc_gc applies to Objective-C pointers or, otherwise, to the
97 // smallest available pointer type (i.e. 'void*' in 'void**').
98 #define OBJC_POINTER_TYPE_ATTRS_CASELIST \
99 case AttributeList::AT_ObjCGC: \
100 case AttributeList::AT_ObjCOwnership
101
102 // Function type attributes.
103 #define FUNCTION_TYPE_ATTRS_CASELIST \
104 case AttributeList::AT_NoReturn: \
105 case AttributeList::AT_CDecl: \
106 case AttributeList::AT_FastCall: \
107 case AttributeList::AT_StdCall: \
108 case AttributeList::AT_ThisCall: \
109 case AttributeList::AT_Pascal: \
110 case AttributeList::AT_VectorCall: \
111 case AttributeList::AT_MSABI: \
112 case AttributeList::AT_SysVABI: \
113 case AttributeList::AT_Regparm: \
114 case AttributeList::AT_Pcs: \
115 case AttributeList::AT_IntelOclBicc
116
117 // Microsoft-specific type qualifiers.
118 #define MS_TYPE_ATTRS_CASELIST \
119 case AttributeList::AT_Ptr32: \
120 case AttributeList::AT_Ptr64: \
121 case AttributeList::AT_SPtr: \
122 case AttributeList::AT_UPtr
123
124 namespace {
125 /// An object which stores processing state for the entire
126 /// GetTypeForDeclarator process.
127 class TypeProcessingState {
128 Sema &sema;
129
130 /// The declarator being processed.
131 Declarator &declarator;
132
133 /// The index of the declarator chunk we're currently processing.
134 /// May be the total number of valid chunks, indicating the
135 /// DeclSpec.
136 unsigned chunkIndex;
137
138 /// Whether there are non-trivial modifications to the decl spec.
139 bool trivial;
140
141 /// Whether we saved the attributes in the decl spec.
142 bool hasSavedAttrs;
143
144 /// The original set of attributes on the DeclSpec.
145 SmallVector<AttributeList*, 2> savedAttrs;
146
147 /// A list of attributes to diagnose the uselessness of when the
148 /// processing is complete.
149 SmallVector<AttributeList*, 2> ignoredTypeAttrs;
150
151 public:
TypeProcessingState(Sema & sema,Declarator & declarator)152 TypeProcessingState(Sema &sema, Declarator &declarator)
153 : sema(sema), declarator(declarator),
154 chunkIndex(declarator.getNumTypeObjects()),
155 trivial(true), hasSavedAttrs(false) {}
156
getSema() const157 Sema &getSema() const {
158 return sema;
159 }
160
getDeclarator() const161 Declarator &getDeclarator() const {
162 return declarator;
163 }
164
isProcessingDeclSpec() const165 bool isProcessingDeclSpec() const {
166 return chunkIndex == declarator.getNumTypeObjects();
167 }
168
getCurrentChunkIndex() const169 unsigned getCurrentChunkIndex() const {
170 return chunkIndex;
171 }
172
setCurrentChunkIndex(unsigned idx)173 void setCurrentChunkIndex(unsigned idx) {
174 assert(idx <= declarator.getNumTypeObjects());
175 chunkIndex = idx;
176 }
177
getCurrentAttrListRef() const178 AttributeList *&getCurrentAttrListRef() const {
179 if (isProcessingDeclSpec())
180 return getMutableDeclSpec().getAttributes().getListRef();
181 return declarator.getTypeObject(chunkIndex).getAttrListRef();
182 }
183
184 /// Save the current set of attributes on the DeclSpec.
saveDeclSpecAttrs()185 void saveDeclSpecAttrs() {
186 // Don't try to save them multiple times.
187 if (hasSavedAttrs) return;
188
189 DeclSpec &spec = getMutableDeclSpec();
190 for (AttributeList *attr = spec.getAttributes().getList(); attr;
191 attr = attr->getNext())
192 savedAttrs.push_back(attr);
193 trivial &= savedAttrs.empty();
194 hasSavedAttrs = true;
195 }
196
197 /// Record that we had nowhere to put the given type attribute.
198 /// We will diagnose such attributes later.
addIgnoredTypeAttr(AttributeList & attr)199 void addIgnoredTypeAttr(AttributeList &attr) {
200 ignoredTypeAttrs.push_back(&attr);
201 }
202
203 /// Diagnose all the ignored type attributes, given that the
204 /// declarator worked out to the given type.
diagnoseIgnoredTypeAttrs(QualType type) const205 void diagnoseIgnoredTypeAttrs(QualType type) const {
206 for (SmallVectorImpl<AttributeList*>::const_iterator
207 i = ignoredTypeAttrs.begin(), e = ignoredTypeAttrs.end();
208 i != e; ++i)
209 diagnoseBadTypeAttribute(getSema(), **i, type);
210 }
211
~TypeProcessingState()212 ~TypeProcessingState() {
213 if (trivial) return;
214
215 restoreDeclSpecAttrs();
216 }
217
218 private:
getMutableDeclSpec() const219 DeclSpec &getMutableDeclSpec() const {
220 return const_cast<DeclSpec&>(declarator.getDeclSpec());
221 }
222
restoreDeclSpecAttrs()223 void restoreDeclSpecAttrs() {
224 assert(hasSavedAttrs);
225
226 if (savedAttrs.empty()) {
227 getMutableDeclSpec().getAttributes().set(nullptr);
228 return;
229 }
230
231 getMutableDeclSpec().getAttributes().set(savedAttrs[0]);
232 for (unsigned i = 0, e = savedAttrs.size() - 1; i != e; ++i)
233 savedAttrs[i]->setNext(savedAttrs[i+1]);
234 savedAttrs.back()->setNext(nullptr);
235 }
236 };
237 }
238
spliceAttrIntoList(AttributeList & attr,AttributeList * & head)239 static void spliceAttrIntoList(AttributeList &attr, AttributeList *&head) {
240 attr.setNext(head);
241 head = &attr;
242 }
243
spliceAttrOutOfList(AttributeList & attr,AttributeList * & head)244 static void spliceAttrOutOfList(AttributeList &attr, AttributeList *&head) {
245 if (head == &attr) {
246 head = attr.getNext();
247 return;
248 }
249
250 AttributeList *cur = head;
251 while (true) {
252 assert(cur && cur->getNext() && "ran out of attrs?");
253 if (cur->getNext() == &attr) {
254 cur->setNext(attr.getNext());
255 return;
256 }
257 cur = cur->getNext();
258 }
259 }
260
moveAttrFromListToList(AttributeList & attr,AttributeList * & fromList,AttributeList * & toList)261 static void moveAttrFromListToList(AttributeList &attr,
262 AttributeList *&fromList,
263 AttributeList *&toList) {
264 spliceAttrOutOfList(attr, fromList);
265 spliceAttrIntoList(attr, toList);
266 }
267
268 /// The location of a type attribute.
269 enum TypeAttrLocation {
270 /// The attribute is in the decl-specifier-seq.
271 TAL_DeclSpec,
272 /// The attribute is part of a DeclaratorChunk.
273 TAL_DeclChunk,
274 /// The attribute is immediately after the declaration's name.
275 TAL_DeclName
276 };
277
278 static void processTypeAttrs(TypeProcessingState &state,
279 QualType &type, TypeAttrLocation TAL,
280 AttributeList *attrs);
281
282 static bool handleFunctionTypeAttr(TypeProcessingState &state,
283 AttributeList &attr,
284 QualType &type);
285
286 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &state,
287 AttributeList &attr,
288 QualType &type);
289
290 static bool handleObjCGCTypeAttr(TypeProcessingState &state,
291 AttributeList &attr, QualType &type);
292
293 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
294 AttributeList &attr, QualType &type);
295
handleObjCPointerTypeAttr(TypeProcessingState & state,AttributeList & attr,QualType & type)296 static bool handleObjCPointerTypeAttr(TypeProcessingState &state,
297 AttributeList &attr, QualType &type) {
298 if (attr.getKind() == AttributeList::AT_ObjCGC)
299 return handleObjCGCTypeAttr(state, attr, type);
300 assert(attr.getKind() == AttributeList::AT_ObjCOwnership);
301 return handleObjCOwnershipTypeAttr(state, attr, type);
302 }
303
304 /// Given the index of a declarator chunk, check whether that chunk
305 /// directly specifies the return type of a function and, if so, find
306 /// an appropriate place for it.
307 ///
308 /// \param i - a notional index which the search will start
309 /// immediately inside
maybeMovePastReturnType(Declarator & declarator,unsigned i)310 static DeclaratorChunk *maybeMovePastReturnType(Declarator &declarator,
311 unsigned i) {
312 assert(i <= declarator.getNumTypeObjects());
313
314 DeclaratorChunk *result = nullptr;
315
316 // First, look inwards past parens for a function declarator.
317 for (; i != 0; --i) {
318 DeclaratorChunk &fnChunk = declarator.getTypeObject(i-1);
319 switch (fnChunk.Kind) {
320 case DeclaratorChunk::Paren:
321 continue;
322
323 // If we find anything except a function, bail out.
324 case DeclaratorChunk::Pointer:
325 case DeclaratorChunk::BlockPointer:
326 case DeclaratorChunk::Array:
327 case DeclaratorChunk::Reference:
328 case DeclaratorChunk::MemberPointer:
329 return result;
330
331 // If we do find a function declarator, scan inwards from that,
332 // looking for a block-pointer declarator.
333 case DeclaratorChunk::Function:
334 for (--i; i != 0; --i) {
335 DeclaratorChunk &blockChunk = declarator.getTypeObject(i-1);
336 switch (blockChunk.Kind) {
337 case DeclaratorChunk::Paren:
338 case DeclaratorChunk::Pointer:
339 case DeclaratorChunk::Array:
340 case DeclaratorChunk::Function:
341 case DeclaratorChunk::Reference:
342 case DeclaratorChunk::MemberPointer:
343 continue;
344 case DeclaratorChunk::BlockPointer:
345 result = &blockChunk;
346 goto continue_outer;
347 }
348 llvm_unreachable("bad declarator chunk kind");
349 }
350
351 // If we run out of declarators doing that, we're done.
352 return result;
353 }
354 llvm_unreachable("bad declarator chunk kind");
355
356 // Okay, reconsider from our new point.
357 continue_outer: ;
358 }
359
360 // Ran out of chunks, bail out.
361 return result;
362 }
363
364 /// Given that an objc_gc attribute was written somewhere on a
365 /// declaration *other* than on the declarator itself (for which, use
366 /// distributeObjCPointerTypeAttrFromDeclarator), and given that it
367 /// didn't apply in whatever position it was written in, try to move
368 /// it to a more appropriate position.
distributeObjCPointerTypeAttr(TypeProcessingState & state,AttributeList & attr,QualType type)369 static void distributeObjCPointerTypeAttr(TypeProcessingState &state,
370 AttributeList &attr,
371 QualType type) {
372 Declarator &declarator = state.getDeclarator();
373
374 // Move it to the outermost normal or block pointer declarator.
375 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
376 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
377 switch (chunk.Kind) {
378 case DeclaratorChunk::Pointer:
379 case DeclaratorChunk::BlockPointer: {
380 // But don't move an ARC ownership attribute to the return type
381 // of a block.
382 DeclaratorChunk *destChunk = nullptr;
383 if (state.isProcessingDeclSpec() &&
384 attr.getKind() == AttributeList::AT_ObjCOwnership)
385 destChunk = maybeMovePastReturnType(declarator, i - 1);
386 if (!destChunk) destChunk = &chunk;
387
388 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
389 destChunk->getAttrListRef());
390 return;
391 }
392
393 case DeclaratorChunk::Paren:
394 case DeclaratorChunk::Array:
395 continue;
396
397 // We may be starting at the return type of a block.
398 case DeclaratorChunk::Function:
399 if (state.isProcessingDeclSpec() &&
400 attr.getKind() == AttributeList::AT_ObjCOwnership) {
401 if (DeclaratorChunk *dest = maybeMovePastReturnType(declarator, i)) {
402 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
403 dest->getAttrListRef());
404 return;
405 }
406 }
407 goto error;
408
409 // Don't walk through these.
410 case DeclaratorChunk::Reference:
411 case DeclaratorChunk::MemberPointer:
412 goto error;
413 }
414 }
415 error:
416
417 diagnoseBadTypeAttribute(state.getSema(), attr, type);
418 }
419
420 /// Distribute an objc_gc type attribute that was written on the
421 /// declarator.
422 static void
distributeObjCPointerTypeAttrFromDeclarator(TypeProcessingState & state,AttributeList & attr,QualType & declSpecType)423 distributeObjCPointerTypeAttrFromDeclarator(TypeProcessingState &state,
424 AttributeList &attr,
425 QualType &declSpecType) {
426 Declarator &declarator = state.getDeclarator();
427
428 // objc_gc goes on the innermost pointer to something that's not a
429 // pointer.
430 unsigned innermost = -1U;
431 bool considerDeclSpec = true;
432 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
433 DeclaratorChunk &chunk = declarator.getTypeObject(i);
434 switch (chunk.Kind) {
435 case DeclaratorChunk::Pointer:
436 case DeclaratorChunk::BlockPointer:
437 innermost = i;
438 continue;
439
440 case DeclaratorChunk::Reference:
441 case DeclaratorChunk::MemberPointer:
442 case DeclaratorChunk::Paren:
443 case DeclaratorChunk::Array:
444 continue;
445
446 case DeclaratorChunk::Function:
447 considerDeclSpec = false;
448 goto done;
449 }
450 }
451 done:
452
453 // That might actually be the decl spec if we weren't blocked by
454 // anything in the declarator.
455 if (considerDeclSpec) {
456 if (handleObjCPointerTypeAttr(state, attr, declSpecType)) {
457 // Splice the attribute into the decl spec. Prevents the
458 // attribute from being applied multiple times and gives
459 // the source-location-filler something to work with.
460 state.saveDeclSpecAttrs();
461 moveAttrFromListToList(attr, declarator.getAttrListRef(),
462 declarator.getMutableDeclSpec().getAttributes().getListRef());
463 return;
464 }
465 }
466
467 // Otherwise, if we found an appropriate chunk, splice the attribute
468 // into it.
469 if (innermost != -1U) {
470 moveAttrFromListToList(attr, declarator.getAttrListRef(),
471 declarator.getTypeObject(innermost).getAttrListRef());
472 return;
473 }
474
475 // Otherwise, diagnose when we're done building the type.
476 spliceAttrOutOfList(attr, declarator.getAttrListRef());
477 state.addIgnoredTypeAttr(attr);
478 }
479
480 /// A function type attribute was written somewhere in a declaration
481 /// *other* than on the declarator itself or in the decl spec. Given
482 /// that it didn't apply in whatever position it was written in, try
483 /// to move it to a more appropriate position.
distributeFunctionTypeAttr(TypeProcessingState & state,AttributeList & attr,QualType type)484 static void distributeFunctionTypeAttr(TypeProcessingState &state,
485 AttributeList &attr,
486 QualType type) {
487 Declarator &declarator = state.getDeclarator();
488
489 // Try to push the attribute from the return type of a function to
490 // the function itself.
491 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
492 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
493 switch (chunk.Kind) {
494 case DeclaratorChunk::Function:
495 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
496 chunk.getAttrListRef());
497 return;
498
499 case DeclaratorChunk::Paren:
500 case DeclaratorChunk::Pointer:
501 case DeclaratorChunk::BlockPointer:
502 case DeclaratorChunk::Array:
503 case DeclaratorChunk::Reference:
504 case DeclaratorChunk::MemberPointer:
505 continue;
506 }
507 }
508
509 diagnoseBadTypeAttribute(state.getSema(), attr, type);
510 }
511
512 /// Try to distribute a function type attribute to the innermost
513 /// function chunk or type. Returns true if the attribute was
514 /// distributed, false if no location was found.
515 static bool
distributeFunctionTypeAttrToInnermost(TypeProcessingState & state,AttributeList & attr,AttributeList * & attrList,QualType & declSpecType)516 distributeFunctionTypeAttrToInnermost(TypeProcessingState &state,
517 AttributeList &attr,
518 AttributeList *&attrList,
519 QualType &declSpecType) {
520 Declarator &declarator = state.getDeclarator();
521
522 // Put it on the innermost function chunk, if there is one.
523 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
524 DeclaratorChunk &chunk = declarator.getTypeObject(i);
525 if (chunk.Kind != DeclaratorChunk::Function) continue;
526
527 moveAttrFromListToList(attr, attrList, chunk.getAttrListRef());
528 return true;
529 }
530
531 return handleFunctionTypeAttr(state, attr, declSpecType);
532 }
533
534 /// A function type attribute was written in the decl spec. Try to
535 /// apply it somewhere.
536 static void
distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState & state,AttributeList & attr,QualType & declSpecType)537 distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state,
538 AttributeList &attr,
539 QualType &declSpecType) {
540 state.saveDeclSpecAttrs();
541
542 // C++11 attributes before the decl specifiers actually appertain to
543 // the declarators. Move them straight there. We don't support the
544 // 'put them wherever you like' semantics we allow for GNU attributes.
545 if (attr.isCXX11Attribute()) {
546 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
547 state.getDeclarator().getAttrListRef());
548 return;
549 }
550
551 // Try to distribute to the innermost.
552 if (distributeFunctionTypeAttrToInnermost(state, attr,
553 state.getCurrentAttrListRef(),
554 declSpecType))
555 return;
556
557 // If that failed, diagnose the bad attribute when the declarator is
558 // fully built.
559 state.addIgnoredTypeAttr(attr);
560 }
561
562 /// A function type attribute was written on the declarator. Try to
563 /// apply it somewhere.
564 static void
distributeFunctionTypeAttrFromDeclarator(TypeProcessingState & state,AttributeList & attr,QualType & declSpecType)565 distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state,
566 AttributeList &attr,
567 QualType &declSpecType) {
568 Declarator &declarator = state.getDeclarator();
569
570 // Try to distribute to the innermost.
571 if (distributeFunctionTypeAttrToInnermost(state, attr,
572 declarator.getAttrListRef(),
573 declSpecType))
574 return;
575
576 // If that failed, diagnose the bad attribute when the declarator is
577 // fully built.
578 spliceAttrOutOfList(attr, declarator.getAttrListRef());
579 state.addIgnoredTypeAttr(attr);
580 }
581
582 /// \brief Given that there are attributes written on the declarator
583 /// itself, try to distribute any type attributes to the appropriate
584 /// declarator chunk.
585 ///
586 /// These are attributes like the following:
587 /// int f ATTR;
588 /// int (f ATTR)();
589 /// but not necessarily this:
590 /// int f() ATTR;
distributeTypeAttrsFromDeclarator(TypeProcessingState & state,QualType & declSpecType)591 static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state,
592 QualType &declSpecType) {
593 // Collect all the type attributes from the declarator itself.
594 assert(state.getDeclarator().getAttributes() && "declarator has no attrs!");
595 AttributeList *attr = state.getDeclarator().getAttributes();
596 AttributeList *next;
597 do {
598 next = attr->getNext();
599
600 // Do not distribute C++11 attributes. They have strict rules for what
601 // they appertain to.
602 if (attr->isCXX11Attribute())
603 continue;
604
605 switch (attr->getKind()) {
606 OBJC_POINTER_TYPE_ATTRS_CASELIST:
607 distributeObjCPointerTypeAttrFromDeclarator(state, *attr, declSpecType);
608 break;
609
610 case AttributeList::AT_NSReturnsRetained:
611 if (!state.getSema().getLangOpts().ObjCAutoRefCount)
612 break;
613 // fallthrough
614
615 FUNCTION_TYPE_ATTRS_CASELIST:
616 distributeFunctionTypeAttrFromDeclarator(state, *attr, declSpecType);
617 break;
618
619 MS_TYPE_ATTRS_CASELIST:
620 // Microsoft type attributes cannot go after the declarator-id.
621 continue;
622
623 default:
624 break;
625 }
626 } while ((attr = next));
627 }
628
629 /// Add a synthetic '()' to a block-literal declarator if it is
630 /// required, given the return type.
maybeSynthesizeBlockSignature(TypeProcessingState & state,QualType declSpecType)631 static void maybeSynthesizeBlockSignature(TypeProcessingState &state,
632 QualType declSpecType) {
633 Declarator &declarator = state.getDeclarator();
634
635 // First, check whether the declarator would produce a function,
636 // i.e. whether the innermost semantic chunk is a function.
637 if (declarator.isFunctionDeclarator()) {
638 // If so, make that declarator a prototyped declarator.
639 declarator.getFunctionTypeInfo().hasPrototype = true;
640 return;
641 }
642
643 // If there are any type objects, the type as written won't name a
644 // function, regardless of the decl spec type. This is because a
645 // block signature declarator is always an abstract-declarator, and
646 // abstract-declarators can't just be parentheses chunks. Therefore
647 // we need to build a function chunk unless there are no type
648 // objects and the decl spec type is a function.
649 if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType())
650 return;
651
652 // Note that there *are* cases with invalid declarators where
653 // declarators consist solely of parentheses. In general, these
654 // occur only in failed efforts to make function declarators, so
655 // faking up the function chunk is still the right thing to do.
656
657 // Otherwise, we need to fake up a function declarator.
658 SourceLocation loc = declarator.getLocStart();
659
660 // ...and *prepend* it to the declarator.
661 SourceLocation NoLoc;
662 declarator.AddInnermostTypeInfo(DeclaratorChunk::getFunction(
663 /*HasProto=*/true,
664 /*IsAmbiguous=*/false,
665 /*LParenLoc=*/NoLoc,
666 /*ArgInfo=*/nullptr,
667 /*NumArgs=*/0,
668 /*EllipsisLoc=*/NoLoc,
669 /*RParenLoc=*/NoLoc,
670 /*TypeQuals=*/0,
671 /*RefQualifierIsLvalueRef=*/true,
672 /*RefQualifierLoc=*/NoLoc,
673 /*ConstQualifierLoc=*/NoLoc,
674 /*VolatileQualifierLoc=*/NoLoc,
675 /*RestrictQualifierLoc=*/NoLoc,
676 /*MutableLoc=*/NoLoc, EST_None,
677 /*ESpecLoc=*/NoLoc,
678 /*Exceptions=*/nullptr,
679 /*ExceptionRanges=*/nullptr,
680 /*NumExceptions=*/0,
681 /*NoexceptExpr=*/nullptr,
682 /*ExceptionSpecTokens=*/nullptr,
683 loc, loc, declarator));
684
685 // For consistency, make sure the state still has us as processing
686 // the decl spec.
687 assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1);
688 state.setCurrentChunkIndex(declarator.getNumTypeObjects());
689 }
690
691 /// \brief Convert the specified declspec to the appropriate type
692 /// object.
693 /// \param state Specifies the declarator containing the declaration specifier
694 /// to be converted, along with other associated processing state.
695 /// \returns The type described by the declaration specifiers. This function
696 /// never returns null.
ConvertDeclSpecToType(TypeProcessingState & state)697 static QualType ConvertDeclSpecToType(TypeProcessingState &state) {
698 // FIXME: Should move the logic from DeclSpec::Finish to here for validity
699 // checking.
700
701 Sema &S = state.getSema();
702 Declarator &declarator = state.getDeclarator();
703 const DeclSpec &DS = declarator.getDeclSpec();
704 SourceLocation DeclLoc = declarator.getIdentifierLoc();
705 if (DeclLoc.isInvalid())
706 DeclLoc = DS.getLocStart();
707
708 ASTContext &Context = S.Context;
709
710 QualType Result;
711 switch (DS.getTypeSpecType()) {
712 case DeclSpec::TST_void:
713 Result = Context.VoidTy;
714 break;
715 case DeclSpec::TST_char:
716 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
717 Result = Context.CharTy;
718 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed)
719 Result = Context.SignedCharTy;
720 else {
721 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
722 "Unknown TSS value");
723 Result = Context.UnsignedCharTy;
724 }
725 break;
726 case DeclSpec::TST_wchar:
727 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
728 Result = Context.WCharTy;
729 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) {
730 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
731 << DS.getSpecifierName(DS.getTypeSpecType(),
732 Context.getPrintingPolicy());
733 Result = Context.getSignedWCharType();
734 } else {
735 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
736 "Unknown TSS value");
737 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
738 << DS.getSpecifierName(DS.getTypeSpecType(),
739 Context.getPrintingPolicy());
740 Result = Context.getUnsignedWCharType();
741 }
742 break;
743 case DeclSpec::TST_char16:
744 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
745 "Unknown TSS value");
746 Result = Context.Char16Ty;
747 break;
748 case DeclSpec::TST_char32:
749 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
750 "Unknown TSS value");
751 Result = Context.Char32Ty;
752 break;
753 case DeclSpec::TST_unspecified:
754 // "<proto1,proto2>" is an objc qualified ID with a missing id.
755 if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) {
756 Result = Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
757 (ObjCProtocolDecl*const*)PQ,
758 DS.getNumProtocolQualifiers());
759 Result = Context.getObjCObjectPointerType(Result);
760 break;
761 }
762
763 // If this is a missing declspec in a block literal return context, then it
764 // is inferred from the return statements inside the block.
765 // The declspec is always missing in a lambda expr context; it is either
766 // specified with a trailing return type or inferred.
767 if (S.getLangOpts().CPlusPlus14 &&
768 declarator.getContext() == Declarator::LambdaExprContext) {
769 // In C++1y, a lambda's implicit return type is 'auto'.
770 Result = Context.getAutoDeductType();
771 break;
772 } else if (declarator.getContext() == Declarator::LambdaExprContext ||
773 isOmittedBlockReturnType(declarator)) {
774 Result = Context.DependentTy;
775 break;
776 }
777
778 // Unspecified typespec defaults to int in C90. However, the C90 grammar
779 // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
780 // type-qualifier, or storage-class-specifier. If not, emit an extwarn.
781 // Note that the one exception to this is function definitions, which are
782 // allowed to be completely missing a declspec. This is handled in the
783 // parser already though by it pretending to have seen an 'int' in this
784 // case.
785 if (S.getLangOpts().ImplicitInt) {
786 // In C89 mode, we only warn if there is a completely missing declspec
787 // when one is not allowed.
788 if (DS.isEmpty()) {
789 S.Diag(DeclLoc, diag::ext_missing_declspec)
790 << DS.getSourceRange()
791 << FixItHint::CreateInsertion(DS.getLocStart(), "int");
792 }
793 } else if (!DS.hasTypeSpecifier()) {
794 // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says:
795 // "At least one type specifier shall be given in the declaration
796 // specifiers in each declaration, and in the specifier-qualifier list in
797 // each struct declaration and type name."
798 if (S.getLangOpts().CPlusPlus) {
799 S.Diag(DeclLoc, diag::err_missing_type_specifier)
800 << DS.getSourceRange();
801
802 // When this occurs in C++ code, often something is very broken with the
803 // value being declared, poison it as invalid so we don't get chains of
804 // errors.
805 declarator.setInvalidType(true);
806 } else {
807 S.Diag(DeclLoc, diag::ext_missing_type_specifier)
808 << DS.getSourceRange();
809 }
810 }
811
812 // FALL THROUGH.
813 case DeclSpec::TST_int: {
814 if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) {
815 switch (DS.getTypeSpecWidth()) {
816 case DeclSpec::TSW_unspecified: Result = Context.IntTy; break;
817 case DeclSpec::TSW_short: Result = Context.ShortTy; break;
818 case DeclSpec::TSW_long: Result = Context.LongTy; break;
819 case DeclSpec::TSW_longlong:
820 Result = Context.LongLongTy;
821
822 // 'long long' is a C99 or C++11 feature.
823 if (!S.getLangOpts().C99) {
824 if (S.getLangOpts().CPlusPlus)
825 S.Diag(DS.getTypeSpecWidthLoc(),
826 S.getLangOpts().CPlusPlus11 ?
827 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
828 else
829 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
830 }
831 break;
832 }
833 } else {
834 switch (DS.getTypeSpecWidth()) {
835 case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break;
836 case DeclSpec::TSW_short: Result = Context.UnsignedShortTy; break;
837 case DeclSpec::TSW_long: Result = Context.UnsignedLongTy; break;
838 case DeclSpec::TSW_longlong:
839 Result = Context.UnsignedLongLongTy;
840
841 // 'long long' is a C99 or C++11 feature.
842 if (!S.getLangOpts().C99) {
843 if (S.getLangOpts().CPlusPlus)
844 S.Diag(DS.getTypeSpecWidthLoc(),
845 S.getLangOpts().CPlusPlus11 ?
846 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
847 else
848 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
849 }
850 break;
851 }
852 }
853 break;
854 }
855 case DeclSpec::TST_int128:
856 if (!S.Context.getTargetInfo().hasInt128Type())
857 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_int128_unsupported);
858 if (DS.getTypeSpecSign() == DeclSpec::TSS_unsigned)
859 Result = Context.UnsignedInt128Ty;
860 else
861 Result = Context.Int128Ty;
862 break;
863 case DeclSpec::TST_half: Result = Context.HalfTy; break;
864 case DeclSpec::TST_float: Result = Context.FloatTy; break;
865 case DeclSpec::TST_double:
866 if (DS.getTypeSpecWidth() == DeclSpec::TSW_long)
867 Result = Context.LongDoubleTy;
868 else
869 Result = Context.DoubleTy;
870
871 if (S.getLangOpts().OpenCL &&
872 !((S.getLangOpts().OpenCLVersion >= 120) ||
873 S.getOpenCLOptions().cl_khr_fp64)) {
874 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_requires_extension)
875 << Result << "cl_khr_fp64";
876 declarator.setInvalidType(true);
877 }
878 break;
879 case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool
880 case DeclSpec::TST_decimal32: // _Decimal32
881 case DeclSpec::TST_decimal64: // _Decimal64
882 case DeclSpec::TST_decimal128: // _Decimal128
883 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
884 Result = Context.IntTy;
885 declarator.setInvalidType(true);
886 break;
887 case DeclSpec::TST_class:
888 case DeclSpec::TST_enum:
889 case DeclSpec::TST_union:
890 case DeclSpec::TST_struct:
891 case DeclSpec::TST_interface: {
892 TypeDecl *D = dyn_cast_or_null<TypeDecl>(DS.getRepAsDecl());
893 if (!D) {
894 // This can happen in C++ with ambiguous lookups.
895 Result = Context.IntTy;
896 declarator.setInvalidType(true);
897 break;
898 }
899
900 // If the type is deprecated or unavailable, diagnose it.
901 S.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeNameLoc());
902
903 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
904 DS.getTypeSpecSign() == 0 && "No qualifiers on tag names!");
905
906 // TypeQuals handled by caller.
907 Result = Context.getTypeDeclType(D);
908
909 // In both C and C++, make an ElaboratedType.
910 ElaboratedTypeKeyword Keyword
911 = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType());
912 Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result);
913 break;
914 }
915 case DeclSpec::TST_typename: {
916 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
917 DS.getTypeSpecSign() == 0 &&
918 "Can't handle qualifiers on typedef names yet!");
919 Result = S.GetTypeFromParser(DS.getRepAsType());
920 if (Result.isNull())
921 declarator.setInvalidType(true);
922 else if (DeclSpec::ProtocolQualifierListTy PQ
923 = DS.getProtocolQualifiers()) {
924 if (const ObjCObjectType *ObjT = Result->getAs<ObjCObjectType>()) {
925 // Silently drop any existing protocol qualifiers.
926 // TODO: determine whether that's the right thing to do.
927 if (ObjT->getNumProtocols())
928 Result = ObjT->getBaseType();
929
930 if (DS.getNumProtocolQualifiers())
931 Result = Context.getObjCObjectType(Result,
932 (ObjCProtocolDecl*const*) PQ,
933 DS.getNumProtocolQualifiers());
934 } else if (Result->isObjCIdType()) {
935 // id<protocol-list>
936 Result = Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
937 (ObjCProtocolDecl*const*) PQ,
938 DS.getNumProtocolQualifiers());
939 Result = Context.getObjCObjectPointerType(Result);
940 } else if (Result->isObjCClassType()) {
941 // Class<protocol-list>
942 Result = Context.getObjCObjectType(Context.ObjCBuiltinClassTy,
943 (ObjCProtocolDecl*const*) PQ,
944 DS.getNumProtocolQualifiers());
945 Result = Context.getObjCObjectPointerType(Result);
946 } else {
947 S.Diag(DeclLoc, diag::err_invalid_protocol_qualifiers)
948 << DS.getSourceRange();
949 declarator.setInvalidType(true);
950 }
951 } else if (S.getLangOpts().OpenCL) {
952 if (const AtomicType *AT = Result->getAs<AtomicType>()) {
953 const BuiltinType *BT = AT->getValueType()->getAs<BuiltinType>();
954 bool NoExtTypes = BT && (BT->getKind() == BuiltinType::Int ||
955 BT->getKind() == BuiltinType::UInt ||
956 BT->getKind() == BuiltinType::Float);
957 if (!S.getOpenCLOptions().cl_khr_int64_base_atomics && !NoExtTypes) {
958 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_requires_extension)
959 << Result << "cl_khr_int64_base_atomics";
960 declarator.setInvalidType(true);
961 }
962 if (!S.getOpenCLOptions().cl_khr_int64_extended_atomics &&
963 !NoExtTypes) {
964 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_requires_extension)
965 << Result << "cl_khr_int64_extended_atomics";
966 declarator.setInvalidType(true);
967 }
968 if (!S.getOpenCLOptions().cl_khr_fp64 && BT &&
969 BT->getKind() == BuiltinType::Double) {
970 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_requires_extension)
971 << Result << "cl_khr_fp64";
972 declarator.setInvalidType(true);
973 }
974 }
975 }
976
977 // TypeQuals handled by caller.
978 break;
979 }
980 case DeclSpec::TST_typeofType:
981 // FIXME: Preserve type source info.
982 Result = S.GetTypeFromParser(DS.getRepAsType());
983 assert(!Result.isNull() && "Didn't get a type for typeof?");
984 if (!Result->isDependentType())
985 if (const TagType *TT = Result->getAs<TagType>())
986 S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc());
987 // TypeQuals handled by caller.
988 Result = Context.getTypeOfType(Result);
989 break;
990 case DeclSpec::TST_typeofExpr: {
991 Expr *E = DS.getRepAsExpr();
992 assert(E && "Didn't get an expression for typeof?");
993 // TypeQuals handled by caller.
994 Result = S.BuildTypeofExprType(E, DS.getTypeSpecTypeLoc());
995 if (Result.isNull()) {
996 Result = Context.IntTy;
997 declarator.setInvalidType(true);
998 }
999 break;
1000 }
1001 case DeclSpec::TST_decltype: {
1002 Expr *E = DS.getRepAsExpr();
1003 assert(E && "Didn't get an expression for decltype?");
1004 // TypeQuals handled by caller.
1005 Result = S.BuildDecltypeType(E, DS.getTypeSpecTypeLoc());
1006 if (Result.isNull()) {
1007 Result = Context.IntTy;
1008 declarator.setInvalidType(true);
1009 }
1010 break;
1011 }
1012 case DeclSpec::TST_underlyingType:
1013 Result = S.GetTypeFromParser(DS.getRepAsType());
1014 assert(!Result.isNull() && "Didn't get a type for __underlying_type?");
1015 Result = S.BuildUnaryTransformType(Result,
1016 UnaryTransformType::EnumUnderlyingType,
1017 DS.getTypeSpecTypeLoc());
1018 if (Result.isNull()) {
1019 Result = Context.IntTy;
1020 declarator.setInvalidType(true);
1021 }
1022 break;
1023
1024 case DeclSpec::TST_auto:
1025 // TypeQuals handled by caller.
1026 // If auto is mentioned in a lambda parameter context, convert it to a
1027 // template parameter type immediately, with the appropriate depth and
1028 // index, and update sema's state (LambdaScopeInfo) for the current lambda
1029 // being analyzed (which tracks the invented type template parameter).
1030 if (declarator.getContext() == Declarator::LambdaExprParameterContext) {
1031 sema::LambdaScopeInfo *LSI = S.getCurLambda();
1032 assert(LSI && "No LambdaScopeInfo on the stack!");
1033 const unsigned TemplateParameterDepth = LSI->AutoTemplateParameterDepth;
1034 const unsigned AutoParameterPosition = LSI->AutoTemplateParams.size();
1035 const bool IsParameterPack = declarator.hasEllipsis();
1036
1037 // Turns out we must create the TemplateTypeParmDecl here to
1038 // retrieve the corresponding template parameter type.
1039 TemplateTypeParmDecl *CorrespondingTemplateParam =
1040 TemplateTypeParmDecl::Create(Context,
1041 // Temporarily add to the TranslationUnit DeclContext. When the
1042 // associated TemplateParameterList is attached to a template
1043 // declaration (such as FunctionTemplateDecl), the DeclContext
1044 // for each template parameter gets updated appropriately via
1045 // a call to AdoptTemplateParameterList.
1046 Context.getTranslationUnitDecl(),
1047 /*KeyLoc*/ SourceLocation(),
1048 /*NameLoc*/ declarator.getLocStart(),
1049 TemplateParameterDepth,
1050 AutoParameterPosition, // our template param index
1051 /* Identifier*/ nullptr, false, IsParameterPack);
1052 LSI->AutoTemplateParams.push_back(CorrespondingTemplateParam);
1053 // Replace the 'auto' in the function parameter with this invented
1054 // template type parameter.
1055 Result = QualType(CorrespondingTemplateParam->getTypeForDecl(), 0);
1056 } else {
1057 Result = Context.getAutoType(QualType(), /*decltype(auto)*/false, false);
1058 }
1059 break;
1060
1061 case DeclSpec::TST_decltype_auto:
1062 Result = Context.getAutoType(QualType(),
1063 /*decltype(auto)*/true,
1064 /*IsDependent*/ false);
1065 break;
1066
1067 case DeclSpec::TST_unknown_anytype:
1068 Result = Context.UnknownAnyTy;
1069 break;
1070
1071 case DeclSpec::TST_atomic:
1072 Result = S.GetTypeFromParser(DS.getRepAsType());
1073 assert(!Result.isNull() && "Didn't get a type for _Atomic?");
1074 Result = S.BuildAtomicType(Result, DS.getTypeSpecTypeLoc());
1075 if (Result.isNull()) {
1076 Result = Context.IntTy;
1077 declarator.setInvalidType(true);
1078 }
1079 break;
1080
1081 case DeclSpec::TST_error:
1082 Result = Context.IntTy;
1083 declarator.setInvalidType(true);
1084 break;
1085 }
1086
1087 // Handle complex types.
1088 if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
1089 if (S.getLangOpts().Freestanding)
1090 S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
1091 Result = Context.getComplexType(Result);
1092 } else if (DS.isTypeAltiVecVector()) {
1093 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result));
1094 assert(typeSize > 0 && "type size for vector must be greater than 0 bits");
1095 VectorType::VectorKind VecKind = VectorType::AltiVecVector;
1096 if (DS.isTypeAltiVecPixel())
1097 VecKind = VectorType::AltiVecPixel;
1098 else if (DS.isTypeAltiVecBool())
1099 VecKind = VectorType::AltiVecBool;
1100 Result = Context.getVectorType(Result, 128/typeSize, VecKind);
1101 }
1102
1103 // FIXME: Imaginary.
1104 if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary)
1105 S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported);
1106
1107 // Before we process any type attributes, synthesize a block literal
1108 // function declarator if necessary.
1109 if (declarator.getContext() == Declarator::BlockLiteralContext)
1110 maybeSynthesizeBlockSignature(state, Result);
1111
1112 // Apply any type attributes from the decl spec. This may cause the
1113 // list of type attributes to be temporarily saved while the type
1114 // attributes are pushed around.
1115 if (AttributeList *attrs = DS.getAttributes().getList())
1116 processTypeAttrs(state, Result, TAL_DeclSpec, attrs);
1117
1118 // Apply const/volatile/restrict qualifiers to T.
1119 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
1120
1121 // Warn about CV qualifiers on functions: C99 6.7.3p8: "If the specification
1122 // of a function type includes any type qualifiers, the behavior is
1123 // undefined."
1124 if (Result->isFunctionType() && TypeQuals) {
1125 if (TypeQuals & DeclSpec::TQ_const)
1126 S.Diag(DS.getConstSpecLoc(), diag::warn_typecheck_function_qualifiers)
1127 << Result << DS.getSourceRange();
1128 else if (TypeQuals & DeclSpec::TQ_volatile)
1129 S.Diag(DS.getVolatileSpecLoc(),
1130 diag::warn_typecheck_function_qualifiers)
1131 << Result << DS.getSourceRange();
1132 else {
1133 assert((TypeQuals & (DeclSpec::TQ_restrict | DeclSpec::TQ_atomic)) &&
1134 "Has CVRA quals but not C, V, R, or A?");
1135 // No diagnostic; we'll diagnose 'restrict' or '_Atomic' applied to a
1136 // function type later, in BuildQualifiedType.
1137 }
1138 }
1139
1140 // C++11 [dcl.ref]p1:
1141 // Cv-qualified references are ill-formed except when the
1142 // cv-qualifiers are introduced through the use of a typedef-name
1143 // or decltype-specifier, in which case the cv-qualifiers are ignored.
1144 //
1145 // There don't appear to be any other contexts in which a cv-qualified
1146 // reference type could be formed, so the 'ill-formed' clause here appears
1147 // to never happen.
1148 if (DS.getTypeSpecType() == DeclSpec::TST_typename &&
1149 TypeQuals && Result->isReferenceType()) {
1150 // If this occurs outside a template instantiation, warn the user about
1151 // it; they probably didn't mean to specify a redundant qualifier.
1152 typedef std::pair<DeclSpec::TQ, SourceLocation> QualLoc;
1153 QualLoc Quals[] = {
1154 QualLoc(DeclSpec::TQ_const, DS.getConstSpecLoc()),
1155 QualLoc(DeclSpec::TQ_volatile, DS.getVolatileSpecLoc()),
1156 QualLoc(DeclSpec::TQ_atomic, DS.getAtomicSpecLoc())
1157 };
1158 for (unsigned I = 0, N = llvm::array_lengthof(Quals); I != N; ++I) {
1159 if (S.ActiveTemplateInstantiations.empty()) {
1160 if (TypeQuals & Quals[I].first)
1161 S.Diag(Quals[I].second, diag::warn_typecheck_reference_qualifiers)
1162 << DeclSpec::getSpecifierName(Quals[I].first) << Result
1163 << FixItHint::CreateRemoval(Quals[I].second);
1164 }
1165 TypeQuals &= ~Quals[I].first;
1166 }
1167 }
1168
1169 // C90 6.5.3 constraints: "The same type qualifier shall not appear more
1170 // than once in the same specifier-list or qualifier-list, either directly
1171 // or via one or more typedefs."
1172 if (!S.getLangOpts().C99 && !S.getLangOpts().CPlusPlus
1173 && TypeQuals & Result.getCVRQualifiers()) {
1174 if (TypeQuals & DeclSpec::TQ_const && Result.isConstQualified()) {
1175 S.Diag(DS.getConstSpecLoc(), diag::ext_duplicate_declspec)
1176 << "const";
1177 }
1178
1179 if (TypeQuals & DeclSpec::TQ_volatile && Result.isVolatileQualified()) {
1180 S.Diag(DS.getVolatileSpecLoc(), diag::ext_duplicate_declspec)
1181 << "volatile";
1182 }
1183
1184 // C90 doesn't have restrict nor _Atomic, so it doesn't force us to
1185 // produce a warning in this case.
1186 }
1187
1188 QualType Qualified = S.BuildQualifiedType(Result, DeclLoc, TypeQuals, &DS);
1189
1190 // If adding qualifiers fails, just use the unqualified type.
1191 if (Qualified.isNull())
1192 declarator.setInvalidType(true);
1193 else
1194 Result = Qualified;
1195 }
1196
1197 assert(!Result.isNull() && "This function should not return a null type");
1198 return Result;
1199 }
1200
getPrintableNameForEntity(DeclarationName Entity)1201 static std::string getPrintableNameForEntity(DeclarationName Entity) {
1202 if (Entity)
1203 return Entity.getAsString();
1204
1205 return "type name";
1206 }
1207
BuildQualifiedType(QualType T,SourceLocation Loc,Qualifiers Qs,const DeclSpec * DS)1208 QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1209 Qualifiers Qs, const DeclSpec *DS) {
1210 if (T.isNull())
1211 return QualType();
1212
1213 // Enforce C99 6.7.3p2: "Types other than pointer types derived from
1214 // object or incomplete types shall not be restrict-qualified."
1215 if (Qs.hasRestrict()) {
1216 unsigned DiagID = 0;
1217 QualType ProblemTy;
1218
1219 if (T->isAnyPointerType() || T->isReferenceType() ||
1220 T->isMemberPointerType()) {
1221 QualType EltTy;
1222 if (T->isObjCObjectPointerType())
1223 EltTy = T;
1224 else if (const MemberPointerType *PTy = T->getAs<MemberPointerType>())
1225 EltTy = PTy->getPointeeType();
1226 else
1227 EltTy = T->getPointeeType();
1228
1229 // If we have a pointer or reference, the pointee must have an object
1230 // incomplete type.
1231 if (!EltTy->isIncompleteOrObjectType()) {
1232 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1233 ProblemTy = EltTy;
1234 }
1235 } else if (!T->isDependentType()) {
1236 DiagID = diag::err_typecheck_invalid_restrict_not_pointer;
1237 ProblemTy = T;
1238 }
1239
1240 if (DiagID) {
1241 Diag(DS ? DS->getRestrictSpecLoc() : Loc, DiagID) << ProblemTy;
1242 Qs.removeRestrict();
1243 }
1244 }
1245
1246 return Context.getQualifiedType(T, Qs);
1247 }
1248
BuildQualifiedType(QualType T,SourceLocation Loc,unsigned CVRA,const DeclSpec * DS)1249 QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1250 unsigned CVRA, const DeclSpec *DS) {
1251 if (T.isNull())
1252 return QualType();
1253
1254 // Convert from DeclSpec::TQ to Qualifiers::TQ by just dropping TQ_atomic.
1255 unsigned CVR = CVRA & ~DeclSpec::TQ_atomic;
1256
1257 // C11 6.7.3/5:
1258 // If the same qualifier appears more than once in the same
1259 // specifier-qualifier-list, either directly or via one or more typedefs,
1260 // the behavior is the same as if it appeared only once.
1261 //
1262 // It's not specified what happens when the _Atomic qualifier is applied to
1263 // a type specified with the _Atomic specifier, but we assume that this
1264 // should be treated as if the _Atomic qualifier appeared multiple times.
1265 if (CVRA & DeclSpec::TQ_atomic && !T->isAtomicType()) {
1266 // C11 6.7.3/5:
1267 // If other qualifiers appear along with the _Atomic qualifier in a
1268 // specifier-qualifier-list, the resulting type is the so-qualified
1269 // atomic type.
1270 //
1271 // Don't need to worry about array types here, since _Atomic can't be
1272 // applied to such types.
1273 SplitQualType Split = T.getSplitUnqualifiedType();
1274 T = BuildAtomicType(QualType(Split.Ty, 0),
1275 DS ? DS->getAtomicSpecLoc() : Loc);
1276 if (T.isNull())
1277 return T;
1278 Split.Quals.addCVRQualifiers(CVR);
1279 return BuildQualifiedType(T, Loc, Split.Quals);
1280 }
1281
1282 return BuildQualifiedType(T, Loc, Qualifiers::fromCVRMask(CVR), DS);
1283 }
1284
1285 /// \brief Build a paren type including \p T.
BuildParenType(QualType T)1286 QualType Sema::BuildParenType(QualType T) {
1287 return Context.getParenType(T);
1288 }
1289
1290 /// Given that we're building a pointer or reference to the given
inferARCLifetimeForPointee(Sema & S,QualType type,SourceLocation loc,bool isReference)1291 static QualType inferARCLifetimeForPointee(Sema &S, QualType type,
1292 SourceLocation loc,
1293 bool isReference) {
1294 // Bail out if retention is unrequired or already specified.
1295 if (!type->isObjCLifetimeType() ||
1296 type.getObjCLifetime() != Qualifiers::OCL_None)
1297 return type;
1298
1299 Qualifiers::ObjCLifetime implicitLifetime = Qualifiers::OCL_None;
1300
1301 // If the object type is const-qualified, we can safely use
1302 // __unsafe_unretained. This is safe (because there are no read
1303 // barriers), and it'll be safe to coerce anything but __weak* to
1304 // the resulting type.
1305 if (type.isConstQualified()) {
1306 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1307
1308 // Otherwise, check whether the static type does not require
1309 // retaining. This currently only triggers for Class (possibly
1310 // protocol-qualifed, and arrays thereof).
1311 } else if (type->isObjCARCImplicitlyUnretainedType()) {
1312 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1313
1314 // If we are in an unevaluated context, like sizeof, skip adding a
1315 // qualification.
1316 } else if (S.isUnevaluatedContext()) {
1317 return type;
1318
1319 // If that failed, give an error and recover using __strong. __strong
1320 // is the option most likely to prevent spurious second-order diagnostics,
1321 // like when binding a reference to a field.
1322 } else {
1323 // These types can show up in private ivars in system headers, so
1324 // we need this to not be an error in those cases. Instead we
1325 // want to delay.
1326 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
1327 S.DelayedDiagnostics.add(
1328 sema::DelayedDiagnostic::makeForbiddenType(loc,
1329 diag::err_arc_indirect_no_ownership, type, isReference));
1330 } else {
1331 S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference;
1332 }
1333 implicitLifetime = Qualifiers::OCL_Strong;
1334 }
1335 assert(implicitLifetime && "didn't infer any lifetime!");
1336
1337 Qualifiers qs;
1338 qs.addObjCLifetime(implicitLifetime);
1339 return S.Context.getQualifiedType(type, qs);
1340 }
1341
getFunctionQualifiersAsString(const FunctionProtoType * FnTy)1342 static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){
1343 std::string Quals =
1344 Qualifiers::fromCVRMask(FnTy->getTypeQuals()).getAsString();
1345
1346 switch (FnTy->getRefQualifier()) {
1347 case RQ_None:
1348 break;
1349
1350 case RQ_LValue:
1351 if (!Quals.empty())
1352 Quals += ' ';
1353 Quals += '&';
1354 break;
1355
1356 case RQ_RValue:
1357 if (!Quals.empty())
1358 Quals += ' ';
1359 Quals += "&&";
1360 break;
1361 }
1362
1363 return Quals;
1364 }
1365
1366 namespace {
1367 /// Kinds of declarator that cannot contain a qualified function type.
1368 ///
1369 /// C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6:
1370 /// a function type with a cv-qualifier or a ref-qualifier can only appear
1371 /// at the topmost level of a type.
1372 ///
1373 /// Parens and member pointers are permitted. We don't diagnose array and
1374 /// function declarators, because they don't allow function types at all.
1375 ///
1376 /// The values of this enum are used in diagnostics.
1377 enum QualifiedFunctionKind { QFK_BlockPointer, QFK_Pointer, QFK_Reference };
1378 }
1379
1380 /// Check whether the type T is a qualified function type, and if it is,
1381 /// diagnose that it cannot be contained within the given kind of declarator.
checkQualifiedFunction(Sema & S,QualType T,SourceLocation Loc,QualifiedFunctionKind QFK)1382 static bool checkQualifiedFunction(Sema &S, QualType T, SourceLocation Loc,
1383 QualifiedFunctionKind QFK) {
1384 // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
1385 const FunctionProtoType *FPT = T->getAs<FunctionProtoType>();
1386 if (!FPT || (FPT->getTypeQuals() == 0 && FPT->getRefQualifier() == RQ_None))
1387 return false;
1388
1389 S.Diag(Loc, diag::err_compound_qualified_function_type)
1390 << QFK << isa<FunctionType>(T.IgnoreParens()) << T
1391 << getFunctionQualifiersAsString(FPT);
1392 return true;
1393 }
1394
1395 /// \brief Build a pointer type.
1396 ///
1397 /// \param T The type to which we'll be building a pointer.
1398 ///
1399 /// \param Loc The location of the entity whose type involves this
1400 /// pointer type or, if there is no such entity, the location of the
1401 /// type that will have pointer type.
1402 ///
1403 /// \param Entity The name of the entity that involves the pointer
1404 /// type, if known.
1405 ///
1406 /// \returns A suitable pointer type, if there are no
1407 /// errors. Otherwise, returns a NULL type.
BuildPointerType(QualType T,SourceLocation Loc,DeclarationName Entity)1408 QualType Sema::BuildPointerType(QualType T,
1409 SourceLocation Loc, DeclarationName Entity) {
1410 if (T->isReferenceType()) {
1411 // C++ 8.3.2p4: There shall be no ... pointers to references ...
1412 Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
1413 << getPrintableNameForEntity(Entity) << T;
1414 return QualType();
1415 }
1416
1417 if (checkQualifiedFunction(*this, T, Loc, QFK_Pointer))
1418 return QualType();
1419
1420 assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType");
1421
1422 // In ARC, it is forbidden to build pointers to unqualified pointers.
1423 if (getLangOpts().ObjCAutoRefCount)
1424 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false);
1425
1426 // Build the pointer type.
1427 return Context.getPointerType(T);
1428 }
1429
1430 /// \brief Build a reference type.
1431 ///
1432 /// \param T The type to which we'll be building a reference.
1433 ///
1434 /// \param Loc The location of the entity whose type involves this
1435 /// reference type or, if there is no such entity, the location of the
1436 /// type that will have reference type.
1437 ///
1438 /// \param Entity The name of the entity that involves the reference
1439 /// type, if known.
1440 ///
1441 /// \returns A suitable reference type, if there are no
1442 /// errors. Otherwise, returns a NULL type.
BuildReferenceType(QualType T,bool SpelledAsLValue,SourceLocation Loc,DeclarationName Entity)1443 QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue,
1444 SourceLocation Loc,
1445 DeclarationName Entity) {
1446 assert(Context.getCanonicalType(T) != Context.OverloadTy &&
1447 "Unresolved overloaded function type");
1448
1449 // C++0x [dcl.ref]p6:
1450 // If a typedef (7.1.3), a type template-parameter (14.3.1), or a
1451 // decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a
1452 // type T, an attempt to create the type "lvalue reference to cv TR" creates
1453 // the type "lvalue reference to T", while an attempt to create the type
1454 // "rvalue reference to cv TR" creates the type TR.
1455 bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
1456
1457 // C++ [dcl.ref]p4: There shall be no references to references.
1458 //
1459 // According to C++ DR 106, references to references are only
1460 // diagnosed when they are written directly (e.g., "int & &"),
1461 // but not when they happen via a typedef:
1462 //
1463 // typedef int& intref;
1464 // typedef intref& intref2;
1465 //
1466 // Parser::ParseDeclaratorInternal diagnoses the case where
1467 // references are written directly; here, we handle the
1468 // collapsing of references-to-references as described in C++0x.
1469 // DR 106 and 540 introduce reference-collapsing into C++98/03.
1470
1471 // C++ [dcl.ref]p1:
1472 // A declarator that specifies the type "reference to cv void"
1473 // is ill-formed.
1474 if (T->isVoidType()) {
1475 Diag(Loc, diag::err_reference_to_void);
1476 return QualType();
1477 }
1478
1479 if (checkQualifiedFunction(*this, T, Loc, QFK_Reference))
1480 return QualType();
1481
1482 // In ARC, it is forbidden to build references to unqualified pointers.
1483 if (getLangOpts().ObjCAutoRefCount)
1484 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true);
1485
1486 // Handle restrict on references.
1487 if (LValueRef)
1488 return Context.getLValueReferenceType(T, SpelledAsLValue);
1489 return Context.getRValueReferenceType(T);
1490 }
1491
1492 /// Check whether the specified array size makes the array type a VLA. If so,
1493 /// return true, if not, return the size of the array in SizeVal.
isArraySizeVLA(Sema & S,Expr * ArraySize,llvm::APSInt & SizeVal)1494 static bool isArraySizeVLA(Sema &S, Expr *ArraySize, llvm::APSInt &SizeVal) {
1495 // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode
1496 // (like gnu99, but not c99) accept any evaluatable value as an extension.
1497 class VLADiagnoser : public Sema::VerifyICEDiagnoser {
1498 public:
1499 VLADiagnoser() : Sema::VerifyICEDiagnoser(true) {}
1500
1501 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
1502 }
1503
1504 void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR) override {
1505 S.Diag(Loc, diag::ext_vla_folded_to_constant) << SR;
1506 }
1507 } Diagnoser;
1508
1509 return S.VerifyIntegerConstantExpression(ArraySize, &SizeVal, Diagnoser,
1510 S.LangOpts.GNUMode).isInvalid();
1511 }
1512
1513
1514 /// \brief Build an array type.
1515 ///
1516 /// \param T The type of each element in the array.
1517 ///
1518 /// \param ASM C99 array size modifier (e.g., '*', 'static').
1519 ///
1520 /// \param ArraySize Expression describing the size of the array.
1521 ///
1522 /// \param Brackets The range from the opening '[' to the closing ']'.
1523 ///
1524 /// \param Entity The name of the entity that involves the array
1525 /// type, if known.
1526 ///
1527 /// \returns A suitable array type, if there are no errors. Otherwise,
1528 /// returns a NULL type.
BuildArrayType(QualType T,ArrayType::ArraySizeModifier ASM,Expr * ArraySize,unsigned Quals,SourceRange Brackets,DeclarationName Entity)1529 QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1530 Expr *ArraySize, unsigned Quals,
1531 SourceRange Brackets, DeclarationName Entity) {
1532
1533 SourceLocation Loc = Brackets.getBegin();
1534 if (getLangOpts().CPlusPlus) {
1535 // C++ [dcl.array]p1:
1536 // T is called the array element type; this type shall not be a reference
1537 // type, the (possibly cv-qualified) type void, a function type or an
1538 // abstract class type.
1539 //
1540 // C++ [dcl.array]p3:
1541 // When several "array of" specifications are adjacent, [...] only the
1542 // first of the constant expressions that specify the bounds of the arrays
1543 // may be omitted.
1544 //
1545 // Note: function types are handled in the common path with C.
1546 if (T->isReferenceType()) {
1547 Diag(Loc, diag::err_illegal_decl_array_of_references)
1548 << getPrintableNameForEntity(Entity) << T;
1549 return QualType();
1550 }
1551
1552 if (T->isVoidType() || T->isIncompleteArrayType()) {
1553 Diag(Loc, diag::err_illegal_decl_array_incomplete_type) << T;
1554 return QualType();
1555 }
1556
1557 if (RequireNonAbstractType(Brackets.getBegin(), T,
1558 diag::err_array_of_abstract_type))
1559 return QualType();
1560
1561 // Mentioning a member pointer type for an array type causes us to lock in
1562 // an inheritance model, even if it's inside an unused typedef.
1563 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
1564 if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>())
1565 if (!MPTy->getClass()->isDependentType())
1566 RequireCompleteType(Loc, T, 0);
1567
1568 } else {
1569 // C99 6.7.5.2p1: If the element type is an incomplete or function type,
1570 // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
1571 if (RequireCompleteType(Loc, T,
1572 diag::err_illegal_decl_array_incomplete_type))
1573 return QualType();
1574 }
1575
1576 if (T->isFunctionType()) {
1577 Diag(Loc, diag::err_illegal_decl_array_of_functions)
1578 << getPrintableNameForEntity(Entity) << T;
1579 return QualType();
1580 }
1581
1582 if (const RecordType *EltTy = T->getAs<RecordType>()) {
1583 // If the element type is a struct or union that contains a variadic
1584 // array, accept it as a GNU extension: C99 6.7.2.1p2.
1585 if (EltTy->getDecl()->hasFlexibleArrayMember())
1586 Diag(Loc, diag::ext_flexible_array_in_array) << T;
1587 } else if (T->isObjCObjectType()) {
1588 Diag(Loc, diag::err_objc_array_of_interfaces) << T;
1589 return QualType();
1590 }
1591
1592 // Do placeholder conversions on the array size expression.
1593 if (ArraySize && ArraySize->hasPlaceholderType()) {
1594 ExprResult Result = CheckPlaceholderExpr(ArraySize);
1595 if (Result.isInvalid()) return QualType();
1596 ArraySize = Result.get();
1597 }
1598
1599 // Do lvalue-to-rvalue conversions on the array size expression.
1600 if (ArraySize && !ArraySize->isRValue()) {
1601 ExprResult Result = DefaultLvalueConversion(ArraySize);
1602 if (Result.isInvalid())
1603 return QualType();
1604
1605 ArraySize = Result.get();
1606 }
1607
1608 // C99 6.7.5.2p1: The size expression shall have integer type.
1609 // C++11 allows contextual conversions to such types.
1610 if (!getLangOpts().CPlusPlus11 &&
1611 ArraySize && !ArraySize->isTypeDependent() &&
1612 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
1613 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
1614 << ArraySize->getType() << ArraySize->getSourceRange();
1615 return QualType();
1616 }
1617
1618 llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType()));
1619 if (!ArraySize) {
1620 if (ASM == ArrayType::Star)
1621 T = Context.getVariableArrayType(T, nullptr, ASM, Quals, Brackets);
1622 else
1623 T = Context.getIncompleteArrayType(T, ASM, Quals);
1624 } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) {
1625 T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets);
1626 } else if ((!T->isDependentType() && !T->isIncompleteType() &&
1627 !T->isConstantSizeType()) ||
1628 isArraySizeVLA(*this, ArraySize, ConstVal)) {
1629 // Even in C++11, don't allow contextual conversions in the array bound
1630 // of a VLA.
1631 if (getLangOpts().CPlusPlus11 &&
1632 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
1633 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
1634 << ArraySize->getType() << ArraySize->getSourceRange();
1635 return QualType();
1636 }
1637
1638 // C99: an array with an element type that has a non-constant-size is a VLA.
1639 // C99: an array with a non-ICE size is a VLA. We accept any expression
1640 // that we can fold to a non-zero positive value as an extension.
1641 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
1642 } else {
1643 // C99 6.7.5.2p1: If the expression is a constant expression, it shall
1644 // have a value greater than zero.
1645 if (ConstVal.isSigned() && ConstVal.isNegative()) {
1646 if (Entity)
1647 Diag(ArraySize->getLocStart(), diag::err_decl_negative_array_size)
1648 << getPrintableNameForEntity(Entity) << ArraySize->getSourceRange();
1649 else
1650 Diag(ArraySize->getLocStart(), diag::err_typecheck_negative_array_size)
1651 << ArraySize->getSourceRange();
1652 return QualType();
1653 }
1654 if (ConstVal == 0) {
1655 // GCC accepts zero sized static arrays. We allow them when
1656 // we're not in a SFINAE context.
1657 Diag(ArraySize->getLocStart(),
1658 isSFINAEContext()? diag::err_typecheck_zero_array_size
1659 : diag::ext_typecheck_zero_array_size)
1660 << ArraySize->getSourceRange();
1661
1662 if (ASM == ArrayType::Static) {
1663 Diag(ArraySize->getLocStart(),
1664 diag::warn_typecheck_zero_static_array_size)
1665 << ArraySize->getSourceRange();
1666 ASM = ArrayType::Normal;
1667 }
1668 } else if (!T->isDependentType() && !T->isVariablyModifiedType() &&
1669 !T->isIncompleteType() && !T->isUndeducedType()) {
1670 // Is the array too large?
1671 unsigned ActiveSizeBits
1672 = ConstantArrayType::getNumAddressingBits(Context, T, ConstVal);
1673 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
1674 Diag(ArraySize->getLocStart(), diag::err_array_too_large)
1675 << ConstVal.toString(10)
1676 << ArraySize->getSourceRange();
1677 return QualType();
1678 }
1679 }
1680
1681 T = Context.getConstantArrayType(T, ConstVal, ASM, Quals);
1682 }
1683
1684 // OpenCL v1.2 s6.9.d: variable length arrays are not supported.
1685 if (getLangOpts().OpenCL && T->isVariableArrayType()) {
1686 Diag(Loc, diag::err_opencl_vla);
1687 return QualType();
1688 }
1689 // If this is not C99, extwarn about VLA's and C99 array size modifiers.
1690 if (!getLangOpts().C99) {
1691 if (T->isVariableArrayType()) {
1692 // Prohibit the use of non-POD types in VLAs.
1693 QualType BaseT = Context.getBaseElementType(T);
1694 if (!T->isDependentType() &&
1695 !RequireCompleteType(Loc, BaseT, 0) &&
1696 !BaseT.isPODType(Context) &&
1697 !BaseT->isObjCLifetimeType()) {
1698 Diag(Loc, diag::err_vla_non_pod)
1699 << BaseT;
1700 return QualType();
1701 }
1702 // Prohibit the use of VLAs during template argument deduction.
1703 else if (isSFINAEContext()) {
1704 Diag(Loc, diag::err_vla_in_sfinae);
1705 return QualType();
1706 }
1707 // Just extwarn about VLAs.
1708 else
1709 Diag(Loc, diag::ext_vla);
1710 } else if (ASM != ArrayType::Normal || Quals != 0)
1711 Diag(Loc,
1712 getLangOpts().CPlusPlus? diag::err_c99_array_usage_cxx
1713 : diag::ext_c99_array_usage) << ASM;
1714 }
1715
1716 if (T->isVariableArrayType()) {
1717 // Warn about VLAs for -Wvla.
1718 Diag(Loc, diag::warn_vla_used);
1719 }
1720
1721 return T;
1722 }
1723
1724 /// \brief Build an ext-vector type.
1725 ///
1726 /// Run the required checks for the extended vector type.
BuildExtVectorType(QualType T,Expr * ArraySize,SourceLocation AttrLoc)1727 QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize,
1728 SourceLocation AttrLoc) {
1729 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1730 // in conjunction with complex types (pointers, arrays, functions, etc.).
1731 if (!T->isDependentType() &&
1732 !T->isIntegerType() && !T->isRealFloatingType()) {
1733 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
1734 return QualType();
1735 }
1736
1737 if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) {
1738 llvm::APSInt vecSize(32);
1739 if (!ArraySize->isIntegerConstantExpr(vecSize, Context)) {
1740 Diag(AttrLoc, diag::err_attribute_argument_type)
1741 << "ext_vector_type" << AANT_ArgumentIntegerConstant
1742 << ArraySize->getSourceRange();
1743 return QualType();
1744 }
1745
1746 // unlike gcc's vector_size attribute, the size is specified as the
1747 // number of elements, not the number of bytes.
1748 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
1749
1750 if (vectorSize == 0) {
1751 Diag(AttrLoc, diag::err_attribute_zero_size)
1752 << ArraySize->getSourceRange();
1753 return QualType();
1754 }
1755
1756 if (VectorType::isVectorSizeTooLarge(vectorSize)) {
1757 Diag(AttrLoc, diag::err_attribute_size_too_large)
1758 << ArraySize->getSourceRange();
1759 return QualType();
1760 }
1761
1762 return Context.getExtVectorType(T, vectorSize);
1763 }
1764
1765 return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc);
1766 }
1767
CheckFunctionReturnType(QualType T,SourceLocation Loc)1768 bool Sema::CheckFunctionReturnType(QualType T, SourceLocation Loc) {
1769 if (T->isArrayType() || T->isFunctionType()) {
1770 Diag(Loc, diag::err_func_returning_array_function)
1771 << T->isFunctionType() << T;
1772 return true;
1773 }
1774
1775 // Functions cannot return half FP.
1776 if (T->isHalfType() && !getLangOpts().HalfArgsAndReturns) {
1777 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 <<
1778 FixItHint::CreateInsertion(Loc, "*");
1779 return true;
1780 }
1781
1782 // Methods cannot return interface types. All ObjC objects are
1783 // passed by reference.
1784 if (T->isObjCObjectType()) {
1785 Diag(Loc, diag::err_object_cannot_be_passed_returned_by_value) << 0 << T;
1786 return 0;
1787 }
1788
1789 return false;
1790 }
1791
BuildFunctionType(QualType T,MutableArrayRef<QualType> ParamTypes,SourceLocation Loc,DeclarationName Entity,const FunctionProtoType::ExtProtoInfo & EPI)1792 QualType Sema::BuildFunctionType(QualType T,
1793 MutableArrayRef<QualType> ParamTypes,
1794 SourceLocation Loc, DeclarationName Entity,
1795 const FunctionProtoType::ExtProtoInfo &EPI) {
1796 bool Invalid = false;
1797
1798 Invalid |= CheckFunctionReturnType(T, Loc);
1799
1800 for (unsigned Idx = 0, Cnt = ParamTypes.size(); Idx < Cnt; ++Idx) {
1801 // FIXME: Loc is too inprecise here, should use proper locations for args.
1802 QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]);
1803 if (ParamType->isVoidType()) {
1804 Diag(Loc, diag::err_param_with_void_type);
1805 Invalid = true;
1806 } else if (ParamType->isHalfType() && !getLangOpts().HalfArgsAndReturns) {
1807 // Disallow half FP arguments.
1808 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 <<
1809 FixItHint::CreateInsertion(Loc, "*");
1810 Invalid = true;
1811 }
1812
1813 ParamTypes[Idx] = ParamType;
1814 }
1815
1816 if (Invalid)
1817 return QualType();
1818
1819 return Context.getFunctionType(T, ParamTypes, EPI);
1820 }
1821
1822 /// \brief Build a member pointer type \c T Class::*.
1823 ///
1824 /// \param T the type to which the member pointer refers.
1825 /// \param Class the class type into which the member pointer points.
1826 /// \param Loc the location where this type begins
1827 /// \param Entity the name of the entity that will have this member pointer type
1828 ///
1829 /// \returns a member pointer type, if successful, or a NULL type if there was
1830 /// an error.
BuildMemberPointerType(QualType T,QualType Class,SourceLocation Loc,DeclarationName Entity)1831 QualType Sema::BuildMemberPointerType(QualType T, QualType Class,
1832 SourceLocation Loc,
1833 DeclarationName Entity) {
1834 // Verify that we're not building a pointer to pointer to function with
1835 // exception specification.
1836 if (CheckDistantExceptionSpec(T)) {
1837 Diag(Loc, diag::err_distant_exception_spec);
1838 return QualType();
1839 }
1840
1841 // C++ 8.3.3p3: A pointer to member shall not point to ... a member
1842 // with reference type, or "cv void."
1843 if (T->isReferenceType()) {
1844 Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
1845 << getPrintableNameForEntity(Entity) << T;
1846 return QualType();
1847 }
1848
1849 if (T->isVoidType()) {
1850 Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
1851 << getPrintableNameForEntity(Entity);
1852 return QualType();
1853 }
1854
1855 if (!Class->isDependentType() && !Class->isRecordType()) {
1856 Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
1857 return QualType();
1858 }
1859
1860 // Adjust the default free function calling convention to the default method
1861 // calling convention.
1862 if (T->isFunctionType())
1863 adjustMemberFunctionCC(T, /*IsStatic=*/false);
1864
1865 return Context.getMemberPointerType(T, Class.getTypePtr());
1866 }
1867
1868 /// \brief Build a block pointer type.
1869 ///
1870 /// \param T The type to which we'll be building a block pointer.
1871 ///
1872 /// \param Loc The source location, used for diagnostics.
1873 ///
1874 /// \param Entity The name of the entity that involves the block pointer
1875 /// type, if known.
1876 ///
1877 /// \returns A suitable block pointer type, if there are no
1878 /// errors. Otherwise, returns a NULL type.
BuildBlockPointerType(QualType T,SourceLocation Loc,DeclarationName Entity)1879 QualType Sema::BuildBlockPointerType(QualType T,
1880 SourceLocation Loc,
1881 DeclarationName Entity) {
1882 if (!T->isFunctionType()) {
1883 Diag(Loc, diag::err_nonfunction_block_type);
1884 return QualType();
1885 }
1886
1887 if (checkQualifiedFunction(*this, T, Loc, QFK_BlockPointer))
1888 return QualType();
1889
1890 return Context.getBlockPointerType(T);
1891 }
1892
GetTypeFromParser(ParsedType Ty,TypeSourceInfo ** TInfo)1893 QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) {
1894 QualType QT = Ty.get();
1895 if (QT.isNull()) {
1896 if (TInfo) *TInfo = nullptr;
1897 return QualType();
1898 }
1899
1900 TypeSourceInfo *DI = nullptr;
1901 if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
1902 QT = LIT->getType();
1903 DI = LIT->getTypeSourceInfo();
1904 }
1905
1906 if (TInfo) *TInfo = DI;
1907 return QT;
1908 }
1909
1910 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
1911 Qualifiers::ObjCLifetime ownership,
1912 unsigned chunkIndex);
1913
1914 /// Given that this is the declaration of a parameter under ARC,
1915 /// attempt to infer attributes and such for pointer-to-whatever
1916 /// types.
inferARCWriteback(TypeProcessingState & state,QualType & declSpecType)1917 static void inferARCWriteback(TypeProcessingState &state,
1918 QualType &declSpecType) {
1919 Sema &S = state.getSema();
1920 Declarator &declarator = state.getDeclarator();
1921
1922 // TODO: should we care about decl qualifiers?
1923
1924 // Check whether the declarator has the expected form. We walk
1925 // from the inside out in order to make the block logic work.
1926 unsigned outermostPointerIndex = 0;
1927 bool isBlockPointer = false;
1928 unsigned numPointers = 0;
1929 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
1930 unsigned chunkIndex = i;
1931 DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex);
1932 switch (chunk.Kind) {
1933 case DeclaratorChunk::Paren:
1934 // Ignore parens.
1935 break;
1936
1937 case DeclaratorChunk::Reference:
1938 case DeclaratorChunk::Pointer:
1939 // Count the number of pointers. Treat references
1940 // interchangeably as pointers; if they're mis-ordered, normal
1941 // type building will discover that.
1942 outermostPointerIndex = chunkIndex;
1943 numPointers++;
1944 break;
1945
1946 case DeclaratorChunk::BlockPointer:
1947 // If we have a pointer to block pointer, that's an acceptable
1948 // indirect reference; anything else is not an application of
1949 // the rules.
1950 if (numPointers != 1) return;
1951 numPointers++;
1952 outermostPointerIndex = chunkIndex;
1953 isBlockPointer = true;
1954
1955 // We don't care about pointer structure in return values here.
1956 goto done;
1957
1958 case DeclaratorChunk::Array: // suppress if written (id[])?
1959 case DeclaratorChunk::Function:
1960 case DeclaratorChunk::MemberPointer:
1961 return;
1962 }
1963 }
1964 done:
1965
1966 // If we have *one* pointer, then we want to throw the qualifier on
1967 // the declaration-specifiers, which means that it needs to be a
1968 // retainable object type.
1969 if (numPointers == 1) {
1970 // If it's not a retainable object type, the rule doesn't apply.
1971 if (!declSpecType->isObjCRetainableType()) return;
1972
1973 // If it already has lifetime, don't do anything.
1974 if (declSpecType.getObjCLifetime()) return;
1975
1976 // Otherwise, modify the type in-place.
1977 Qualifiers qs;
1978
1979 if (declSpecType->isObjCARCImplicitlyUnretainedType())
1980 qs.addObjCLifetime(Qualifiers::OCL_ExplicitNone);
1981 else
1982 qs.addObjCLifetime(Qualifiers::OCL_Autoreleasing);
1983 declSpecType = S.Context.getQualifiedType(declSpecType, qs);
1984
1985 // If we have *two* pointers, then we want to throw the qualifier on
1986 // the outermost pointer.
1987 } else if (numPointers == 2) {
1988 // If we don't have a block pointer, we need to check whether the
1989 // declaration-specifiers gave us something that will turn into a
1990 // retainable object pointer after we slap the first pointer on it.
1991 if (!isBlockPointer && !declSpecType->isObjCObjectType())
1992 return;
1993
1994 // Look for an explicit lifetime attribute there.
1995 DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex);
1996 if (chunk.Kind != DeclaratorChunk::Pointer &&
1997 chunk.Kind != DeclaratorChunk::BlockPointer)
1998 return;
1999 for (const AttributeList *attr = chunk.getAttrs(); attr;
2000 attr = attr->getNext())
2001 if (attr->getKind() == AttributeList::AT_ObjCOwnership)
2002 return;
2003
2004 transferARCOwnershipToDeclaratorChunk(state, Qualifiers::OCL_Autoreleasing,
2005 outermostPointerIndex);
2006
2007 // Any other number of pointers/references does not trigger the rule.
2008 } else return;
2009
2010 // TODO: mark whether we did this inference?
2011 }
2012
diagnoseIgnoredQualifiers(unsigned DiagID,unsigned Quals,SourceLocation FallbackLoc,SourceLocation ConstQualLoc,SourceLocation VolatileQualLoc,SourceLocation RestrictQualLoc,SourceLocation AtomicQualLoc)2013 void Sema::diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
2014 SourceLocation FallbackLoc,
2015 SourceLocation ConstQualLoc,
2016 SourceLocation VolatileQualLoc,
2017 SourceLocation RestrictQualLoc,
2018 SourceLocation AtomicQualLoc) {
2019 if (!Quals)
2020 return;
2021
2022 struct Qual {
2023 unsigned Mask;
2024 const char *Name;
2025 SourceLocation Loc;
2026 } const QualKinds[4] = {
2027 { DeclSpec::TQ_const, "const", ConstQualLoc },
2028 { DeclSpec::TQ_volatile, "volatile", VolatileQualLoc },
2029 { DeclSpec::TQ_restrict, "restrict", RestrictQualLoc },
2030 { DeclSpec::TQ_atomic, "_Atomic", AtomicQualLoc }
2031 };
2032
2033 SmallString<32> QualStr;
2034 unsigned NumQuals = 0;
2035 SourceLocation Loc;
2036 FixItHint FixIts[4];
2037
2038 // Build a string naming the redundant qualifiers.
2039 for (unsigned I = 0; I != 4; ++I) {
2040 if (Quals & QualKinds[I].Mask) {
2041 if (!QualStr.empty()) QualStr += ' ';
2042 QualStr += QualKinds[I].Name;
2043
2044 // If we have a location for the qualifier, offer a fixit.
2045 SourceLocation QualLoc = QualKinds[I].Loc;
2046 if (!QualLoc.isInvalid()) {
2047 FixIts[NumQuals] = FixItHint::CreateRemoval(QualLoc);
2048 if (Loc.isInvalid() ||
2049 getSourceManager().isBeforeInTranslationUnit(QualLoc, Loc))
2050 Loc = QualLoc;
2051 }
2052
2053 ++NumQuals;
2054 }
2055 }
2056
2057 Diag(Loc.isInvalid() ? FallbackLoc : Loc, DiagID)
2058 << QualStr << NumQuals << FixIts[0] << FixIts[1] << FixIts[2] << FixIts[3];
2059 }
2060
2061 // Diagnose pointless type qualifiers on the return type of a function.
diagnoseRedundantReturnTypeQualifiers(Sema & S,QualType RetTy,Declarator & D,unsigned FunctionChunkIndex)2062 static void diagnoseRedundantReturnTypeQualifiers(Sema &S, QualType RetTy,
2063 Declarator &D,
2064 unsigned FunctionChunkIndex) {
2065 if (D.getTypeObject(FunctionChunkIndex).Fun.hasTrailingReturnType()) {
2066 // FIXME: TypeSourceInfo doesn't preserve location information for
2067 // qualifiers.
2068 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
2069 RetTy.getLocalCVRQualifiers(),
2070 D.getIdentifierLoc());
2071 return;
2072 }
2073
2074 for (unsigned OuterChunkIndex = FunctionChunkIndex + 1,
2075 End = D.getNumTypeObjects();
2076 OuterChunkIndex != End; ++OuterChunkIndex) {
2077 DeclaratorChunk &OuterChunk = D.getTypeObject(OuterChunkIndex);
2078 switch (OuterChunk.Kind) {
2079 case DeclaratorChunk::Paren:
2080 continue;
2081
2082 case DeclaratorChunk::Pointer: {
2083 DeclaratorChunk::PointerTypeInfo &PTI = OuterChunk.Ptr;
2084 S.diagnoseIgnoredQualifiers(
2085 diag::warn_qual_return_type,
2086 PTI.TypeQuals,
2087 SourceLocation(),
2088 SourceLocation::getFromRawEncoding(PTI.ConstQualLoc),
2089 SourceLocation::getFromRawEncoding(PTI.VolatileQualLoc),
2090 SourceLocation::getFromRawEncoding(PTI.RestrictQualLoc),
2091 SourceLocation::getFromRawEncoding(PTI.AtomicQualLoc));
2092 return;
2093 }
2094
2095 case DeclaratorChunk::Function:
2096 case DeclaratorChunk::BlockPointer:
2097 case DeclaratorChunk::Reference:
2098 case DeclaratorChunk::Array:
2099 case DeclaratorChunk::MemberPointer:
2100 // FIXME: We can't currently provide an accurate source location and a
2101 // fix-it hint for these.
2102 unsigned AtomicQual = RetTy->isAtomicType() ? DeclSpec::TQ_atomic : 0;
2103 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
2104 RetTy.getCVRQualifiers() | AtomicQual,
2105 D.getIdentifierLoc());
2106 return;
2107 }
2108
2109 llvm_unreachable("unknown declarator chunk kind");
2110 }
2111
2112 // If the qualifiers come from a conversion function type, don't diagnose
2113 // them -- they're not necessarily redundant, since such a conversion
2114 // operator can be explicitly called as "x.operator const int()".
2115 if (D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId)
2116 return;
2117
2118 // Just parens all the way out to the decl specifiers. Diagnose any qualifiers
2119 // which are present there.
2120 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
2121 D.getDeclSpec().getTypeQualifiers(),
2122 D.getIdentifierLoc(),
2123 D.getDeclSpec().getConstSpecLoc(),
2124 D.getDeclSpec().getVolatileSpecLoc(),
2125 D.getDeclSpec().getRestrictSpecLoc(),
2126 D.getDeclSpec().getAtomicSpecLoc());
2127 }
2128
GetDeclSpecTypeForDeclarator(TypeProcessingState & state,TypeSourceInfo * & ReturnTypeInfo)2129 static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state,
2130 TypeSourceInfo *&ReturnTypeInfo) {
2131 Sema &SemaRef = state.getSema();
2132 Declarator &D = state.getDeclarator();
2133 QualType T;
2134 ReturnTypeInfo = nullptr;
2135
2136 // The TagDecl owned by the DeclSpec.
2137 TagDecl *OwnedTagDecl = nullptr;
2138
2139 bool ContainsPlaceholderType = false;
2140
2141 switch (D.getName().getKind()) {
2142 case UnqualifiedId::IK_ImplicitSelfParam:
2143 case UnqualifiedId::IK_OperatorFunctionId:
2144 case UnqualifiedId::IK_Identifier:
2145 case UnqualifiedId::IK_LiteralOperatorId:
2146 case UnqualifiedId::IK_TemplateId:
2147 T = ConvertDeclSpecToType(state);
2148 ContainsPlaceholderType = D.getDeclSpec().containsPlaceholderType();
2149
2150 if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) {
2151 OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
2152 // Owned declaration is embedded in declarator.
2153 OwnedTagDecl->setEmbeddedInDeclarator(true);
2154 }
2155 break;
2156
2157 case UnqualifiedId::IK_ConstructorName:
2158 case UnqualifiedId::IK_ConstructorTemplateId:
2159 case UnqualifiedId::IK_DestructorName:
2160 // Constructors and destructors don't have return types. Use
2161 // "void" instead.
2162 T = SemaRef.Context.VoidTy;
2163 if (AttributeList *attrs = D.getDeclSpec().getAttributes().getList())
2164 processTypeAttrs(state, T, TAL_DeclSpec, attrs);
2165 break;
2166
2167 case UnqualifiedId::IK_ConversionFunctionId:
2168 // The result type of a conversion function is the type that it
2169 // converts to.
2170 T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId,
2171 &ReturnTypeInfo);
2172 ContainsPlaceholderType = T->getContainedAutoType();
2173 break;
2174 }
2175
2176 if (D.getAttributes())
2177 distributeTypeAttrsFromDeclarator(state, T);
2178
2179 // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context.
2180 // In C++11, a function declarator using 'auto' must have a trailing return
2181 // type (this is checked later) and we can skip this. In other languages
2182 // using auto, we need to check regardless.
2183 // C++14 In generic lambdas allow 'auto' in their parameters.
2184 if (ContainsPlaceholderType &&
2185 (!SemaRef.getLangOpts().CPlusPlus11 || !D.isFunctionDeclarator())) {
2186 int Error = -1;
2187
2188 switch (D.getContext()) {
2189 case Declarator::KNRTypeListContext:
2190 llvm_unreachable("K&R type lists aren't allowed in C++");
2191 case Declarator::LambdaExprContext:
2192 llvm_unreachable("Can't specify a type specifier in lambda grammar");
2193 case Declarator::ObjCParameterContext:
2194 case Declarator::ObjCResultContext:
2195 case Declarator::PrototypeContext:
2196 Error = 0;
2197 break;
2198 case Declarator::LambdaExprParameterContext:
2199 if (!(SemaRef.getLangOpts().CPlusPlus14
2200 && D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto))
2201 Error = 14;
2202 break;
2203 case Declarator::MemberContext:
2204 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)
2205 break;
2206 switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) {
2207 case TTK_Enum: llvm_unreachable("unhandled tag kind");
2208 case TTK_Struct: Error = 1; /* Struct member */ break;
2209 case TTK_Union: Error = 2; /* Union member */ break;
2210 case TTK_Class: Error = 3; /* Class member */ break;
2211 case TTK_Interface: Error = 4; /* Interface member */ break;
2212 }
2213 break;
2214 case Declarator::CXXCatchContext:
2215 case Declarator::ObjCCatchContext:
2216 Error = 5; // Exception declaration
2217 break;
2218 case Declarator::TemplateParamContext:
2219 Error = 6; // Template parameter
2220 break;
2221 case Declarator::BlockLiteralContext:
2222 Error = 7; // Block literal
2223 break;
2224 case Declarator::TemplateTypeArgContext:
2225 Error = 8; // Template type argument
2226 break;
2227 case Declarator::AliasDeclContext:
2228 case Declarator::AliasTemplateContext:
2229 Error = 10; // Type alias
2230 break;
2231 case Declarator::TrailingReturnContext:
2232 if (!SemaRef.getLangOpts().CPlusPlus14)
2233 Error = 11; // Function return type
2234 break;
2235 case Declarator::ConversionIdContext:
2236 if (!SemaRef.getLangOpts().CPlusPlus14)
2237 Error = 12; // conversion-type-id
2238 break;
2239 case Declarator::TypeNameContext:
2240 Error = 13; // Generic
2241 break;
2242 case Declarator::FileContext:
2243 case Declarator::BlockContext:
2244 case Declarator::ForContext:
2245 case Declarator::ConditionContext:
2246 case Declarator::CXXNewContext:
2247 break;
2248 }
2249
2250 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
2251 Error = 9;
2252
2253 // In Objective-C it is an error to use 'auto' on a function declarator.
2254 if (D.isFunctionDeclarator())
2255 Error = 11;
2256
2257 // C++11 [dcl.spec.auto]p2: 'auto' is always fine if the declarator
2258 // contains a trailing return type. That is only legal at the outermost
2259 // level. Check all declarator chunks (outermost first) anyway, to give
2260 // better diagnostics.
2261 if (SemaRef.getLangOpts().CPlusPlus11 && Error != -1) {
2262 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
2263 unsigned chunkIndex = e - i - 1;
2264 state.setCurrentChunkIndex(chunkIndex);
2265 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
2266 if (DeclType.Kind == DeclaratorChunk::Function) {
2267 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
2268 if (FTI.hasTrailingReturnType()) {
2269 Error = -1;
2270 break;
2271 }
2272 }
2273 }
2274 }
2275
2276 SourceRange AutoRange = D.getDeclSpec().getTypeSpecTypeLoc();
2277 if (D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId)
2278 AutoRange = D.getName().getSourceRange();
2279
2280 if (Error != -1) {
2281 const bool IsDeclTypeAuto =
2282 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_decltype_auto;
2283 SemaRef.Diag(AutoRange.getBegin(), diag::err_auto_not_allowed)
2284 << IsDeclTypeAuto << Error << AutoRange;
2285 T = SemaRef.Context.IntTy;
2286 D.setInvalidType(true);
2287 } else
2288 SemaRef.Diag(AutoRange.getBegin(),
2289 diag::warn_cxx98_compat_auto_type_specifier)
2290 << AutoRange;
2291 }
2292
2293 if (SemaRef.getLangOpts().CPlusPlus &&
2294 OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) {
2295 // Check the contexts where C++ forbids the declaration of a new class
2296 // or enumeration in a type-specifier-seq.
2297 switch (D.getContext()) {
2298 case Declarator::TrailingReturnContext:
2299 // Class and enumeration definitions are syntactically not allowed in
2300 // trailing return types.
2301 llvm_unreachable("parser should not have allowed this");
2302 break;
2303 case Declarator::FileContext:
2304 case Declarator::MemberContext:
2305 case Declarator::BlockContext:
2306 case Declarator::ForContext:
2307 case Declarator::BlockLiteralContext:
2308 case Declarator::LambdaExprContext:
2309 // C++11 [dcl.type]p3:
2310 // A type-specifier-seq shall not define a class or enumeration unless
2311 // it appears in the type-id of an alias-declaration (7.1.3) that is not
2312 // the declaration of a template-declaration.
2313 case Declarator::AliasDeclContext:
2314 break;
2315 case Declarator::AliasTemplateContext:
2316 SemaRef.Diag(OwnedTagDecl->getLocation(),
2317 diag::err_type_defined_in_alias_template)
2318 << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
2319 D.setInvalidType(true);
2320 break;
2321 case Declarator::TypeNameContext:
2322 case Declarator::ConversionIdContext:
2323 case Declarator::TemplateParamContext:
2324 case Declarator::CXXNewContext:
2325 case Declarator::CXXCatchContext:
2326 case Declarator::ObjCCatchContext:
2327 case Declarator::TemplateTypeArgContext:
2328 SemaRef.Diag(OwnedTagDecl->getLocation(),
2329 diag::err_type_defined_in_type_specifier)
2330 << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
2331 D.setInvalidType(true);
2332 break;
2333 case Declarator::PrototypeContext:
2334 case Declarator::LambdaExprParameterContext:
2335 case Declarator::ObjCParameterContext:
2336 case Declarator::ObjCResultContext:
2337 case Declarator::KNRTypeListContext:
2338 // C++ [dcl.fct]p6:
2339 // Types shall not be defined in return or parameter types.
2340 SemaRef.Diag(OwnedTagDecl->getLocation(),
2341 diag::err_type_defined_in_param_type)
2342 << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
2343 D.setInvalidType(true);
2344 break;
2345 case Declarator::ConditionContext:
2346 // C++ 6.4p2:
2347 // The type-specifier-seq shall not contain typedef and shall not declare
2348 // a new class or enumeration.
2349 SemaRef.Diag(OwnedTagDecl->getLocation(),
2350 diag::err_type_defined_in_condition);
2351 D.setInvalidType(true);
2352 break;
2353 }
2354 }
2355
2356 assert(!T.isNull() && "This function should not return a null type");
2357 return T;
2358 }
2359
2360 /// Produce an appropriate diagnostic for an ambiguity between a function
2361 /// declarator and a C++ direct-initializer.
warnAboutAmbiguousFunction(Sema & S,Declarator & D,DeclaratorChunk & DeclType,QualType RT)2362 static void warnAboutAmbiguousFunction(Sema &S, Declarator &D,
2363 DeclaratorChunk &DeclType, QualType RT) {
2364 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
2365 assert(FTI.isAmbiguous && "no direct-initializer / function ambiguity");
2366
2367 // If the return type is void there is no ambiguity.
2368 if (RT->isVoidType())
2369 return;
2370
2371 // An initializer for a non-class type can have at most one argument.
2372 if (!RT->isRecordType() && FTI.NumParams > 1)
2373 return;
2374
2375 // An initializer for a reference must have exactly one argument.
2376 if (RT->isReferenceType() && FTI.NumParams != 1)
2377 return;
2378
2379 // Only warn if this declarator is declaring a function at block scope, and
2380 // doesn't have a storage class (such as 'extern') specified.
2381 if (!D.isFunctionDeclarator() ||
2382 D.getFunctionDefinitionKind() != FDK_Declaration ||
2383 !S.CurContext->isFunctionOrMethod() ||
2384 D.getDeclSpec().getStorageClassSpec()
2385 != DeclSpec::SCS_unspecified)
2386 return;
2387
2388 // Inside a condition, a direct initializer is not permitted. We allow one to
2389 // be parsed in order to give better diagnostics in condition parsing.
2390 if (D.getContext() == Declarator::ConditionContext)
2391 return;
2392
2393 SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc);
2394
2395 S.Diag(DeclType.Loc,
2396 FTI.NumParams ? diag::warn_parens_disambiguated_as_function_declaration
2397 : diag::warn_empty_parens_are_function_decl)
2398 << ParenRange;
2399
2400 // If the declaration looks like:
2401 // T var1,
2402 // f();
2403 // and name lookup finds a function named 'f', then the ',' was
2404 // probably intended to be a ';'.
2405 if (!D.isFirstDeclarator() && D.getIdentifier()) {
2406 FullSourceLoc Comma(D.getCommaLoc(), S.SourceMgr);
2407 FullSourceLoc Name(D.getIdentifierLoc(), S.SourceMgr);
2408 if (Comma.getFileID() != Name.getFileID() ||
2409 Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) {
2410 LookupResult Result(S, D.getIdentifier(), SourceLocation(),
2411 Sema::LookupOrdinaryName);
2412 if (S.LookupName(Result, S.getCurScope()))
2413 S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call)
2414 << FixItHint::CreateReplacement(D.getCommaLoc(), ";")
2415 << D.getIdentifier();
2416 }
2417 }
2418
2419 if (FTI.NumParams > 0) {
2420 // For a declaration with parameters, eg. "T var(T());", suggest adding
2421 // parens around the first parameter to turn the declaration into a
2422 // variable declaration.
2423 SourceRange Range = FTI.Params[0].Param->getSourceRange();
2424 SourceLocation B = Range.getBegin();
2425 SourceLocation E = S.getLocForEndOfToken(Range.getEnd());
2426 // FIXME: Maybe we should suggest adding braces instead of parens
2427 // in C++11 for classes that don't have an initializer_list constructor.
2428 S.Diag(B, diag::note_additional_parens_for_variable_declaration)
2429 << FixItHint::CreateInsertion(B, "(")
2430 << FixItHint::CreateInsertion(E, ")");
2431 } else {
2432 // For a declaration without parameters, eg. "T var();", suggest replacing
2433 // the parens with an initializer to turn the declaration into a variable
2434 // declaration.
2435 const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
2436
2437 // Empty parens mean value-initialization, and no parens mean
2438 // default initialization. These are equivalent if the default
2439 // constructor is user-provided or if zero-initialization is a
2440 // no-op.
2441 if (RD && RD->hasDefinition() &&
2442 (RD->isEmpty() || RD->hasUserProvidedDefaultConstructor()))
2443 S.Diag(DeclType.Loc, diag::note_empty_parens_default_ctor)
2444 << FixItHint::CreateRemoval(ParenRange);
2445 else {
2446 std::string Init =
2447 S.getFixItZeroInitializerForType(RT, ParenRange.getBegin());
2448 if (Init.empty() && S.LangOpts.CPlusPlus11)
2449 Init = "{}";
2450 if (!Init.empty())
2451 S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize)
2452 << FixItHint::CreateReplacement(ParenRange, Init);
2453 }
2454 }
2455 }
2456
2457 /// Helper for figuring out the default CC for a function declarator type. If
2458 /// this is the outermost chunk, then we can determine the CC from the
2459 /// declarator context. If not, then this could be either a member function
2460 /// type or normal function type.
2461 static CallingConv
getCCForDeclaratorChunk(Sema & S,Declarator & D,const DeclaratorChunk::FunctionTypeInfo & FTI,unsigned ChunkIndex)2462 getCCForDeclaratorChunk(Sema &S, Declarator &D,
2463 const DeclaratorChunk::FunctionTypeInfo &FTI,
2464 unsigned ChunkIndex) {
2465 assert(D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function);
2466
2467 bool IsCXXInstanceMethod = false;
2468
2469 if (S.getLangOpts().CPlusPlus) {
2470 // Look inwards through parentheses to see if this chunk will form a
2471 // member pointer type or if we're the declarator. Any type attributes
2472 // between here and there will override the CC we choose here.
2473 unsigned I = ChunkIndex;
2474 bool FoundNonParen = false;
2475 while (I && !FoundNonParen) {
2476 --I;
2477 if (D.getTypeObject(I).Kind != DeclaratorChunk::Paren)
2478 FoundNonParen = true;
2479 }
2480
2481 if (FoundNonParen) {
2482 // If we're not the declarator, we're a regular function type unless we're
2483 // in a member pointer.
2484 IsCXXInstanceMethod =
2485 D.getTypeObject(I).Kind == DeclaratorChunk::MemberPointer;
2486 } else if (D.getContext() == Declarator::LambdaExprContext) {
2487 // This can only be a call operator for a lambda, which is an instance
2488 // method.
2489 IsCXXInstanceMethod = true;
2490 } else {
2491 // We're the innermost decl chunk, so must be a function declarator.
2492 assert(D.isFunctionDeclarator());
2493
2494 // If we're inside a record, we're declaring a method, but it could be
2495 // explicitly or implicitly static.
2496 IsCXXInstanceMethod =
2497 D.isFirstDeclarationOfMember() &&
2498 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
2499 !D.isStaticMember();
2500 }
2501 }
2502
2503 CallingConv CC = S.Context.getDefaultCallingConvention(FTI.isVariadic,
2504 IsCXXInstanceMethod);
2505
2506 // Attribute AT_OpenCLKernel affects the calling convention only on
2507 // the SPIR target, hence it cannot be treated as a calling
2508 // convention attribute. This is the simplest place to infer
2509 // "spir_kernel" for OpenCL kernels on SPIR.
2510 if (CC == CC_SpirFunction) {
2511 for (const AttributeList *Attr = D.getDeclSpec().getAttributes().getList();
2512 Attr; Attr = Attr->getNext()) {
2513 if (Attr->getKind() == AttributeList::AT_OpenCLKernel) {
2514 CC = CC_SpirKernel;
2515 break;
2516 }
2517 }
2518 }
2519
2520 return CC;
2521 }
2522
GetFullTypeForDeclarator(TypeProcessingState & state,QualType declSpecType,TypeSourceInfo * TInfo)2523 static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
2524 QualType declSpecType,
2525 TypeSourceInfo *TInfo) {
2526 // The TypeSourceInfo that this function returns will not be a null type.
2527 // If there is an error, this function will fill in a dummy type as fallback.
2528 QualType T = declSpecType;
2529 Declarator &D = state.getDeclarator();
2530 Sema &S = state.getSema();
2531 ASTContext &Context = S.Context;
2532 const LangOptions &LangOpts = S.getLangOpts();
2533
2534 // The name we're declaring, if any.
2535 DeclarationName Name;
2536 if (D.getIdentifier())
2537 Name = D.getIdentifier();
2538
2539 // Does this declaration declare a typedef-name?
2540 bool IsTypedefName =
2541 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef ||
2542 D.getContext() == Declarator::AliasDeclContext ||
2543 D.getContext() == Declarator::AliasTemplateContext;
2544
2545 // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
2546 bool IsQualifiedFunction = T->isFunctionProtoType() &&
2547 (T->castAs<FunctionProtoType>()->getTypeQuals() != 0 ||
2548 T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None);
2549
2550 // If T is 'decltype(auto)', the only declarators we can have are parens
2551 // and at most one function declarator if this is a function declaration.
2552 if (const AutoType *AT = T->getAs<AutoType>()) {
2553 if (AT->isDecltypeAuto()) {
2554 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
2555 unsigned Index = E - I - 1;
2556 DeclaratorChunk &DeclChunk = D.getTypeObject(Index);
2557 unsigned DiagId = diag::err_decltype_auto_compound_type;
2558 unsigned DiagKind = 0;
2559 switch (DeclChunk.Kind) {
2560 case DeclaratorChunk::Paren:
2561 continue;
2562 case DeclaratorChunk::Function: {
2563 unsigned FnIndex;
2564 if (D.isFunctionDeclarationContext() &&
2565 D.isFunctionDeclarator(FnIndex) && FnIndex == Index)
2566 continue;
2567 DiagId = diag::err_decltype_auto_function_declarator_not_declaration;
2568 break;
2569 }
2570 case DeclaratorChunk::Pointer:
2571 case DeclaratorChunk::BlockPointer:
2572 case DeclaratorChunk::MemberPointer:
2573 DiagKind = 0;
2574 break;
2575 case DeclaratorChunk::Reference:
2576 DiagKind = 1;
2577 break;
2578 case DeclaratorChunk::Array:
2579 DiagKind = 2;
2580 break;
2581 }
2582
2583 S.Diag(DeclChunk.Loc, DiagId) << DiagKind;
2584 D.setInvalidType(true);
2585 break;
2586 }
2587 }
2588 }
2589
2590 // Walk the DeclTypeInfo, building the recursive type as we go.
2591 // DeclTypeInfos are ordered from the identifier out, which is
2592 // opposite of what we want :).
2593 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
2594 unsigned chunkIndex = e - i - 1;
2595 state.setCurrentChunkIndex(chunkIndex);
2596 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
2597 IsQualifiedFunction &= DeclType.Kind == DeclaratorChunk::Paren;
2598 switch (DeclType.Kind) {
2599 case DeclaratorChunk::Paren:
2600 T = S.BuildParenType(T);
2601 break;
2602 case DeclaratorChunk::BlockPointer:
2603 // If blocks are disabled, emit an error.
2604 if (!LangOpts.Blocks)
2605 S.Diag(DeclType.Loc, diag::err_blocks_disable);
2606
2607 T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name);
2608 if (DeclType.Cls.TypeQuals)
2609 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals);
2610 break;
2611 case DeclaratorChunk::Pointer:
2612 // Verify that we're not building a pointer to pointer to function with
2613 // exception specification.
2614 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
2615 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
2616 D.setInvalidType(true);
2617 // Build the type anyway.
2618 }
2619 if (LangOpts.ObjC1 && T->getAs<ObjCObjectType>()) {
2620 T = Context.getObjCObjectPointerType(T);
2621 if (DeclType.Ptr.TypeQuals)
2622 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
2623 break;
2624 }
2625 T = S.BuildPointerType(T, DeclType.Loc, Name);
2626 if (DeclType.Ptr.TypeQuals)
2627 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
2628
2629 break;
2630 case DeclaratorChunk::Reference: {
2631 // Verify that we're not building a reference to pointer to function with
2632 // exception specification.
2633 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
2634 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
2635 D.setInvalidType(true);
2636 // Build the type anyway.
2637 }
2638 T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name);
2639
2640 if (DeclType.Ref.HasRestrict)
2641 T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict);
2642 break;
2643 }
2644 case DeclaratorChunk::Array: {
2645 // Verify that we're not building an array of pointers to function with
2646 // exception specification.
2647 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
2648 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
2649 D.setInvalidType(true);
2650 // Build the type anyway.
2651 }
2652 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
2653 Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
2654 ArrayType::ArraySizeModifier ASM;
2655 if (ATI.isStar)
2656 ASM = ArrayType::Star;
2657 else if (ATI.hasStatic)
2658 ASM = ArrayType::Static;
2659 else
2660 ASM = ArrayType::Normal;
2661 if (ASM == ArrayType::Star && !D.isPrototypeContext()) {
2662 // FIXME: This check isn't quite right: it allows star in prototypes
2663 // for function definitions, and disallows some edge cases detailed
2664 // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
2665 S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
2666 ASM = ArrayType::Normal;
2667 D.setInvalidType(true);
2668 }
2669
2670 // C99 6.7.5.2p1: The optional type qualifiers and the keyword static
2671 // shall appear only in a declaration of a function parameter with an
2672 // array type, ...
2673 if (ASM == ArrayType::Static || ATI.TypeQuals) {
2674 if (!(D.isPrototypeContext() ||
2675 D.getContext() == Declarator::KNRTypeListContext)) {
2676 S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype) <<
2677 (ASM == ArrayType::Static ? "'static'" : "type qualifier");
2678 // Remove the 'static' and the type qualifiers.
2679 if (ASM == ArrayType::Static)
2680 ASM = ArrayType::Normal;
2681 ATI.TypeQuals = 0;
2682 D.setInvalidType(true);
2683 }
2684
2685 // C99 6.7.5.2p1: ... and then only in the outermost array type
2686 // derivation.
2687 unsigned x = chunkIndex;
2688 while (x != 0) {
2689 // Walk outwards along the declarator chunks.
2690 x--;
2691 const DeclaratorChunk &DC = D.getTypeObject(x);
2692 switch (DC.Kind) {
2693 case DeclaratorChunk::Paren:
2694 continue;
2695 case DeclaratorChunk::Array:
2696 case DeclaratorChunk::Pointer:
2697 case DeclaratorChunk::Reference:
2698 case DeclaratorChunk::MemberPointer:
2699 S.Diag(DeclType.Loc, diag::err_array_static_not_outermost) <<
2700 (ASM == ArrayType::Static ? "'static'" : "type qualifier");
2701 if (ASM == ArrayType::Static)
2702 ASM = ArrayType::Normal;
2703 ATI.TypeQuals = 0;
2704 D.setInvalidType(true);
2705 break;
2706 case DeclaratorChunk::Function:
2707 case DeclaratorChunk::BlockPointer:
2708 // These are invalid anyway, so just ignore.
2709 break;
2710 }
2711 }
2712 }
2713 const AutoType *AT = T->getContainedAutoType();
2714 // Allow arrays of auto if we are a generic lambda parameter.
2715 // i.e. [](auto (&array)[5]) { return array[0]; }; OK
2716 if (AT && D.getContext() != Declarator::LambdaExprParameterContext) {
2717 // We've already diagnosed this for decltype(auto).
2718 if (!AT->isDecltypeAuto())
2719 S.Diag(DeclType.Loc, diag::err_illegal_decl_array_of_auto)
2720 << getPrintableNameForEntity(Name) << T;
2721 T = QualType();
2722 break;
2723 }
2724
2725 T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals,
2726 SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
2727 break;
2728 }
2729 case DeclaratorChunk::Function: {
2730 // If the function declarator has a prototype (i.e. it is not () and
2731 // does not have a K&R-style identifier list), then the arguments are part
2732 // of the type, otherwise the argument list is ().
2733 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
2734 IsQualifiedFunction = FTI.TypeQuals || FTI.hasRefQualifier();
2735
2736 // Check for auto functions and trailing return type and adjust the
2737 // return type accordingly.
2738 if (!D.isInvalidType()) {
2739 // trailing-return-type is only required if we're declaring a function,
2740 // and not, for instance, a pointer to a function.
2741 if (D.getDeclSpec().containsPlaceholderType() &&
2742 !FTI.hasTrailingReturnType() && chunkIndex == 0 &&
2743 !S.getLangOpts().CPlusPlus14) {
2744 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
2745 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto
2746 ? diag::err_auto_missing_trailing_return
2747 : diag::err_deduced_return_type);
2748 T = Context.IntTy;
2749 D.setInvalidType(true);
2750 } else if (FTI.hasTrailingReturnType()) {
2751 // T must be exactly 'auto' at this point. See CWG issue 681.
2752 if (isa<ParenType>(T)) {
2753 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
2754 diag::err_trailing_return_in_parens)
2755 << T << D.getDeclSpec().getSourceRange();
2756 D.setInvalidType(true);
2757 } else if (D.getContext() != Declarator::LambdaExprContext &&
2758 (T.hasQualifiers() || !isa<AutoType>(T) ||
2759 cast<AutoType>(T)->isDecltypeAuto())) {
2760 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
2761 diag::err_trailing_return_without_auto)
2762 << T << D.getDeclSpec().getSourceRange();
2763 D.setInvalidType(true);
2764 }
2765 T = S.GetTypeFromParser(FTI.getTrailingReturnType(), &TInfo);
2766 if (T.isNull()) {
2767 // An error occurred parsing the trailing return type.
2768 T = Context.IntTy;
2769 D.setInvalidType(true);
2770 }
2771 }
2772 }
2773
2774 // C99 6.7.5.3p1: The return type may not be a function or array type.
2775 // For conversion functions, we'll diagnose this particular error later.
2776 if ((T->isArrayType() || T->isFunctionType()) &&
2777 (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId)) {
2778 unsigned diagID = diag::err_func_returning_array_function;
2779 // Last processing chunk in block context means this function chunk
2780 // represents the block.
2781 if (chunkIndex == 0 &&
2782 D.getContext() == Declarator::BlockLiteralContext)
2783 diagID = diag::err_block_returning_array_function;
2784 S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T;
2785 T = Context.IntTy;
2786 D.setInvalidType(true);
2787 }
2788
2789 // Do not allow returning half FP value.
2790 // FIXME: This really should be in BuildFunctionType.
2791 if (T->isHalfType()) {
2792 if (S.getLangOpts().OpenCL) {
2793 if (!S.getOpenCLOptions().cl_khr_fp16) {
2794 S.Diag(D.getIdentifierLoc(), diag::err_opencl_half_return) << T;
2795 D.setInvalidType(true);
2796 }
2797 } else if (!S.getLangOpts().HalfArgsAndReturns) {
2798 S.Diag(D.getIdentifierLoc(),
2799 diag::err_parameters_retval_cannot_have_fp16_type) << 1;
2800 D.setInvalidType(true);
2801 }
2802 }
2803
2804 // Methods cannot return interface types. All ObjC objects are
2805 // passed by reference.
2806 if (T->isObjCObjectType()) {
2807 SourceLocation DiagLoc, FixitLoc;
2808 if (TInfo) {
2809 DiagLoc = TInfo->getTypeLoc().getLocStart();
2810 FixitLoc = S.getLocForEndOfToken(TInfo->getTypeLoc().getLocEnd());
2811 } else {
2812 DiagLoc = D.getDeclSpec().getTypeSpecTypeLoc();
2813 FixitLoc = S.getLocForEndOfToken(D.getDeclSpec().getLocEnd());
2814 }
2815 S.Diag(DiagLoc, diag::err_object_cannot_be_passed_returned_by_value)
2816 << 0 << T
2817 << FixItHint::CreateInsertion(FixitLoc, "*");
2818
2819 T = Context.getObjCObjectPointerType(T);
2820 if (TInfo) {
2821 TypeLocBuilder TLB;
2822 TLB.pushFullCopy(TInfo->getTypeLoc());
2823 ObjCObjectPointerTypeLoc TLoc = TLB.push<ObjCObjectPointerTypeLoc>(T);
2824 TLoc.setStarLoc(FixitLoc);
2825 TInfo = TLB.getTypeSourceInfo(Context, T);
2826 }
2827
2828 D.setInvalidType(true);
2829 }
2830
2831 // cv-qualifiers on return types are pointless except when the type is a
2832 // class type in C++.
2833 if ((T.getCVRQualifiers() || T->isAtomicType()) &&
2834 !(S.getLangOpts().CPlusPlus &&
2835 (T->isDependentType() || T->isRecordType()))) {
2836 if (T->isVoidType() && !S.getLangOpts().CPlusPlus &&
2837 D.getFunctionDefinitionKind() == FDK_Definition) {
2838 // [6.9.1/3] qualified void return is invalid on a C
2839 // function definition. Apparently ok on declarations and
2840 // in C++ though (!)
2841 S.Diag(DeclType.Loc, diag::err_func_returning_qualified_void) << T;
2842 } else
2843 diagnoseRedundantReturnTypeQualifiers(S, T, D, chunkIndex);
2844 }
2845
2846 // Objective-C ARC ownership qualifiers are ignored on the function
2847 // return type (by type canonicalization). Complain if this attribute
2848 // was written here.
2849 if (T.getQualifiers().hasObjCLifetime()) {
2850 SourceLocation AttrLoc;
2851 if (chunkIndex + 1 < D.getNumTypeObjects()) {
2852 DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1);
2853 for (const AttributeList *Attr = ReturnTypeChunk.getAttrs();
2854 Attr; Attr = Attr->getNext()) {
2855 if (Attr->getKind() == AttributeList::AT_ObjCOwnership) {
2856 AttrLoc = Attr->getLoc();
2857 break;
2858 }
2859 }
2860 }
2861 if (AttrLoc.isInvalid()) {
2862 for (const AttributeList *Attr
2863 = D.getDeclSpec().getAttributes().getList();
2864 Attr; Attr = Attr->getNext()) {
2865 if (Attr->getKind() == AttributeList::AT_ObjCOwnership) {
2866 AttrLoc = Attr->getLoc();
2867 break;
2868 }
2869 }
2870 }
2871
2872 if (AttrLoc.isValid()) {
2873 // The ownership attributes are almost always written via
2874 // the predefined
2875 // __strong/__weak/__autoreleasing/__unsafe_unretained.
2876 if (AttrLoc.isMacroID())
2877 AttrLoc = S.SourceMgr.getImmediateExpansionRange(AttrLoc).first;
2878
2879 S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type)
2880 << T.getQualifiers().getObjCLifetime();
2881 }
2882 }
2883
2884 if (LangOpts.CPlusPlus && D.getDeclSpec().hasTagDefinition()) {
2885 // C++ [dcl.fct]p6:
2886 // Types shall not be defined in return or parameter types.
2887 TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
2888 S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
2889 << Context.getTypeDeclType(Tag);
2890 }
2891
2892 // Exception specs are not allowed in typedefs. Complain, but add it
2893 // anyway.
2894 if (IsTypedefName && FTI.getExceptionSpecType())
2895 S.Diag(FTI.getExceptionSpecLoc(), diag::err_exception_spec_in_typedef)
2896 << (D.getContext() == Declarator::AliasDeclContext ||
2897 D.getContext() == Declarator::AliasTemplateContext);
2898
2899 // If we see "T var();" or "T var(T());" at block scope, it is probably
2900 // an attempt to initialize a variable, not a function declaration.
2901 if (FTI.isAmbiguous)
2902 warnAboutAmbiguousFunction(S, D, DeclType, T);
2903
2904 FunctionType::ExtInfo EI(getCCForDeclaratorChunk(S, D, FTI, chunkIndex));
2905
2906 if (!FTI.NumParams && !FTI.isVariadic && !LangOpts.CPlusPlus) {
2907 // Simple void foo(), where the incoming T is the result type.
2908 T = Context.getFunctionNoProtoType(T, EI);
2909 } else {
2910 // We allow a zero-parameter variadic function in C if the
2911 // function is marked with the "overloadable" attribute. Scan
2912 // for this attribute now.
2913 if (!FTI.NumParams && FTI.isVariadic && !LangOpts.CPlusPlus) {
2914 bool Overloadable = false;
2915 for (const AttributeList *Attrs = D.getAttributes();
2916 Attrs; Attrs = Attrs->getNext()) {
2917 if (Attrs->getKind() == AttributeList::AT_Overloadable) {
2918 Overloadable = true;
2919 break;
2920 }
2921 }
2922
2923 if (!Overloadable)
2924 S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_param);
2925 }
2926
2927 if (FTI.NumParams && FTI.Params[0].Param == nullptr) {
2928 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function
2929 // definition.
2930 S.Diag(FTI.Params[0].IdentLoc,
2931 diag::err_ident_list_in_fn_declaration);
2932 D.setInvalidType(true);
2933 // Recover by creating a K&R-style function type.
2934 T = Context.getFunctionNoProtoType(T, EI);
2935 break;
2936 }
2937
2938 FunctionProtoType::ExtProtoInfo EPI;
2939 EPI.ExtInfo = EI;
2940 EPI.Variadic = FTI.isVariadic;
2941 EPI.HasTrailingReturn = FTI.hasTrailingReturnType();
2942 EPI.TypeQuals = FTI.TypeQuals;
2943 EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None
2944 : FTI.RefQualifierIsLValueRef? RQ_LValue
2945 : RQ_RValue;
2946
2947 // Otherwise, we have a function with a parameter list that is
2948 // potentially variadic.
2949 SmallVector<QualType, 16> ParamTys;
2950 ParamTys.reserve(FTI.NumParams);
2951
2952 SmallVector<bool, 16> ConsumedParameters;
2953 ConsumedParameters.reserve(FTI.NumParams);
2954 bool HasAnyConsumedParameters = false;
2955
2956 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
2957 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
2958 QualType ParamTy = Param->getType();
2959 assert(!ParamTy.isNull() && "Couldn't parse type?");
2960
2961 // Look for 'void'. void is allowed only as a single parameter to a
2962 // function with no other parameters (C99 6.7.5.3p10). We record
2963 // int(void) as a FunctionProtoType with an empty parameter list.
2964 if (ParamTy->isVoidType()) {
2965 // If this is something like 'float(int, void)', reject it. 'void'
2966 // is an incomplete type (C99 6.2.5p19) and function decls cannot
2967 // have parameters of incomplete type.
2968 if (FTI.NumParams != 1 || FTI.isVariadic) {
2969 S.Diag(DeclType.Loc, diag::err_void_only_param);
2970 ParamTy = Context.IntTy;
2971 Param->setType(ParamTy);
2972 } else if (FTI.Params[i].Ident) {
2973 // Reject, but continue to parse 'int(void abc)'.
2974 S.Diag(FTI.Params[i].IdentLoc, diag::err_param_with_void_type);
2975 ParamTy = Context.IntTy;
2976 Param->setType(ParamTy);
2977 } else {
2978 // Reject, but continue to parse 'float(const void)'.
2979 if (ParamTy.hasQualifiers())
2980 S.Diag(DeclType.Loc, diag::err_void_param_qualified);
2981
2982 // Do not add 'void' to the list.
2983 break;
2984 }
2985 } else if (ParamTy->isHalfType()) {
2986 // Disallow half FP parameters.
2987 // FIXME: This really should be in BuildFunctionType.
2988 if (S.getLangOpts().OpenCL) {
2989 if (!S.getOpenCLOptions().cl_khr_fp16) {
2990 S.Diag(Param->getLocation(),
2991 diag::err_opencl_half_param) << ParamTy;
2992 D.setInvalidType();
2993 Param->setInvalidDecl();
2994 }
2995 } else if (!S.getLangOpts().HalfArgsAndReturns) {
2996 S.Diag(Param->getLocation(),
2997 diag::err_parameters_retval_cannot_have_fp16_type) << 0;
2998 D.setInvalidType();
2999 }
3000 } else if (!FTI.hasPrototype) {
3001 if (ParamTy->isPromotableIntegerType()) {
3002 ParamTy = Context.getPromotedIntegerType(ParamTy);
3003 Param->setKNRPromoted(true);
3004 } else if (const BuiltinType* BTy = ParamTy->getAs<BuiltinType>()) {
3005 if (BTy->getKind() == BuiltinType::Float) {
3006 ParamTy = Context.DoubleTy;
3007 Param->setKNRPromoted(true);
3008 }
3009 }
3010 }
3011
3012 if (LangOpts.ObjCAutoRefCount) {
3013 bool Consumed = Param->hasAttr<NSConsumedAttr>();
3014 ConsumedParameters.push_back(Consumed);
3015 HasAnyConsumedParameters |= Consumed;
3016 }
3017
3018 ParamTys.push_back(ParamTy);
3019 }
3020
3021 if (HasAnyConsumedParameters)
3022 EPI.ConsumedParameters = ConsumedParameters.data();
3023
3024 SmallVector<QualType, 4> Exceptions;
3025 SmallVector<ParsedType, 2> DynamicExceptions;
3026 SmallVector<SourceRange, 2> DynamicExceptionRanges;
3027 Expr *NoexceptExpr = nullptr;
3028
3029 if (FTI.getExceptionSpecType() == EST_Dynamic) {
3030 // FIXME: It's rather inefficient to have to split into two vectors
3031 // here.
3032 unsigned N = FTI.NumExceptions;
3033 DynamicExceptions.reserve(N);
3034 DynamicExceptionRanges.reserve(N);
3035 for (unsigned I = 0; I != N; ++I) {
3036 DynamicExceptions.push_back(FTI.Exceptions[I].Ty);
3037 DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range);
3038 }
3039 } else if (FTI.getExceptionSpecType() == EST_ComputedNoexcept) {
3040 NoexceptExpr = FTI.NoexceptExpr;
3041 }
3042
3043 S.checkExceptionSpecification(D.isFunctionDeclarationContext(),
3044 FTI.getExceptionSpecType(),
3045 DynamicExceptions,
3046 DynamicExceptionRanges,
3047 NoexceptExpr,
3048 Exceptions,
3049 EPI.ExceptionSpec);
3050
3051 T = Context.getFunctionType(T, ParamTys, EPI);
3052 }
3053
3054 break;
3055 }
3056 case DeclaratorChunk::MemberPointer:
3057 // The scope spec must refer to a class, or be dependent.
3058 CXXScopeSpec &SS = DeclType.Mem.Scope();
3059 QualType ClsType;
3060 if (SS.isInvalid()) {
3061 // Avoid emitting extra errors if we already errored on the scope.
3062 D.setInvalidType(true);
3063 } else if (S.isDependentScopeSpecifier(SS) ||
3064 dyn_cast_or_null<CXXRecordDecl>(S.computeDeclContext(SS))) {
3065 NestedNameSpecifier *NNS = SS.getScopeRep();
3066 NestedNameSpecifier *NNSPrefix = NNS->getPrefix();
3067 switch (NNS->getKind()) {
3068 case NestedNameSpecifier::Identifier:
3069 ClsType = Context.getDependentNameType(ETK_None, NNSPrefix,
3070 NNS->getAsIdentifier());
3071 break;
3072
3073 case NestedNameSpecifier::Namespace:
3074 case NestedNameSpecifier::NamespaceAlias:
3075 case NestedNameSpecifier::Global:
3076 case NestedNameSpecifier::Super:
3077 llvm_unreachable("Nested-name-specifier must name a type");
3078
3079 case NestedNameSpecifier::TypeSpec:
3080 case NestedNameSpecifier::TypeSpecWithTemplate:
3081 ClsType = QualType(NNS->getAsType(), 0);
3082 // Note: if the NNS has a prefix and ClsType is a nondependent
3083 // TemplateSpecializationType, then the NNS prefix is NOT included
3084 // in ClsType; hence we wrap ClsType into an ElaboratedType.
3085 // NOTE: in particular, no wrap occurs if ClsType already is an
3086 // Elaborated, DependentName, or DependentTemplateSpecialization.
3087 if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType()))
3088 ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType);
3089 break;
3090 }
3091 } else {
3092 S.Diag(DeclType.Mem.Scope().getBeginLoc(),
3093 diag::err_illegal_decl_mempointer_in_nonclass)
3094 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
3095 << DeclType.Mem.Scope().getRange();
3096 D.setInvalidType(true);
3097 }
3098
3099 if (!ClsType.isNull())
3100 T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc,
3101 D.getIdentifier());
3102 if (T.isNull()) {
3103 T = Context.IntTy;
3104 D.setInvalidType(true);
3105 } else if (DeclType.Mem.TypeQuals) {
3106 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals);
3107 }
3108 break;
3109 }
3110
3111 if (T.isNull()) {
3112 D.setInvalidType(true);
3113 T = Context.IntTy;
3114 }
3115
3116 // See if there are any attributes on this declarator chunk.
3117 if (AttributeList *attrs = const_cast<AttributeList*>(DeclType.getAttrs()))
3118 processTypeAttrs(state, T, TAL_DeclChunk, attrs);
3119 }
3120
3121 assert(!T.isNull() && "T must not be null after this point");
3122
3123 if (LangOpts.CPlusPlus && T->isFunctionType()) {
3124 const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
3125 assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
3126
3127 // C++ 8.3.5p4:
3128 // A cv-qualifier-seq shall only be part of the function type
3129 // for a nonstatic member function, the function type to which a pointer
3130 // to member refers, or the top-level function type of a function typedef
3131 // declaration.
3132 //
3133 // Core issue 547 also allows cv-qualifiers on function types that are
3134 // top-level template type arguments.
3135 bool FreeFunction;
3136 if (!D.getCXXScopeSpec().isSet()) {
3137 FreeFunction = ((D.getContext() != Declarator::MemberContext &&
3138 D.getContext() != Declarator::LambdaExprContext) ||
3139 D.getDeclSpec().isFriendSpecified());
3140 } else {
3141 DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec());
3142 FreeFunction = (DC && !DC->isRecord());
3143 }
3144
3145 // C++11 [dcl.fct]p6 (w/DR1417):
3146 // An attempt to specify a function type with a cv-qualifier-seq or a
3147 // ref-qualifier (including by typedef-name) is ill-formed unless it is:
3148 // - the function type for a non-static member function,
3149 // - the function type to which a pointer to member refers,
3150 // - the top-level function type of a function typedef declaration or
3151 // alias-declaration,
3152 // - the type-id in the default argument of a type-parameter, or
3153 // - the type-id of a template-argument for a type-parameter
3154 //
3155 // FIXME: Checking this here is insufficient. We accept-invalid on:
3156 //
3157 // template<typename T> struct S { void f(T); };
3158 // S<int() const> s;
3159 //
3160 // ... for instance.
3161 if (IsQualifiedFunction &&
3162 !(!FreeFunction &&
3163 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) &&
3164 !IsTypedefName &&
3165 D.getContext() != Declarator::TemplateTypeArgContext) {
3166 SourceLocation Loc = D.getLocStart();
3167 SourceRange RemovalRange;
3168 unsigned I;
3169 if (D.isFunctionDeclarator(I)) {
3170 SmallVector<SourceLocation, 4> RemovalLocs;
3171 const DeclaratorChunk &Chunk = D.getTypeObject(I);
3172 assert(Chunk.Kind == DeclaratorChunk::Function);
3173 if (Chunk.Fun.hasRefQualifier())
3174 RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc());
3175 if (Chunk.Fun.TypeQuals & Qualifiers::Const)
3176 RemovalLocs.push_back(Chunk.Fun.getConstQualifierLoc());
3177 if (Chunk.Fun.TypeQuals & Qualifiers::Volatile)
3178 RemovalLocs.push_back(Chunk.Fun.getVolatileQualifierLoc());
3179 if (Chunk.Fun.TypeQuals & Qualifiers::Restrict)
3180 RemovalLocs.push_back(Chunk.Fun.getRestrictQualifierLoc());
3181 if (!RemovalLocs.empty()) {
3182 std::sort(RemovalLocs.begin(), RemovalLocs.end(),
3183 BeforeThanCompare<SourceLocation>(S.getSourceManager()));
3184 RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back());
3185 Loc = RemovalLocs.front();
3186 }
3187 }
3188
3189 S.Diag(Loc, diag::err_invalid_qualified_function_type)
3190 << FreeFunction << D.isFunctionDeclarator() << T
3191 << getFunctionQualifiersAsString(FnTy)
3192 << FixItHint::CreateRemoval(RemovalRange);
3193
3194 // Strip the cv-qualifiers and ref-qualifiers from the type.
3195 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
3196 EPI.TypeQuals = 0;
3197 EPI.RefQualifier = RQ_None;
3198
3199 T = Context.getFunctionType(FnTy->getReturnType(), FnTy->getParamTypes(),
3200 EPI);
3201 // Rebuild any parens around the identifier in the function type.
3202 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
3203 if (D.getTypeObject(i).Kind != DeclaratorChunk::Paren)
3204 break;
3205 T = S.BuildParenType(T);
3206 }
3207 }
3208 }
3209
3210 // Apply any undistributed attributes from the declarator.
3211 if (AttributeList *attrs = D.getAttributes())
3212 processTypeAttrs(state, T, TAL_DeclName, attrs);
3213
3214 // Diagnose any ignored type attributes.
3215 state.diagnoseIgnoredTypeAttrs(T);
3216
3217 // C++0x [dcl.constexpr]p9:
3218 // A constexpr specifier used in an object declaration declares the object
3219 // as const.
3220 if (D.getDeclSpec().isConstexprSpecified() && T->isObjectType()) {
3221 T.addConst();
3222 }
3223
3224 // If there was an ellipsis in the declarator, the declaration declares a
3225 // parameter pack whose type may be a pack expansion type.
3226 if (D.hasEllipsis()) {
3227 // C++0x [dcl.fct]p13:
3228 // A declarator-id or abstract-declarator containing an ellipsis shall
3229 // only be used in a parameter-declaration. Such a parameter-declaration
3230 // is a parameter pack (14.5.3). [...]
3231 switch (D.getContext()) {
3232 case Declarator::PrototypeContext:
3233 case Declarator::LambdaExprParameterContext:
3234 // C++0x [dcl.fct]p13:
3235 // [...] When it is part of a parameter-declaration-clause, the
3236 // parameter pack is a function parameter pack (14.5.3). The type T
3237 // of the declarator-id of the function parameter pack shall contain
3238 // a template parameter pack; each template parameter pack in T is
3239 // expanded by the function parameter pack.
3240 //
3241 // We represent function parameter packs as function parameters whose
3242 // type is a pack expansion.
3243 if (!T->containsUnexpandedParameterPack()) {
3244 S.Diag(D.getEllipsisLoc(),
3245 diag::err_function_parameter_pack_without_parameter_packs)
3246 << T << D.getSourceRange();
3247 D.setEllipsisLoc(SourceLocation());
3248 } else {
3249 T = Context.getPackExpansionType(T, None);
3250 }
3251 break;
3252 case Declarator::TemplateParamContext:
3253 // C++0x [temp.param]p15:
3254 // If a template-parameter is a [...] is a parameter-declaration that
3255 // declares a parameter pack (8.3.5), then the template-parameter is a
3256 // template parameter pack (14.5.3).
3257 //
3258 // Note: core issue 778 clarifies that, if there are any unexpanded
3259 // parameter packs in the type of the non-type template parameter, then
3260 // it expands those parameter packs.
3261 if (T->containsUnexpandedParameterPack())
3262 T = Context.getPackExpansionType(T, None);
3263 else
3264 S.Diag(D.getEllipsisLoc(),
3265 LangOpts.CPlusPlus11
3266 ? diag::warn_cxx98_compat_variadic_templates
3267 : diag::ext_variadic_templates);
3268 break;
3269
3270 case Declarator::FileContext:
3271 case Declarator::KNRTypeListContext:
3272 case Declarator::ObjCParameterContext: // FIXME: special diagnostic here?
3273 case Declarator::ObjCResultContext: // FIXME: special diagnostic here?
3274 case Declarator::TypeNameContext:
3275 case Declarator::CXXNewContext:
3276 case Declarator::AliasDeclContext:
3277 case Declarator::AliasTemplateContext:
3278 case Declarator::MemberContext:
3279 case Declarator::BlockContext:
3280 case Declarator::ForContext:
3281 case Declarator::ConditionContext:
3282 case Declarator::CXXCatchContext:
3283 case Declarator::ObjCCatchContext:
3284 case Declarator::BlockLiteralContext:
3285 case Declarator::LambdaExprContext:
3286 case Declarator::ConversionIdContext:
3287 case Declarator::TrailingReturnContext:
3288 case Declarator::TemplateTypeArgContext:
3289 // FIXME: We may want to allow parameter packs in block-literal contexts
3290 // in the future.
3291 S.Diag(D.getEllipsisLoc(),
3292 diag::err_ellipsis_in_declarator_not_parameter);
3293 D.setEllipsisLoc(SourceLocation());
3294 break;
3295 }
3296 }
3297
3298 assert(!T.isNull() && "T must not be null at the end of this function");
3299 if (D.isInvalidType())
3300 return Context.getTrivialTypeSourceInfo(T);
3301
3302 return S.GetTypeSourceInfoForDeclarator(D, T, TInfo);
3303 }
3304
3305 /// GetTypeForDeclarator - Convert the type for the specified
3306 /// declarator to Type instances.
3307 ///
3308 /// The result of this call will never be null, but the associated
3309 /// type may be a null type if there's an unrecoverable error.
GetTypeForDeclarator(Declarator & D,Scope * S)3310 TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) {
3311 // Determine the type of the declarator. Not all forms of declarator
3312 // have a type.
3313
3314 TypeProcessingState state(*this, D);
3315
3316 TypeSourceInfo *ReturnTypeInfo = nullptr;
3317 QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
3318
3319 if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount)
3320 inferARCWriteback(state, T);
3321
3322 return GetFullTypeForDeclarator(state, T, ReturnTypeInfo);
3323 }
3324
transferARCOwnershipToDeclSpec(Sema & S,QualType & declSpecTy,Qualifiers::ObjCLifetime ownership)3325 static void transferARCOwnershipToDeclSpec(Sema &S,
3326 QualType &declSpecTy,
3327 Qualifiers::ObjCLifetime ownership) {
3328 if (declSpecTy->isObjCRetainableType() &&
3329 declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) {
3330 Qualifiers qs;
3331 qs.addObjCLifetime(ownership);
3332 declSpecTy = S.Context.getQualifiedType(declSpecTy, qs);
3333 }
3334 }
3335
transferARCOwnershipToDeclaratorChunk(TypeProcessingState & state,Qualifiers::ObjCLifetime ownership,unsigned chunkIndex)3336 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
3337 Qualifiers::ObjCLifetime ownership,
3338 unsigned chunkIndex) {
3339 Sema &S = state.getSema();
3340 Declarator &D = state.getDeclarator();
3341
3342 // Look for an explicit lifetime attribute.
3343 DeclaratorChunk &chunk = D.getTypeObject(chunkIndex);
3344 for (const AttributeList *attr = chunk.getAttrs(); attr;
3345 attr = attr->getNext())
3346 if (attr->getKind() == AttributeList::AT_ObjCOwnership)
3347 return;
3348
3349 const char *attrStr = nullptr;
3350 switch (ownership) {
3351 case Qualifiers::OCL_None: llvm_unreachable("no ownership!");
3352 case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break;
3353 case Qualifiers::OCL_Strong: attrStr = "strong"; break;
3354 case Qualifiers::OCL_Weak: attrStr = "weak"; break;
3355 case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break;
3356 }
3357
3358 IdentifierLoc *Arg = new (S.Context) IdentifierLoc;
3359 Arg->Ident = &S.Context.Idents.get(attrStr);
3360 Arg->Loc = SourceLocation();
3361
3362 ArgsUnion Args(Arg);
3363
3364 // If there wasn't one, add one (with an invalid source location
3365 // so that we don't make an AttributedType for it).
3366 AttributeList *attr = D.getAttributePool()
3367 .create(&S.Context.Idents.get("objc_ownership"), SourceLocation(),
3368 /*scope*/ nullptr, SourceLocation(),
3369 /*args*/ &Args, 1, AttributeList::AS_GNU);
3370 spliceAttrIntoList(*attr, chunk.getAttrListRef());
3371
3372 // TODO: mark whether we did this inference?
3373 }
3374
3375 /// \brief Used for transferring ownership in casts resulting in l-values.
transferARCOwnership(TypeProcessingState & state,QualType & declSpecTy,Qualifiers::ObjCLifetime ownership)3376 static void transferARCOwnership(TypeProcessingState &state,
3377 QualType &declSpecTy,
3378 Qualifiers::ObjCLifetime ownership) {
3379 Sema &S = state.getSema();
3380 Declarator &D = state.getDeclarator();
3381
3382 int inner = -1;
3383 bool hasIndirection = false;
3384 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
3385 DeclaratorChunk &chunk = D.getTypeObject(i);
3386 switch (chunk.Kind) {
3387 case DeclaratorChunk::Paren:
3388 // Ignore parens.
3389 break;
3390
3391 case DeclaratorChunk::Array:
3392 case DeclaratorChunk::Reference:
3393 case DeclaratorChunk::Pointer:
3394 if (inner != -1)
3395 hasIndirection = true;
3396 inner = i;
3397 break;
3398
3399 case DeclaratorChunk::BlockPointer:
3400 if (inner != -1)
3401 transferARCOwnershipToDeclaratorChunk(state, ownership, i);
3402 return;
3403
3404 case DeclaratorChunk::Function:
3405 case DeclaratorChunk::MemberPointer:
3406 return;
3407 }
3408 }
3409
3410 if (inner == -1)
3411 return;
3412
3413 DeclaratorChunk &chunk = D.getTypeObject(inner);
3414 if (chunk.Kind == DeclaratorChunk::Pointer) {
3415 if (declSpecTy->isObjCRetainableType())
3416 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
3417 if (declSpecTy->isObjCObjectType() && hasIndirection)
3418 return transferARCOwnershipToDeclaratorChunk(state, ownership, inner);
3419 } else {
3420 assert(chunk.Kind == DeclaratorChunk::Array ||
3421 chunk.Kind == DeclaratorChunk::Reference);
3422 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
3423 }
3424 }
3425
GetTypeForDeclaratorCast(Declarator & D,QualType FromTy)3426 TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) {
3427 TypeProcessingState state(*this, D);
3428
3429 TypeSourceInfo *ReturnTypeInfo = nullptr;
3430 QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
3431
3432 if (getLangOpts().ObjCAutoRefCount) {
3433 Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy);
3434 if (ownership != Qualifiers::OCL_None)
3435 transferARCOwnership(state, declSpecTy, ownership);
3436 }
3437
3438 return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo);
3439 }
3440
3441 /// Map an AttributedType::Kind to an AttributeList::Kind.
getAttrListKind(AttributedType::Kind kind)3442 static AttributeList::Kind getAttrListKind(AttributedType::Kind kind) {
3443 switch (kind) {
3444 case AttributedType::attr_address_space:
3445 return AttributeList::AT_AddressSpace;
3446 case AttributedType::attr_regparm:
3447 return AttributeList::AT_Regparm;
3448 case AttributedType::attr_vector_size:
3449 return AttributeList::AT_VectorSize;
3450 case AttributedType::attr_neon_vector_type:
3451 return AttributeList::AT_NeonVectorType;
3452 case AttributedType::attr_neon_polyvector_type:
3453 return AttributeList::AT_NeonPolyVectorType;
3454 case AttributedType::attr_objc_gc:
3455 return AttributeList::AT_ObjCGC;
3456 case AttributedType::attr_objc_ownership:
3457 return AttributeList::AT_ObjCOwnership;
3458 case AttributedType::attr_noreturn:
3459 return AttributeList::AT_NoReturn;
3460 case AttributedType::attr_cdecl:
3461 return AttributeList::AT_CDecl;
3462 case AttributedType::attr_fastcall:
3463 return AttributeList::AT_FastCall;
3464 case AttributedType::attr_stdcall:
3465 return AttributeList::AT_StdCall;
3466 case AttributedType::attr_thiscall:
3467 return AttributeList::AT_ThisCall;
3468 case AttributedType::attr_pascal:
3469 return AttributeList::AT_Pascal;
3470 case AttributedType::attr_vectorcall:
3471 return AttributeList::AT_VectorCall;
3472 case AttributedType::attr_pcs:
3473 case AttributedType::attr_pcs_vfp:
3474 return AttributeList::AT_Pcs;
3475 case AttributedType::attr_inteloclbicc:
3476 return AttributeList::AT_IntelOclBicc;
3477 case AttributedType::attr_ms_abi:
3478 return AttributeList::AT_MSABI;
3479 case AttributedType::attr_sysv_abi:
3480 return AttributeList::AT_SysVABI;
3481 case AttributedType::attr_ptr32:
3482 return AttributeList::AT_Ptr32;
3483 case AttributedType::attr_ptr64:
3484 return AttributeList::AT_Ptr64;
3485 case AttributedType::attr_sptr:
3486 return AttributeList::AT_SPtr;
3487 case AttributedType::attr_uptr:
3488 return AttributeList::AT_UPtr;
3489 }
3490 llvm_unreachable("unexpected attribute kind!");
3491 }
3492
fillAttributedTypeLoc(AttributedTypeLoc TL,const AttributeList * attrs)3493 static void fillAttributedTypeLoc(AttributedTypeLoc TL,
3494 const AttributeList *attrs) {
3495 AttributedType::Kind kind = TL.getAttrKind();
3496
3497 assert(attrs && "no type attributes in the expected location!");
3498 AttributeList::Kind parsedKind = getAttrListKind(kind);
3499 while (attrs->getKind() != parsedKind) {
3500 attrs = attrs->getNext();
3501 assert(attrs && "no matching attribute in expected location!");
3502 }
3503
3504 TL.setAttrNameLoc(attrs->getLoc());
3505 if (TL.hasAttrExprOperand()) {
3506 assert(attrs->isArgExpr(0) && "mismatched attribute operand kind");
3507 TL.setAttrExprOperand(attrs->getArgAsExpr(0));
3508 } else if (TL.hasAttrEnumOperand()) {
3509 assert((attrs->isArgIdent(0) || attrs->isArgExpr(0)) &&
3510 "unexpected attribute operand kind");
3511 if (attrs->isArgIdent(0))
3512 TL.setAttrEnumOperandLoc(attrs->getArgAsIdent(0)->Loc);
3513 else
3514 TL.setAttrEnumOperandLoc(attrs->getArgAsExpr(0)->getExprLoc());
3515 }
3516
3517 // FIXME: preserve this information to here.
3518 if (TL.hasAttrOperand())
3519 TL.setAttrOperandParensRange(SourceRange());
3520 }
3521
3522 namespace {
3523 class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
3524 ASTContext &Context;
3525 const DeclSpec &DS;
3526
3527 public:
TypeSpecLocFiller(ASTContext & Context,const DeclSpec & DS)3528 TypeSpecLocFiller(ASTContext &Context, const DeclSpec &DS)
3529 : Context(Context), DS(DS) {}
3530
VisitAttributedTypeLoc(AttributedTypeLoc TL)3531 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
3532 fillAttributedTypeLoc(TL, DS.getAttributes().getList());
3533 Visit(TL.getModifiedLoc());
3534 }
VisitQualifiedTypeLoc(QualifiedTypeLoc TL)3535 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
3536 Visit(TL.getUnqualifiedLoc());
3537 }
VisitTypedefTypeLoc(TypedefTypeLoc TL)3538 void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
3539 TL.setNameLoc(DS.getTypeSpecTypeLoc());
3540 }
VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL)3541 void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
3542 TL.setNameLoc(DS.getTypeSpecTypeLoc());
3543 // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires
3544 // addition field. What we have is good enough for dispay of location
3545 // of 'fixit' on interface name.
3546 TL.setNameEndLoc(DS.getLocEnd());
3547 }
VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL)3548 void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
3549 // Handle the base type, which might not have been written explicitly.
3550 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
3551 TL.setHasBaseTypeAsWritten(false);
3552 TL.getBaseLoc().initialize(Context, SourceLocation());
3553 } else {
3554 TL.setHasBaseTypeAsWritten(true);
3555 Visit(TL.getBaseLoc());
3556 }
3557
3558 // Protocol qualifiers.
3559 if (DS.getProtocolQualifiers()) {
3560 assert(TL.getNumProtocols() > 0);
3561 assert(TL.getNumProtocols() == DS.getNumProtocolQualifiers());
3562 TL.setLAngleLoc(DS.getProtocolLAngleLoc());
3563 TL.setRAngleLoc(DS.getSourceRange().getEnd());
3564 for (unsigned i = 0, e = DS.getNumProtocolQualifiers(); i != e; ++i)
3565 TL.setProtocolLoc(i, DS.getProtocolLocs()[i]);
3566 } else {
3567 assert(TL.getNumProtocols() == 0);
3568 TL.setLAngleLoc(SourceLocation());
3569 TL.setRAngleLoc(SourceLocation());
3570 }
3571 }
VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL)3572 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
3573 TL.setStarLoc(SourceLocation());
3574 Visit(TL.getPointeeLoc());
3575 }
VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL)3576 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
3577 TypeSourceInfo *TInfo = nullptr;
3578 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
3579
3580 // If we got no declarator info from previous Sema routines,
3581 // just fill with the typespec loc.
3582 if (!TInfo) {
3583 TL.initialize(Context, DS.getTypeSpecTypeNameLoc());
3584 return;
3585 }
3586
3587 TypeLoc OldTL = TInfo->getTypeLoc();
3588 if (TInfo->getType()->getAs<ElaboratedType>()) {
3589 ElaboratedTypeLoc ElabTL = OldTL.castAs<ElaboratedTypeLoc>();
3590 TemplateSpecializationTypeLoc NamedTL = ElabTL.getNamedTypeLoc()
3591 .castAs<TemplateSpecializationTypeLoc>();
3592 TL.copy(NamedTL);
3593 } else {
3594 TL.copy(OldTL.castAs<TemplateSpecializationTypeLoc>());
3595 assert(TL.getRAngleLoc() == OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc());
3596 }
3597
3598 }
VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL)3599 void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
3600 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr);
3601 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
3602 TL.setParensRange(DS.getTypeofParensRange());
3603 }
VisitTypeOfTypeLoc(TypeOfTypeLoc TL)3604 void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
3605 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType);
3606 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
3607 TL.setParensRange(DS.getTypeofParensRange());
3608 assert(DS.getRepAsType());
3609 TypeSourceInfo *TInfo = nullptr;
3610 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
3611 TL.setUnderlyingTInfo(TInfo);
3612 }
VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL)3613 void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
3614 // FIXME: This holds only because we only have one unary transform.
3615 assert(DS.getTypeSpecType() == DeclSpec::TST_underlyingType);
3616 TL.setKWLoc(DS.getTypeSpecTypeLoc());
3617 TL.setParensRange(DS.getTypeofParensRange());
3618 assert(DS.getRepAsType());
3619 TypeSourceInfo *TInfo = nullptr;
3620 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
3621 TL.setUnderlyingTInfo(TInfo);
3622 }
VisitBuiltinTypeLoc(BuiltinTypeLoc TL)3623 void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
3624 // By default, use the source location of the type specifier.
3625 TL.setBuiltinLoc(DS.getTypeSpecTypeLoc());
3626 if (TL.needsExtraLocalData()) {
3627 // Set info for the written builtin specifiers.
3628 TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs();
3629 // Try to have a meaningful source location.
3630 if (TL.getWrittenSignSpec() != TSS_unspecified)
3631 // Sign spec loc overrides the others (e.g., 'unsigned long').
3632 TL.setBuiltinLoc(DS.getTypeSpecSignLoc());
3633 else if (TL.getWrittenWidthSpec() != TSW_unspecified)
3634 // Width spec loc overrides type spec loc (e.g., 'short int').
3635 TL.setBuiltinLoc(DS.getTypeSpecWidthLoc());
3636 }
3637 }
VisitElaboratedTypeLoc(ElaboratedTypeLoc TL)3638 void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
3639 ElaboratedTypeKeyword Keyword
3640 = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
3641 if (DS.getTypeSpecType() == TST_typename) {
3642 TypeSourceInfo *TInfo = nullptr;
3643 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
3644 if (TInfo) {
3645 TL.copy(TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>());
3646 return;
3647 }
3648 }
3649 TL.setElaboratedKeywordLoc(Keyword != ETK_None
3650 ? DS.getTypeSpecTypeLoc()
3651 : SourceLocation());
3652 const CXXScopeSpec& SS = DS.getTypeSpecScope();
3653 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3654 Visit(TL.getNextTypeLoc().getUnqualifiedLoc());
3655 }
VisitDependentNameTypeLoc(DependentNameTypeLoc TL)3656 void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
3657 assert(DS.getTypeSpecType() == TST_typename);
3658 TypeSourceInfo *TInfo = nullptr;
3659 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
3660 assert(TInfo);
3661 TL.copy(TInfo->getTypeLoc().castAs<DependentNameTypeLoc>());
3662 }
VisitDependentTemplateSpecializationTypeLoc(DependentTemplateSpecializationTypeLoc TL)3663 void VisitDependentTemplateSpecializationTypeLoc(
3664 DependentTemplateSpecializationTypeLoc TL) {
3665 assert(DS.getTypeSpecType() == TST_typename);
3666 TypeSourceInfo *TInfo = nullptr;
3667 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
3668 assert(TInfo);
3669 TL.copy(
3670 TInfo->getTypeLoc().castAs<DependentTemplateSpecializationTypeLoc>());
3671 }
VisitTagTypeLoc(TagTypeLoc TL)3672 void VisitTagTypeLoc(TagTypeLoc TL) {
3673 TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
3674 }
VisitAtomicTypeLoc(AtomicTypeLoc TL)3675 void VisitAtomicTypeLoc(AtomicTypeLoc TL) {
3676 // An AtomicTypeLoc can come from either an _Atomic(...) type specifier
3677 // or an _Atomic qualifier.
3678 if (DS.getTypeSpecType() == DeclSpec::TST_atomic) {
3679 TL.setKWLoc(DS.getTypeSpecTypeLoc());
3680 TL.setParensRange(DS.getTypeofParensRange());
3681
3682 TypeSourceInfo *TInfo = nullptr;
3683 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
3684 assert(TInfo);
3685 TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
3686 } else {
3687 TL.setKWLoc(DS.getAtomicSpecLoc());
3688 // No parens, to indicate this was spelled as an _Atomic qualifier.
3689 TL.setParensRange(SourceRange());
3690 Visit(TL.getValueLoc());
3691 }
3692 }
3693
VisitTypeLoc(TypeLoc TL)3694 void VisitTypeLoc(TypeLoc TL) {
3695 // FIXME: add other typespec types and change this to an assert.
3696 TL.initialize(Context, DS.getTypeSpecTypeLoc());
3697 }
3698 };
3699
3700 class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
3701 ASTContext &Context;
3702 const DeclaratorChunk &Chunk;
3703
3704 public:
DeclaratorLocFiller(ASTContext & Context,const DeclaratorChunk & Chunk)3705 DeclaratorLocFiller(ASTContext &Context, const DeclaratorChunk &Chunk)
3706 : Context(Context), Chunk(Chunk) {}
3707
VisitQualifiedTypeLoc(QualifiedTypeLoc TL)3708 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
3709 llvm_unreachable("qualified type locs not expected here!");
3710 }
VisitDecayedTypeLoc(DecayedTypeLoc TL)3711 void VisitDecayedTypeLoc(DecayedTypeLoc TL) {
3712 llvm_unreachable("decayed type locs not expected here!");
3713 }
3714
VisitAttributedTypeLoc(AttributedTypeLoc TL)3715 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
3716 fillAttributedTypeLoc(TL, Chunk.getAttrs());
3717 }
VisitAdjustedTypeLoc(AdjustedTypeLoc TL)3718 void VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
3719 // nothing
3720 }
VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL)3721 void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
3722 assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
3723 TL.setCaretLoc(Chunk.Loc);
3724 }
VisitPointerTypeLoc(PointerTypeLoc TL)3725 void VisitPointerTypeLoc(PointerTypeLoc TL) {
3726 assert(Chunk.Kind == DeclaratorChunk::Pointer);
3727 TL.setStarLoc(Chunk.Loc);
3728 }
VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL)3729 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
3730 assert(Chunk.Kind == DeclaratorChunk::Pointer);
3731 TL.setStarLoc(Chunk.Loc);
3732 }
VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL)3733 void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
3734 assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
3735 const CXXScopeSpec& SS = Chunk.Mem.Scope();
3736 NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context);
3737
3738 const Type* ClsTy = TL.getClass();
3739 QualType ClsQT = QualType(ClsTy, 0);
3740 TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0);
3741 // Now copy source location info into the type loc component.
3742 TypeLoc ClsTL = ClsTInfo->getTypeLoc();
3743 switch (NNSLoc.getNestedNameSpecifier()->getKind()) {
3744 case NestedNameSpecifier::Identifier:
3745 assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc");
3746 {
3747 DependentNameTypeLoc DNTLoc = ClsTL.castAs<DependentNameTypeLoc>();
3748 DNTLoc.setElaboratedKeywordLoc(SourceLocation());
3749 DNTLoc.setQualifierLoc(NNSLoc.getPrefix());
3750 DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc());
3751 }
3752 break;
3753
3754 case NestedNameSpecifier::TypeSpec:
3755 case NestedNameSpecifier::TypeSpecWithTemplate:
3756 if (isa<ElaboratedType>(ClsTy)) {
3757 ElaboratedTypeLoc ETLoc = ClsTL.castAs<ElaboratedTypeLoc>();
3758 ETLoc.setElaboratedKeywordLoc(SourceLocation());
3759 ETLoc.setQualifierLoc(NNSLoc.getPrefix());
3760 TypeLoc NamedTL = ETLoc.getNamedTypeLoc();
3761 NamedTL.initializeFullCopy(NNSLoc.getTypeLoc());
3762 } else {
3763 ClsTL.initializeFullCopy(NNSLoc.getTypeLoc());
3764 }
3765 break;
3766
3767 case NestedNameSpecifier::Namespace:
3768 case NestedNameSpecifier::NamespaceAlias:
3769 case NestedNameSpecifier::Global:
3770 case NestedNameSpecifier::Super:
3771 llvm_unreachable("Nested-name-specifier must name a type");
3772 }
3773
3774 // Finally fill in MemberPointerLocInfo fields.
3775 TL.setStarLoc(Chunk.Loc);
3776 TL.setClassTInfo(ClsTInfo);
3777 }
VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL)3778 void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
3779 assert(Chunk.Kind == DeclaratorChunk::Reference);
3780 // 'Amp' is misleading: this might have been originally
3781 /// spelled with AmpAmp.
3782 TL.setAmpLoc(Chunk.Loc);
3783 }
VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL)3784 void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
3785 assert(Chunk.Kind == DeclaratorChunk::Reference);
3786 assert(!Chunk.Ref.LValueRef);
3787 TL.setAmpAmpLoc(Chunk.Loc);
3788 }
VisitArrayTypeLoc(ArrayTypeLoc TL)3789 void VisitArrayTypeLoc(ArrayTypeLoc TL) {
3790 assert(Chunk.Kind == DeclaratorChunk::Array);
3791 TL.setLBracketLoc(Chunk.Loc);
3792 TL.setRBracketLoc(Chunk.EndLoc);
3793 TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
3794 }
VisitFunctionTypeLoc(FunctionTypeLoc TL)3795 void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
3796 assert(Chunk.Kind == DeclaratorChunk::Function);
3797 TL.setLocalRangeBegin(Chunk.Loc);
3798 TL.setLocalRangeEnd(Chunk.EndLoc);
3799
3800 const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
3801 TL.setLParenLoc(FTI.getLParenLoc());
3802 TL.setRParenLoc(FTI.getRParenLoc());
3803 for (unsigned i = 0, e = TL.getNumParams(), tpi = 0; i != e; ++i) {
3804 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
3805 TL.setParam(tpi++, Param);
3806 }
3807 // FIXME: exception specs
3808 }
VisitParenTypeLoc(ParenTypeLoc TL)3809 void VisitParenTypeLoc(ParenTypeLoc TL) {
3810 assert(Chunk.Kind == DeclaratorChunk::Paren);
3811 TL.setLParenLoc(Chunk.Loc);
3812 TL.setRParenLoc(Chunk.EndLoc);
3813 }
3814
VisitTypeLoc(TypeLoc TL)3815 void VisitTypeLoc(TypeLoc TL) {
3816 llvm_unreachable("unsupported TypeLoc kind in declarator!");
3817 }
3818 };
3819 }
3820
fillAtomicQualLoc(AtomicTypeLoc ATL,const DeclaratorChunk & Chunk)3821 static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk) {
3822 SourceLocation Loc;
3823 switch (Chunk.Kind) {
3824 case DeclaratorChunk::Function:
3825 case DeclaratorChunk::Array:
3826 case DeclaratorChunk::Paren:
3827 llvm_unreachable("cannot be _Atomic qualified");
3828
3829 case DeclaratorChunk::Pointer:
3830 Loc = SourceLocation::getFromRawEncoding(Chunk.Ptr.AtomicQualLoc);
3831 break;
3832
3833 case DeclaratorChunk::BlockPointer:
3834 case DeclaratorChunk::Reference:
3835 case DeclaratorChunk::MemberPointer:
3836 // FIXME: Provide a source location for the _Atomic keyword.
3837 break;
3838 }
3839
3840 ATL.setKWLoc(Loc);
3841 ATL.setParensRange(SourceRange());
3842 }
3843
3844 /// \brief Create and instantiate a TypeSourceInfo with type source information.
3845 ///
3846 /// \param T QualType referring to the type as written in source code.
3847 ///
3848 /// \param ReturnTypeInfo For declarators whose return type does not show
3849 /// up in the normal place in the declaration specifiers (such as a C++
3850 /// conversion function), this pointer will refer to a type source information
3851 /// for that return type.
3852 TypeSourceInfo *
GetTypeSourceInfoForDeclarator(Declarator & D,QualType T,TypeSourceInfo * ReturnTypeInfo)3853 Sema::GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
3854 TypeSourceInfo *ReturnTypeInfo) {
3855 TypeSourceInfo *TInfo = Context.CreateTypeSourceInfo(T);
3856 UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc();
3857
3858 // Handle parameter packs whose type is a pack expansion.
3859 if (isa<PackExpansionType>(T)) {
3860 CurrTL.castAs<PackExpansionTypeLoc>().setEllipsisLoc(D.getEllipsisLoc());
3861 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
3862 }
3863
3864 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
3865 // An AtomicTypeLoc might be produced by an atomic qualifier in this
3866 // declarator chunk.
3867 if (AtomicTypeLoc ATL = CurrTL.getAs<AtomicTypeLoc>()) {
3868 fillAtomicQualLoc(ATL, D.getTypeObject(i));
3869 CurrTL = ATL.getValueLoc().getUnqualifiedLoc();
3870 }
3871
3872 while (AttributedTypeLoc TL = CurrTL.getAs<AttributedTypeLoc>()) {
3873 fillAttributedTypeLoc(TL, D.getTypeObject(i).getAttrs());
3874 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
3875 }
3876
3877 // FIXME: Ordering here?
3878 while (AdjustedTypeLoc TL = CurrTL.getAs<AdjustedTypeLoc>())
3879 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
3880
3881 DeclaratorLocFiller(Context, D.getTypeObject(i)).Visit(CurrTL);
3882 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
3883 }
3884
3885 // If we have different source information for the return type, use
3886 // that. This really only applies to C++ conversion functions.
3887 if (ReturnTypeInfo) {
3888 TypeLoc TL = ReturnTypeInfo->getTypeLoc();
3889 assert(TL.getFullDataSize() == CurrTL.getFullDataSize());
3890 memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize());
3891 } else {
3892 TypeSpecLocFiller(Context, D.getDeclSpec()).Visit(CurrTL);
3893 }
3894
3895 return TInfo;
3896 }
3897
3898 /// \brief Create a LocInfoType to hold the given QualType and TypeSourceInfo.
CreateParsedType(QualType T,TypeSourceInfo * TInfo)3899 ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) {
3900 // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
3901 // and Sema during declaration parsing. Try deallocating/caching them when
3902 // it's appropriate, instead of allocating them and keeping them around.
3903 LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType),
3904 TypeAlignment);
3905 new (LocT) LocInfoType(T, TInfo);
3906 assert(LocT->getTypeClass() != T->getTypeClass() &&
3907 "LocInfoType's TypeClass conflicts with an existing Type class");
3908 return ParsedType::make(QualType(LocT, 0));
3909 }
3910
getAsStringInternal(std::string & Str,const PrintingPolicy & Policy) const3911 void LocInfoType::getAsStringInternal(std::string &Str,
3912 const PrintingPolicy &Policy) const {
3913 llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*"
3914 " was used directly instead of getting the QualType through"
3915 " GetTypeFromParser");
3916 }
3917
ActOnTypeName(Scope * S,Declarator & D)3918 TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
3919 // C99 6.7.6: Type names have no identifier. This is already validated by
3920 // the parser.
3921 assert(D.getIdentifier() == nullptr &&
3922 "Type name should have no identifier!");
3923
3924 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
3925 QualType T = TInfo->getType();
3926 if (D.isInvalidType())
3927 return true;
3928
3929 // Make sure there are no unused decl attributes on the declarator.
3930 // We don't want to do this for ObjC parameters because we're going
3931 // to apply them to the actual parameter declaration.
3932 // Likewise, we don't want to do this for alias declarations, because
3933 // we are actually going to build a declaration from this eventually.
3934 if (D.getContext() != Declarator::ObjCParameterContext &&
3935 D.getContext() != Declarator::AliasDeclContext &&
3936 D.getContext() != Declarator::AliasTemplateContext)
3937 checkUnusedDeclAttributes(D);
3938
3939 if (getLangOpts().CPlusPlus) {
3940 // Check that there are no default arguments (C++ only).
3941 CheckExtraCXXDefaultArguments(D);
3942 }
3943
3944 return CreateParsedType(T, TInfo);
3945 }
3946
ActOnObjCInstanceType(SourceLocation Loc)3947 ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) {
3948 QualType T = Context.getObjCInstanceType();
3949 TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
3950 return CreateParsedType(T, TInfo);
3951 }
3952
3953
3954 //===----------------------------------------------------------------------===//
3955 // Type Attribute Processing
3956 //===----------------------------------------------------------------------===//
3957
3958 /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
3959 /// specified type. The attribute contains 1 argument, the id of the address
3960 /// space for the type.
HandleAddressSpaceTypeAttribute(QualType & Type,const AttributeList & Attr,Sema & S)3961 static void HandleAddressSpaceTypeAttribute(QualType &Type,
3962 const AttributeList &Attr, Sema &S){
3963
3964 // If this type is already address space qualified, reject it.
3965 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified by
3966 // qualifiers for two or more different address spaces."
3967 if (Type.getAddressSpace()) {
3968 S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers);
3969 Attr.setInvalid();
3970 return;
3971 }
3972
3973 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be
3974 // qualified by an address-space qualifier."
3975 if (Type->isFunctionType()) {
3976 S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type);
3977 Attr.setInvalid();
3978 return;
3979 }
3980
3981 unsigned ASIdx;
3982 if (Attr.getKind() == AttributeList::AT_AddressSpace) {
3983 // Check the attribute arguments.
3984 if (Attr.getNumArgs() != 1) {
3985 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
3986 << Attr.getName() << 1;
3987 Attr.setInvalid();
3988 return;
3989 }
3990 Expr *ASArgExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
3991 llvm::APSInt addrSpace(32);
3992 if (ASArgExpr->isTypeDependent() || ASArgExpr->isValueDependent() ||
3993 !ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) {
3994 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
3995 << Attr.getName() << AANT_ArgumentIntegerConstant
3996 << ASArgExpr->getSourceRange();
3997 Attr.setInvalid();
3998 return;
3999 }
4000
4001 // Bounds checking.
4002 if (addrSpace.isSigned()) {
4003 if (addrSpace.isNegative()) {
4004 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_negative)
4005 << ASArgExpr->getSourceRange();
4006 Attr.setInvalid();
4007 return;
4008 }
4009 addrSpace.setIsSigned(false);
4010 }
4011 llvm::APSInt max(addrSpace.getBitWidth());
4012 max = Qualifiers::MaxAddressSpace;
4013 if (addrSpace > max) {
4014 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_too_high)
4015 << int(Qualifiers::MaxAddressSpace) << ASArgExpr->getSourceRange();
4016 Attr.setInvalid();
4017 return;
4018 }
4019 ASIdx = static_cast<unsigned>(addrSpace.getZExtValue());
4020 } else {
4021 // The keyword-based type attributes imply which address space to use.
4022 switch (Attr.getKind()) {
4023 case AttributeList::AT_OpenCLGlobalAddressSpace:
4024 ASIdx = LangAS::opencl_global; break;
4025 case AttributeList::AT_OpenCLLocalAddressSpace:
4026 ASIdx = LangAS::opencl_local; break;
4027 case AttributeList::AT_OpenCLConstantAddressSpace:
4028 ASIdx = LangAS::opencl_constant; break;
4029 case AttributeList::AT_OpenCLGenericAddressSpace:
4030 ASIdx = LangAS::opencl_generic; break;
4031 default:
4032 assert(Attr.getKind() == AttributeList::AT_OpenCLPrivateAddressSpace);
4033 ASIdx = 0; break;
4034 }
4035 }
4036
4037 Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
4038 }
4039
4040 /// Does this type have a "direct" ownership qualifier? That is,
4041 /// is it written like "__strong id", as opposed to something like
4042 /// "typeof(foo)", where that happens to be strong?
hasDirectOwnershipQualifier(QualType type)4043 static bool hasDirectOwnershipQualifier(QualType type) {
4044 // Fast path: no qualifier at all.
4045 assert(type.getQualifiers().hasObjCLifetime());
4046
4047 while (true) {
4048 // __strong id
4049 if (const AttributedType *attr = dyn_cast<AttributedType>(type)) {
4050 if (attr->getAttrKind() == AttributedType::attr_objc_ownership)
4051 return true;
4052
4053 type = attr->getModifiedType();
4054
4055 // X *__strong (...)
4056 } else if (const ParenType *paren = dyn_cast<ParenType>(type)) {
4057 type = paren->getInnerType();
4058
4059 // That's it for things we want to complain about. In particular,
4060 // we do not want to look through typedefs, typeof(expr),
4061 // typeof(type), or any other way that the type is somehow
4062 // abstracted.
4063 } else {
4064
4065 return false;
4066 }
4067 }
4068 }
4069
4070 /// handleObjCOwnershipTypeAttr - Process an objc_ownership
4071 /// attribute on the specified type.
4072 ///
4073 /// Returns 'true' if the attribute was handled.
handleObjCOwnershipTypeAttr(TypeProcessingState & state,AttributeList & attr,QualType & type)4074 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
4075 AttributeList &attr,
4076 QualType &type) {
4077 bool NonObjCPointer = false;
4078
4079 if (!type->isDependentType() && !type->isUndeducedType()) {
4080 if (const PointerType *ptr = type->getAs<PointerType>()) {
4081 QualType pointee = ptr->getPointeeType();
4082 if (pointee->isObjCRetainableType() || pointee->isPointerType())
4083 return false;
4084 // It is important not to lose the source info that there was an attribute
4085 // applied to non-objc pointer. We will create an attributed type but
4086 // its type will be the same as the original type.
4087 NonObjCPointer = true;
4088 } else if (!type->isObjCRetainableType()) {
4089 return false;
4090 }
4091
4092 // Don't accept an ownership attribute in the declspec if it would
4093 // just be the return type of a block pointer.
4094 if (state.isProcessingDeclSpec()) {
4095 Declarator &D = state.getDeclarator();
4096 if (maybeMovePastReturnType(D, D.getNumTypeObjects()))
4097 return false;
4098 }
4099 }
4100
4101 Sema &S = state.getSema();
4102 SourceLocation AttrLoc = attr.getLoc();
4103 if (AttrLoc.isMacroID())
4104 AttrLoc = S.getSourceManager().getImmediateExpansionRange(AttrLoc).first;
4105
4106 if (!attr.isArgIdent(0)) {
4107 S.Diag(AttrLoc, diag::err_attribute_argument_type)
4108 << attr.getName() << AANT_ArgumentString;
4109 attr.setInvalid();
4110 return true;
4111 }
4112
4113 // Consume lifetime attributes without further comment outside of
4114 // ARC mode.
4115 if (!S.getLangOpts().ObjCAutoRefCount)
4116 return true;
4117
4118 IdentifierInfo *II = attr.getArgAsIdent(0)->Ident;
4119 Qualifiers::ObjCLifetime lifetime;
4120 if (II->isStr("none"))
4121 lifetime = Qualifiers::OCL_ExplicitNone;
4122 else if (II->isStr("strong"))
4123 lifetime = Qualifiers::OCL_Strong;
4124 else if (II->isStr("weak"))
4125 lifetime = Qualifiers::OCL_Weak;
4126 else if (II->isStr("autoreleasing"))
4127 lifetime = Qualifiers::OCL_Autoreleasing;
4128 else {
4129 S.Diag(AttrLoc, diag::warn_attribute_type_not_supported)
4130 << attr.getName() << II;
4131 attr.setInvalid();
4132 return true;
4133 }
4134
4135 SplitQualType underlyingType = type.split();
4136
4137 // Check for redundant/conflicting ownership qualifiers.
4138 if (Qualifiers::ObjCLifetime previousLifetime
4139 = type.getQualifiers().getObjCLifetime()) {
4140 // If it's written directly, that's an error.
4141 if (hasDirectOwnershipQualifier(type)) {
4142 S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant)
4143 << type;
4144 return true;
4145 }
4146
4147 // Otherwise, if the qualifiers actually conflict, pull sugar off
4148 // until we reach a type that is directly qualified.
4149 if (previousLifetime != lifetime) {
4150 // This should always terminate: the canonical type is
4151 // qualified, so some bit of sugar must be hiding it.
4152 while (!underlyingType.Quals.hasObjCLifetime()) {
4153 underlyingType = underlyingType.getSingleStepDesugaredType();
4154 }
4155 underlyingType.Quals.removeObjCLifetime();
4156 }
4157 }
4158
4159 underlyingType.Quals.addObjCLifetime(lifetime);
4160
4161 if (NonObjCPointer) {
4162 StringRef name = attr.getName()->getName();
4163 switch (lifetime) {
4164 case Qualifiers::OCL_None:
4165 case Qualifiers::OCL_ExplicitNone:
4166 break;
4167 case Qualifiers::OCL_Strong: name = "__strong"; break;
4168 case Qualifiers::OCL_Weak: name = "__weak"; break;
4169 case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break;
4170 }
4171 S.Diag(AttrLoc, diag::warn_type_attribute_wrong_type) << name
4172 << TDS_ObjCObjOrBlock << type;
4173 }
4174
4175 QualType origType = type;
4176 if (!NonObjCPointer)
4177 type = S.Context.getQualifiedType(underlyingType);
4178
4179 // If we have a valid source location for the attribute, use an
4180 // AttributedType instead.
4181 if (AttrLoc.isValid())
4182 type = S.Context.getAttributedType(AttributedType::attr_objc_ownership,
4183 origType, type);
4184
4185 // Forbid __weak if the runtime doesn't support it.
4186 if (lifetime == Qualifiers::OCL_Weak &&
4187 !S.getLangOpts().ObjCARCWeak && !NonObjCPointer) {
4188
4189 // Actually, delay this until we know what we're parsing.
4190 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
4191 S.DelayedDiagnostics.add(
4192 sema::DelayedDiagnostic::makeForbiddenType(
4193 S.getSourceManager().getExpansionLoc(AttrLoc),
4194 diag::err_arc_weak_no_runtime, type, /*ignored*/ 0));
4195 } else {
4196 S.Diag(AttrLoc, diag::err_arc_weak_no_runtime);
4197 }
4198
4199 attr.setInvalid();
4200 return true;
4201 }
4202
4203 // Forbid __weak for class objects marked as
4204 // objc_arc_weak_reference_unavailable
4205 if (lifetime == Qualifiers::OCL_Weak) {
4206 if (const ObjCObjectPointerType *ObjT =
4207 type->getAs<ObjCObjectPointerType>()) {
4208 if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) {
4209 if (Class->isArcWeakrefUnavailable()) {
4210 S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class);
4211 S.Diag(ObjT->getInterfaceDecl()->getLocation(),
4212 diag::note_class_declared);
4213 }
4214 }
4215 }
4216 }
4217
4218 return true;
4219 }
4220
4221 /// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type
4222 /// attribute on the specified type. Returns true to indicate that
4223 /// the attribute was handled, false to indicate that the type does
4224 /// not permit the attribute.
handleObjCGCTypeAttr(TypeProcessingState & state,AttributeList & attr,QualType & type)4225 static bool handleObjCGCTypeAttr(TypeProcessingState &state,
4226 AttributeList &attr,
4227 QualType &type) {
4228 Sema &S = state.getSema();
4229
4230 // Delay if this isn't some kind of pointer.
4231 if (!type->isPointerType() &&
4232 !type->isObjCObjectPointerType() &&
4233 !type->isBlockPointerType())
4234 return false;
4235
4236 if (type.getObjCGCAttr() != Qualifiers::GCNone) {
4237 S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc);
4238 attr.setInvalid();
4239 return true;
4240 }
4241
4242 // Check the attribute arguments.
4243 if (!attr.isArgIdent(0)) {
4244 S.Diag(attr.getLoc(), diag::err_attribute_argument_type)
4245 << attr.getName() << AANT_ArgumentString;
4246 attr.setInvalid();
4247 return true;
4248 }
4249 Qualifiers::GC GCAttr;
4250 if (attr.getNumArgs() > 1) {
4251 S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments)
4252 << attr.getName() << 1;
4253 attr.setInvalid();
4254 return true;
4255 }
4256
4257 IdentifierInfo *II = attr.getArgAsIdent(0)->Ident;
4258 if (II->isStr("weak"))
4259 GCAttr = Qualifiers::Weak;
4260 else if (II->isStr("strong"))
4261 GCAttr = Qualifiers::Strong;
4262 else {
4263 S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported)
4264 << attr.getName() << II;
4265 attr.setInvalid();
4266 return true;
4267 }
4268
4269 QualType origType = type;
4270 type = S.Context.getObjCGCQualType(origType, GCAttr);
4271
4272 // Make an attributed type to preserve the source information.
4273 if (attr.getLoc().isValid())
4274 type = S.Context.getAttributedType(AttributedType::attr_objc_gc,
4275 origType, type);
4276
4277 return true;
4278 }
4279
4280 namespace {
4281 /// A helper class to unwrap a type down to a function for the
4282 /// purposes of applying attributes there.
4283 ///
4284 /// Use:
4285 /// FunctionTypeUnwrapper unwrapped(SemaRef, T);
4286 /// if (unwrapped.isFunctionType()) {
4287 /// const FunctionType *fn = unwrapped.get();
4288 /// // change fn somehow
4289 /// T = unwrapped.wrap(fn);
4290 /// }
4291 struct FunctionTypeUnwrapper {
4292 enum WrapKind {
4293 Desugar,
4294 Parens,
4295 Pointer,
4296 BlockPointer,
4297 Reference,
4298 MemberPointer
4299 };
4300
4301 QualType Original;
4302 const FunctionType *Fn;
4303 SmallVector<unsigned char /*WrapKind*/, 8> Stack;
4304
FunctionTypeUnwrapper__anon9acaebf90411::FunctionTypeUnwrapper4305 FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) {
4306 while (true) {
4307 const Type *Ty = T.getTypePtr();
4308 if (isa<FunctionType>(Ty)) {
4309 Fn = cast<FunctionType>(Ty);
4310 return;
4311 } else if (isa<ParenType>(Ty)) {
4312 T = cast<ParenType>(Ty)->getInnerType();
4313 Stack.push_back(Parens);
4314 } else if (isa<PointerType>(Ty)) {
4315 T = cast<PointerType>(Ty)->getPointeeType();
4316 Stack.push_back(Pointer);
4317 } else if (isa<BlockPointerType>(Ty)) {
4318 T = cast<BlockPointerType>(Ty)->getPointeeType();
4319 Stack.push_back(BlockPointer);
4320 } else if (isa<MemberPointerType>(Ty)) {
4321 T = cast<MemberPointerType>(Ty)->getPointeeType();
4322 Stack.push_back(MemberPointer);
4323 } else if (isa<ReferenceType>(Ty)) {
4324 T = cast<ReferenceType>(Ty)->getPointeeType();
4325 Stack.push_back(Reference);
4326 } else {
4327 const Type *DTy = Ty->getUnqualifiedDesugaredType();
4328 if (Ty == DTy) {
4329 Fn = nullptr;
4330 return;
4331 }
4332
4333 T = QualType(DTy, 0);
4334 Stack.push_back(Desugar);
4335 }
4336 }
4337 }
4338
isFunctionType__anon9acaebf90411::FunctionTypeUnwrapper4339 bool isFunctionType() const { return (Fn != nullptr); }
get__anon9acaebf90411::FunctionTypeUnwrapper4340 const FunctionType *get() const { return Fn; }
4341
wrap__anon9acaebf90411::FunctionTypeUnwrapper4342 QualType wrap(Sema &S, const FunctionType *New) {
4343 // If T wasn't modified from the unwrapped type, do nothing.
4344 if (New == get()) return Original;
4345
4346 Fn = New;
4347 return wrap(S.Context, Original, 0);
4348 }
4349
4350 private:
wrap__anon9acaebf90411::FunctionTypeUnwrapper4351 QualType wrap(ASTContext &C, QualType Old, unsigned I) {
4352 if (I == Stack.size())
4353 return C.getQualifiedType(Fn, Old.getQualifiers());
4354
4355 // Build up the inner type, applying the qualifiers from the old
4356 // type to the new type.
4357 SplitQualType SplitOld = Old.split();
4358
4359 // As a special case, tail-recurse if there are no qualifiers.
4360 if (SplitOld.Quals.empty())
4361 return wrap(C, SplitOld.Ty, I);
4362 return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals);
4363 }
4364
wrap__anon9acaebf90411::FunctionTypeUnwrapper4365 QualType wrap(ASTContext &C, const Type *Old, unsigned I) {
4366 if (I == Stack.size()) return QualType(Fn, 0);
4367
4368 switch (static_cast<WrapKind>(Stack[I++])) {
4369 case Desugar:
4370 // This is the point at which we potentially lose source
4371 // information.
4372 return wrap(C, Old->getUnqualifiedDesugaredType(), I);
4373
4374 case Parens: {
4375 QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I);
4376 return C.getParenType(New);
4377 }
4378
4379 case Pointer: {
4380 QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I);
4381 return C.getPointerType(New);
4382 }
4383
4384 case BlockPointer: {
4385 QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I);
4386 return C.getBlockPointerType(New);
4387 }
4388
4389 case MemberPointer: {
4390 const MemberPointerType *OldMPT = cast<MemberPointerType>(Old);
4391 QualType New = wrap(C, OldMPT->getPointeeType(), I);
4392 return C.getMemberPointerType(New, OldMPT->getClass());
4393 }
4394
4395 case Reference: {
4396 const ReferenceType *OldRef = cast<ReferenceType>(Old);
4397 QualType New = wrap(C, OldRef->getPointeeType(), I);
4398 if (isa<LValueReferenceType>(OldRef))
4399 return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue());
4400 else
4401 return C.getRValueReferenceType(New);
4402 }
4403 }
4404
4405 llvm_unreachable("unknown wrapping kind");
4406 }
4407 };
4408 }
4409
handleMSPointerTypeQualifierAttr(TypeProcessingState & State,AttributeList & Attr,QualType & Type)4410 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &State,
4411 AttributeList &Attr,
4412 QualType &Type) {
4413 Sema &S = State.getSema();
4414
4415 AttributeList::Kind Kind = Attr.getKind();
4416 QualType Desugared = Type;
4417 const AttributedType *AT = dyn_cast<AttributedType>(Type);
4418 while (AT) {
4419 AttributedType::Kind CurAttrKind = AT->getAttrKind();
4420
4421 // You cannot specify duplicate type attributes, so if the attribute has
4422 // already been applied, flag it.
4423 if (getAttrListKind(CurAttrKind) == Kind) {
4424 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute_exact)
4425 << Attr.getName();
4426 return true;
4427 }
4428
4429 // You cannot have both __sptr and __uptr on the same type, nor can you
4430 // have __ptr32 and __ptr64.
4431 if ((CurAttrKind == AttributedType::attr_ptr32 &&
4432 Kind == AttributeList::AT_Ptr64) ||
4433 (CurAttrKind == AttributedType::attr_ptr64 &&
4434 Kind == AttributeList::AT_Ptr32)) {
4435 S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
4436 << "'__ptr32'" << "'__ptr64'";
4437 return true;
4438 } else if ((CurAttrKind == AttributedType::attr_sptr &&
4439 Kind == AttributeList::AT_UPtr) ||
4440 (CurAttrKind == AttributedType::attr_uptr &&
4441 Kind == AttributeList::AT_SPtr)) {
4442 S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
4443 << "'__sptr'" << "'__uptr'";
4444 return true;
4445 }
4446
4447 Desugared = AT->getEquivalentType();
4448 AT = dyn_cast<AttributedType>(Desugared);
4449 }
4450
4451 // Pointer type qualifiers can only operate on pointer types, but not
4452 // pointer-to-member types.
4453 if (!isa<PointerType>(Desugared)) {
4454 S.Diag(Attr.getLoc(), Type->isMemberPointerType() ?
4455 diag::err_attribute_no_member_pointers :
4456 diag::err_attribute_pointers_only) << Attr.getName();
4457 return true;
4458 }
4459
4460 AttributedType::Kind TAK;
4461 switch (Kind) {
4462 default: llvm_unreachable("Unknown attribute kind");
4463 case AttributeList::AT_Ptr32: TAK = AttributedType::attr_ptr32; break;
4464 case AttributeList::AT_Ptr64: TAK = AttributedType::attr_ptr64; break;
4465 case AttributeList::AT_SPtr: TAK = AttributedType::attr_sptr; break;
4466 case AttributeList::AT_UPtr: TAK = AttributedType::attr_uptr; break;
4467 }
4468
4469 Type = S.Context.getAttributedType(TAK, Type, Type);
4470 return false;
4471 }
4472
getCCTypeAttrKind(AttributeList & Attr)4473 static AttributedType::Kind getCCTypeAttrKind(AttributeList &Attr) {
4474 assert(!Attr.isInvalid());
4475 switch (Attr.getKind()) {
4476 default:
4477 llvm_unreachable("not a calling convention attribute");
4478 case AttributeList::AT_CDecl:
4479 return AttributedType::attr_cdecl;
4480 case AttributeList::AT_FastCall:
4481 return AttributedType::attr_fastcall;
4482 case AttributeList::AT_StdCall:
4483 return AttributedType::attr_stdcall;
4484 case AttributeList::AT_ThisCall:
4485 return AttributedType::attr_thiscall;
4486 case AttributeList::AT_Pascal:
4487 return AttributedType::attr_pascal;
4488 case AttributeList::AT_VectorCall:
4489 return AttributedType::attr_vectorcall;
4490 case AttributeList::AT_Pcs: {
4491 // The attribute may have had a fixit applied where we treated an
4492 // identifier as a string literal. The contents of the string are valid,
4493 // but the form may not be.
4494 StringRef Str;
4495 if (Attr.isArgExpr(0))
4496 Str = cast<StringLiteral>(Attr.getArgAsExpr(0))->getString();
4497 else
4498 Str = Attr.getArgAsIdent(0)->Ident->getName();
4499 return llvm::StringSwitch<AttributedType::Kind>(Str)
4500 .Case("aapcs", AttributedType::attr_pcs)
4501 .Case("aapcs-vfp", AttributedType::attr_pcs_vfp);
4502 }
4503 case AttributeList::AT_IntelOclBicc:
4504 return AttributedType::attr_inteloclbicc;
4505 case AttributeList::AT_MSABI:
4506 return AttributedType::attr_ms_abi;
4507 case AttributeList::AT_SysVABI:
4508 return AttributedType::attr_sysv_abi;
4509 }
4510 llvm_unreachable("unexpected attribute kind!");
4511 }
4512
4513 /// Process an individual function attribute. Returns true to
4514 /// indicate that the attribute was handled, false if it wasn't.
handleFunctionTypeAttr(TypeProcessingState & state,AttributeList & attr,QualType & type)4515 static bool handleFunctionTypeAttr(TypeProcessingState &state,
4516 AttributeList &attr,
4517 QualType &type) {
4518 Sema &S = state.getSema();
4519
4520 FunctionTypeUnwrapper unwrapped(S, type);
4521
4522 if (attr.getKind() == AttributeList::AT_NoReturn) {
4523 if (S.CheckNoReturnAttr(attr))
4524 return true;
4525
4526 // Delay if this is not a function type.
4527 if (!unwrapped.isFunctionType())
4528 return false;
4529
4530 // Otherwise we can process right away.
4531 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true);
4532 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
4533 return true;
4534 }
4535
4536 // ns_returns_retained is not always a type attribute, but if we got
4537 // here, we're treating it as one right now.
4538 if (attr.getKind() == AttributeList::AT_NSReturnsRetained) {
4539 assert(S.getLangOpts().ObjCAutoRefCount &&
4540 "ns_returns_retained treated as type attribute in non-ARC");
4541 if (attr.getNumArgs()) return true;
4542
4543 // Delay if this is not a function type.
4544 if (!unwrapped.isFunctionType())
4545 return false;
4546
4547 FunctionType::ExtInfo EI
4548 = unwrapped.get()->getExtInfo().withProducesResult(true);
4549 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
4550 return true;
4551 }
4552
4553 if (attr.getKind() == AttributeList::AT_Regparm) {
4554 unsigned value;
4555 if (S.CheckRegparmAttr(attr, value))
4556 return true;
4557
4558 // Delay if this is not a function type.
4559 if (!unwrapped.isFunctionType())
4560 return false;
4561
4562 // Diagnose regparm with fastcall.
4563 const FunctionType *fn = unwrapped.get();
4564 CallingConv CC = fn->getCallConv();
4565 if (CC == CC_X86FastCall) {
4566 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
4567 << FunctionType::getNameForCallConv(CC)
4568 << "regparm";
4569 attr.setInvalid();
4570 return true;
4571 }
4572
4573 FunctionType::ExtInfo EI =
4574 unwrapped.get()->getExtInfo().withRegParm(value);
4575 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
4576 return true;
4577 }
4578
4579 // Delay if the type didn't work out to a function.
4580 if (!unwrapped.isFunctionType()) return false;
4581
4582 // Otherwise, a calling convention.
4583 CallingConv CC;
4584 if (S.CheckCallingConvAttr(attr, CC))
4585 return true;
4586
4587 const FunctionType *fn = unwrapped.get();
4588 CallingConv CCOld = fn->getCallConv();
4589 AttributedType::Kind CCAttrKind = getCCTypeAttrKind(attr);
4590
4591 if (CCOld != CC) {
4592 // Error out on when there's already an attribute on the type
4593 // and the CCs don't match.
4594 const AttributedType *AT = S.getCallingConvAttributedType(type);
4595 if (AT && AT->getAttrKind() != CCAttrKind) {
4596 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
4597 << FunctionType::getNameForCallConv(CC)
4598 << FunctionType::getNameForCallConv(CCOld);
4599 attr.setInvalid();
4600 return true;
4601 }
4602 }
4603
4604 // Diagnose use of callee-cleanup calling convention on variadic functions.
4605 if (!supportsVariadicCall(CC)) {
4606 const FunctionProtoType *FnP = dyn_cast<FunctionProtoType>(fn);
4607 if (FnP && FnP->isVariadic()) {
4608 unsigned DiagID = diag::err_cconv_varargs;
4609 // stdcall and fastcall are ignored with a warning for GCC and MS
4610 // compatibility.
4611 if (CC == CC_X86StdCall || CC == CC_X86FastCall)
4612 DiagID = diag::warn_cconv_varargs;
4613
4614 S.Diag(attr.getLoc(), DiagID) << FunctionType::getNameForCallConv(CC);
4615 attr.setInvalid();
4616 return true;
4617 }
4618 }
4619
4620 // Also diagnose fastcall with regparm.
4621 if (CC == CC_X86FastCall && fn->getHasRegParm()) {
4622 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
4623 << "regparm" << FunctionType::getNameForCallConv(CC_X86FastCall);
4624 attr.setInvalid();
4625 return true;
4626 }
4627
4628 // Modify the CC from the wrapped function type, wrap it all back, and then
4629 // wrap the whole thing in an AttributedType as written. The modified type
4630 // might have a different CC if we ignored the attribute.
4631 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withCallingConv(CC);
4632 QualType Equivalent =
4633 unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
4634 type = S.Context.getAttributedType(CCAttrKind, type, Equivalent);
4635 return true;
4636 }
4637
hasExplicitCallingConv(QualType & T)4638 bool Sema::hasExplicitCallingConv(QualType &T) {
4639 QualType R = T.IgnoreParens();
4640 while (const AttributedType *AT = dyn_cast<AttributedType>(R)) {
4641 if (AT->isCallingConv())
4642 return true;
4643 R = AT->getModifiedType().IgnoreParens();
4644 }
4645 return false;
4646 }
4647
adjustMemberFunctionCC(QualType & T,bool IsStatic)4648 void Sema::adjustMemberFunctionCC(QualType &T, bool IsStatic) {
4649 FunctionTypeUnwrapper Unwrapped(*this, T);
4650 const FunctionType *FT = Unwrapped.get();
4651 bool IsVariadic = (isa<FunctionProtoType>(FT) &&
4652 cast<FunctionProtoType>(FT)->isVariadic());
4653
4654 // Only adjust types with the default convention. For example, on Windows we
4655 // should adjust a __cdecl type to __thiscall for instance methods, and a
4656 // __thiscall type to __cdecl for static methods.
4657 CallingConv CurCC = FT->getCallConv();
4658 CallingConv FromCC =
4659 Context.getDefaultCallingConvention(IsVariadic, IsStatic);
4660 CallingConv ToCC = Context.getDefaultCallingConvention(IsVariadic, !IsStatic);
4661 if (CurCC != FromCC || FromCC == ToCC)
4662 return;
4663
4664 if (hasExplicitCallingConv(T))
4665 return;
4666
4667 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(ToCC));
4668 QualType Wrapped = Unwrapped.wrap(*this, FT);
4669 T = Context.getAdjustedType(T, Wrapped);
4670 }
4671
4672 /// HandleVectorSizeAttribute - this attribute is only applicable to integral
4673 /// and float scalars, although arrays, pointers, and function return values are
4674 /// allowed in conjunction with this construct. Aggregates with this attribute
4675 /// are invalid, even if they are of the same size as a corresponding scalar.
4676 /// The raw attribute should contain precisely 1 argument, the vector size for
4677 /// the variable, measured in bytes. If curType and rawAttr are well formed,
4678 /// this routine will return a new vector type.
HandleVectorSizeAttr(QualType & CurType,const AttributeList & Attr,Sema & S)4679 static void HandleVectorSizeAttr(QualType& CurType, const AttributeList &Attr,
4680 Sema &S) {
4681 // Check the attribute arguments.
4682 if (Attr.getNumArgs() != 1) {
4683 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
4684 << Attr.getName() << 1;
4685 Attr.setInvalid();
4686 return;
4687 }
4688 Expr *sizeExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
4689 llvm::APSInt vecSize(32);
4690 if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() ||
4691 !sizeExpr->isIntegerConstantExpr(vecSize, S.Context)) {
4692 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
4693 << Attr.getName() << AANT_ArgumentIntegerConstant
4694 << sizeExpr->getSourceRange();
4695 Attr.setInvalid();
4696 return;
4697 }
4698 // The base type must be integer (not Boolean or enumeration) or float, and
4699 // can't already be a vector.
4700 if (!CurType->isBuiltinType() || CurType->isBooleanType() ||
4701 (!CurType->isIntegerType() && !CurType->isRealFloatingType())) {
4702 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
4703 Attr.setInvalid();
4704 return;
4705 }
4706 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
4707 // vecSize is specified in bytes - convert to bits.
4708 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
4709
4710 // the vector size needs to be an integral multiple of the type size.
4711 if (vectorSize % typeSize) {
4712 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
4713 << sizeExpr->getSourceRange();
4714 Attr.setInvalid();
4715 return;
4716 }
4717 if (VectorType::isVectorSizeTooLarge(vectorSize / typeSize)) {
4718 S.Diag(Attr.getLoc(), diag::err_attribute_size_too_large)
4719 << sizeExpr->getSourceRange();
4720 Attr.setInvalid();
4721 return;
4722 }
4723 if (vectorSize == 0) {
4724 S.Diag(Attr.getLoc(), diag::err_attribute_zero_size)
4725 << sizeExpr->getSourceRange();
4726 Attr.setInvalid();
4727 return;
4728 }
4729
4730 // Success! Instantiate the vector type, the number of elements is > 0, and
4731 // not required to be a power of 2, unlike GCC.
4732 CurType = S.Context.getVectorType(CurType, vectorSize/typeSize,
4733 VectorType::GenericVector);
4734 }
4735
4736 /// \brief Process the OpenCL-like ext_vector_type attribute when it occurs on
4737 /// a type.
HandleExtVectorTypeAttr(QualType & CurType,const AttributeList & Attr,Sema & S)4738 static void HandleExtVectorTypeAttr(QualType &CurType,
4739 const AttributeList &Attr,
4740 Sema &S) {
4741 // check the attribute arguments.
4742 if (Attr.getNumArgs() != 1) {
4743 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
4744 << Attr.getName() << 1;
4745 return;
4746 }
4747
4748 Expr *sizeExpr;
4749
4750 // Special case where the argument is a template id.
4751 if (Attr.isArgIdent(0)) {
4752 CXXScopeSpec SS;
4753 SourceLocation TemplateKWLoc;
4754 UnqualifiedId id;
4755 id.setIdentifier(Attr.getArgAsIdent(0)->Ident, Attr.getLoc());
4756
4757 ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, TemplateKWLoc,
4758 id, false, false);
4759 if (Size.isInvalid())
4760 return;
4761
4762 sizeExpr = Size.get();
4763 } else {
4764 sizeExpr = Attr.getArgAsExpr(0);
4765 }
4766
4767 // Create the vector type.
4768 QualType T = S.BuildExtVectorType(CurType, sizeExpr, Attr.getLoc());
4769 if (!T.isNull())
4770 CurType = T;
4771 }
4772
isPermittedNeonBaseType(QualType & Ty,VectorType::VectorKind VecKind,Sema & S)4773 static bool isPermittedNeonBaseType(QualType &Ty,
4774 VectorType::VectorKind VecKind, Sema &S) {
4775 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
4776 if (!BTy)
4777 return false;
4778
4779 llvm::Triple Triple = S.Context.getTargetInfo().getTriple();
4780
4781 // Signed poly is mathematically wrong, but has been baked into some ABIs by
4782 // now.
4783 bool IsPolyUnsigned = Triple.getArch() == llvm::Triple::aarch64 ||
4784 Triple.getArch() == llvm::Triple::aarch64_be;
4785 if (VecKind == VectorType::NeonPolyVector) {
4786 if (IsPolyUnsigned) {
4787 // AArch64 polynomial vectors are unsigned and support poly64.
4788 return BTy->getKind() == BuiltinType::UChar ||
4789 BTy->getKind() == BuiltinType::UShort ||
4790 BTy->getKind() == BuiltinType::ULong ||
4791 BTy->getKind() == BuiltinType::ULongLong;
4792 } else {
4793 // AArch32 polynomial vector are signed.
4794 return BTy->getKind() == BuiltinType::SChar ||
4795 BTy->getKind() == BuiltinType::Short;
4796 }
4797 }
4798
4799 // Non-polynomial vector types: the usual suspects are allowed, as well as
4800 // float64_t on AArch64.
4801 bool Is64Bit = Triple.getArch() == llvm::Triple::aarch64 ||
4802 Triple.getArch() == llvm::Triple::aarch64_be;
4803
4804 if (Is64Bit && BTy->getKind() == BuiltinType::Double)
4805 return true;
4806
4807 return BTy->getKind() == BuiltinType::SChar ||
4808 BTy->getKind() == BuiltinType::UChar ||
4809 BTy->getKind() == BuiltinType::Short ||
4810 BTy->getKind() == BuiltinType::UShort ||
4811 BTy->getKind() == BuiltinType::Int ||
4812 BTy->getKind() == BuiltinType::UInt ||
4813 BTy->getKind() == BuiltinType::Long ||
4814 BTy->getKind() == BuiltinType::ULong ||
4815 BTy->getKind() == BuiltinType::LongLong ||
4816 BTy->getKind() == BuiltinType::ULongLong ||
4817 BTy->getKind() == BuiltinType::Float ||
4818 BTy->getKind() == BuiltinType::Half;
4819 }
4820
4821 /// HandleNeonVectorTypeAttr - The "neon_vector_type" and
4822 /// "neon_polyvector_type" attributes are used to create vector types that
4823 /// are mangled according to ARM's ABI. Otherwise, these types are identical
4824 /// to those created with the "vector_size" attribute. Unlike "vector_size"
4825 /// the argument to these Neon attributes is the number of vector elements,
4826 /// not the vector size in bytes. The vector width and element type must
4827 /// match one of the standard Neon vector types.
HandleNeonVectorTypeAttr(QualType & CurType,const AttributeList & Attr,Sema & S,VectorType::VectorKind VecKind)4828 static void HandleNeonVectorTypeAttr(QualType& CurType,
4829 const AttributeList &Attr, Sema &S,
4830 VectorType::VectorKind VecKind) {
4831 // Target must have NEON
4832 if (!S.Context.getTargetInfo().hasFeature("neon")) {
4833 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) << Attr.getName();
4834 Attr.setInvalid();
4835 return;
4836 }
4837 // Check the attribute arguments.
4838 if (Attr.getNumArgs() != 1) {
4839 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
4840 << Attr.getName() << 1;
4841 Attr.setInvalid();
4842 return;
4843 }
4844 // The number of elements must be an ICE.
4845 Expr *numEltsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
4846 llvm::APSInt numEltsInt(32);
4847 if (numEltsExpr->isTypeDependent() || numEltsExpr->isValueDependent() ||
4848 !numEltsExpr->isIntegerConstantExpr(numEltsInt, S.Context)) {
4849 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
4850 << Attr.getName() << AANT_ArgumentIntegerConstant
4851 << numEltsExpr->getSourceRange();
4852 Attr.setInvalid();
4853 return;
4854 }
4855 // Only certain element types are supported for Neon vectors.
4856 if (!isPermittedNeonBaseType(CurType, VecKind, S)) {
4857 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
4858 Attr.setInvalid();
4859 return;
4860 }
4861
4862 // The total size of the vector must be 64 or 128 bits.
4863 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
4864 unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue());
4865 unsigned vecSize = typeSize * numElts;
4866 if (vecSize != 64 && vecSize != 128) {
4867 S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType;
4868 Attr.setInvalid();
4869 return;
4870 }
4871
4872 CurType = S.Context.getVectorType(CurType, numElts, VecKind);
4873 }
4874
processTypeAttrs(TypeProcessingState & state,QualType & type,TypeAttrLocation TAL,AttributeList * attrs)4875 static void processTypeAttrs(TypeProcessingState &state, QualType &type,
4876 TypeAttrLocation TAL, AttributeList *attrs) {
4877 // Scan through and apply attributes to this type where it makes sense. Some
4878 // attributes (such as __address_space__, __vector_size__, etc) apply to the
4879 // type, but others can be present in the type specifiers even though they
4880 // apply to the decl. Here we apply type attributes and ignore the rest.
4881
4882 AttributeList *next;
4883 do {
4884 AttributeList &attr = *attrs;
4885 next = attr.getNext();
4886
4887 // Skip attributes that were marked to be invalid.
4888 if (attr.isInvalid())
4889 continue;
4890
4891 if (attr.isCXX11Attribute()) {
4892 // [[gnu::...]] attributes are treated as declaration attributes, so may
4893 // not appertain to a DeclaratorChunk, even if we handle them as type
4894 // attributes.
4895 if (attr.getScopeName() && attr.getScopeName()->isStr("gnu")) {
4896 if (TAL == TAL_DeclChunk) {
4897 state.getSema().Diag(attr.getLoc(),
4898 diag::warn_cxx11_gnu_attribute_on_type)
4899 << attr.getName();
4900 continue;
4901 }
4902 } else if (TAL != TAL_DeclChunk) {
4903 // Otherwise, only consider type processing for a C++11 attribute if
4904 // it's actually been applied to a type.
4905 continue;
4906 }
4907 }
4908
4909 // If this is an attribute we can handle, do so now,
4910 // otherwise, add it to the FnAttrs list for rechaining.
4911 switch (attr.getKind()) {
4912 default:
4913 // A C++11 attribute on a declarator chunk must appertain to a type.
4914 if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk) {
4915 state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr)
4916 << attr.getName();
4917 attr.setUsedAsTypeAttr();
4918 }
4919 break;
4920
4921 case AttributeList::UnknownAttribute:
4922 if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk)
4923 state.getSema().Diag(attr.getLoc(),
4924 diag::warn_unknown_attribute_ignored)
4925 << attr.getName();
4926 break;
4927
4928 case AttributeList::IgnoredAttribute:
4929 break;
4930
4931 case AttributeList::AT_MayAlias:
4932 // FIXME: This attribute needs to actually be handled, but if we ignore
4933 // it it breaks large amounts of Linux software.
4934 attr.setUsedAsTypeAttr();
4935 break;
4936 case AttributeList::AT_OpenCLPrivateAddressSpace:
4937 case AttributeList::AT_OpenCLGlobalAddressSpace:
4938 case AttributeList::AT_OpenCLLocalAddressSpace:
4939 case AttributeList::AT_OpenCLConstantAddressSpace:
4940 case AttributeList::AT_OpenCLGenericAddressSpace:
4941 case AttributeList::AT_AddressSpace:
4942 HandleAddressSpaceTypeAttribute(type, attr, state.getSema());
4943 attr.setUsedAsTypeAttr();
4944 break;
4945 OBJC_POINTER_TYPE_ATTRS_CASELIST:
4946 if (!handleObjCPointerTypeAttr(state, attr, type))
4947 distributeObjCPointerTypeAttr(state, attr, type);
4948 attr.setUsedAsTypeAttr();
4949 break;
4950 case AttributeList::AT_VectorSize:
4951 HandleVectorSizeAttr(type, attr, state.getSema());
4952 attr.setUsedAsTypeAttr();
4953 break;
4954 case AttributeList::AT_ExtVectorType:
4955 HandleExtVectorTypeAttr(type, attr, state.getSema());
4956 attr.setUsedAsTypeAttr();
4957 break;
4958 case AttributeList::AT_NeonVectorType:
4959 HandleNeonVectorTypeAttr(type, attr, state.getSema(),
4960 VectorType::NeonVector);
4961 attr.setUsedAsTypeAttr();
4962 break;
4963 case AttributeList::AT_NeonPolyVectorType:
4964 HandleNeonVectorTypeAttr(type, attr, state.getSema(),
4965 VectorType::NeonPolyVector);
4966 attr.setUsedAsTypeAttr();
4967 break;
4968 case AttributeList::AT_OpenCLImageAccess:
4969 // FIXME: there should be some type checking happening here, I would
4970 // imagine, but the original handler's checking was entirely superfluous.
4971 attr.setUsedAsTypeAttr();
4972 break;
4973
4974 MS_TYPE_ATTRS_CASELIST:
4975 if (!handleMSPointerTypeQualifierAttr(state, attr, type))
4976 attr.setUsedAsTypeAttr();
4977 break;
4978
4979 case AttributeList::AT_NSReturnsRetained:
4980 if (!state.getSema().getLangOpts().ObjCAutoRefCount)
4981 break;
4982 // fallthrough into the function attrs
4983
4984 FUNCTION_TYPE_ATTRS_CASELIST:
4985 attr.setUsedAsTypeAttr();
4986
4987 // Never process function type attributes as part of the
4988 // declaration-specifiers.
4989 if (TAL == TAL_DeclSpec)
4990 distributeFunctionTypeAttrFromDeclSpec(state, attr, type);
4991
4992 // Otherwise, handle the possible delays.
4993 else if (!handleFunctionTypeAttr(state, attr, type))
4994 distributeFunctionTypeAttr(state, attr, type);
4995 break;
4996 }
4997 } while ((attrs = next));
4998 }
4999
5000 /// \brief Ensure that the type of the given expression is complete.
5001 ///
5002 /// This routine checks whether the expression \p E has a complete type. If the
5003 /// expression refers to an instantiable construct, that instantiation is
5004 /// performed as needed to complete its type. Furthermore
5005 /// Sema::RequireCompleteType is called for the expression's type (or in the
5006 /// case of a reference type, the referred-to type).
5007 ///
5008 /// \param E The expression whose type is required to be complete.
5009 /// \param Diagnoser The object that will emit a diagnostic if the type is
5010 /// incomplete.
5011 ///
5012 /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false
5013 /// otherwise.
RequireCompleteExprType(Expr * E,TypeDiagnoser & Diagnoser)5014 bool Sema::RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser){
5015 QualType T = E->getType();
5016
5017 // Fast path the case where the type is already complete.
5018 if (!T->isIncompleteType())
5019 // FIXME: The definition might not be visible.
5020 return false;
5021
5022 // Incomplete array types may be completed by the initializer attached to
5023 // their definitions. For static data members of class templates and for
5024 // variable templates, we need to instantiate the definition to get this
5025 // initializer and complete the type.
5026 if (T->isIncompleteArrayType()) {
5027 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
5028 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
5029 if (isTemplateInstantiation(Var->getTemplateSpecializationKind())) {
5030 SourceLocation PointOfInstantiation = E->getExprLoc();
5031
5032 if (MemberSpecializationInfo *MSInfo =
5033 Var->getMemberSpecializationInfo()) {
5034 // If we don't already have a point of instantiation, this is it.
5035 if (MSInfo->getPointOfInstantiation().isInvalid()) {
5036 MSInfo->setPointOfInstantiation(PointOfInstantiation);
5037
5038 // This is a modification of an existing AST node. Notify
5039 // listeners.
5040 if (ASTMutationListener *L = getASTMutationListener())
5041 L->StaticDataMemberInstantiated(Var);
5042 }
5043 } else {
5044 VarTemplateSpecializationDecl *VarSpec =
5045 cast<VarTemplateSpecializationDecl>(Var);
5046 if (VarSpec->getPointOfInstantiation().isInvalid())
5047 VarSpec->setPointOfInstantiation(PointOfInstantiation);
5048 }
5049
5050 InstantiateVariableDefinition(PointOfInstantiation, Var);
5051
5052 // Update the type to the newly instantiated definition's type both
5053 // here and within the expression.
5054 if (VarDecl *Def = Var->getDefinition()) {
5055 DRE->setDecl(Def);
5056 T = Def->getType();
5057 DRE->setType(T);
5058 E->setType(T);
5059 }
5060
5061 // We still go on to try to complete the type independently, as it
5062 // may also require instantiations or diagnostics if it remains
5063 // incomplete.
5064 }
5065 }
5066 }
5067 }
5068
5069 // FIXME: Are there other cases which require instantiating something other
5070 // than the type to complete the type of an expression?
5071
5072 // Look through reference types and complete the referred type.
5073 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5074 T = Ref->getPointeeType();
5075
5076 return RequireCompleteType(E->getExprLoc(), T, Diagnoser);
5077 }
5078
5079 namespace {
5080 struct TypeDiagnoserDiag : Sema::TypeDiagnoser {
5081 unsigned DiagID;
5082
TypeDiagnoserDiag__anon9acaebf90511::TypeDiagnoserDiag5083 TypeDiagnoserDiag(unsigned DiagID)
5084 : Sema::TypeDiagnoser(DiagID == 0), DiagID(DiagID) {}
5085
diagnose__anon9acaebf90511::TypeDiagnoserDiag5086 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5087 if (Suppressed) return;
5088 S.Diag(Loc, DiagID) << T;
5089 }
5090 };
5091 }
5092
RequireCompleteExprType(Expr * E,unsigned DiagID)5093 bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) {
5094 TypeDiagnoserDiag Diagnoser(DiagID);
5095 return RequireCompleteExprType(E, Diagnoser);
5096 }
5097
5098 /// @brief Ensure that the type T is a complete type.
5099 ///
5100 /// This routine checks whether the type @p T is complete in any
5101 /// context where a complete type is required. If @p T is a complete
5102 /// type, returns false. If @p T is a class template specialization,
5103 /// this routine then attempts to perform class template
5104 /// instantiation. If instantiation fails, or if @p T is incomplete
5105 /// and cannot be completed, issues the diagnostic @p diag (giving it
5106 /// the type @p T) and returns true.
5107 ///
5108 /// @param Loc The location in the source that the incomplete type
5109 /// diagnostic should refer to.
5110 ///
5111 /// @param T The type that this routine is examining for completeness.
5112 ///
5113 /// @returns @c true if @p T is incomplete and a diagnostic was emitted,
5114 /// @c false otherwise.
RequireCompleteType(SourceLocation Loc,QualType T,TypeDiagnoser & Diagnoser)5115 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
5116 TypeDiagnoser &Diagnoser) {
5117 if (RequireCompleteTypeImpl(Loc, T, Diagnoser))
5118 return true;
5119 if (const TagType *Tag = T->getAs<TagType>()) {
5120 if (!Tag->getDecl()->isCompleteDefinitionRequired()) {
5121 Tag->getDecl()->setCompleteDefinitionRequired();
5122 Consumer.HandleTagDeclRequiredDefinition(Tag->getDecl());
5123 }
5124 }
5125 return false;
5126 }
5127
5128 /// \brief Determine whether there is any declaration of \p D that was ever a
5129 /// definition (perhaps before module merging) and is currently visible.
5130 /// \param D The definition of the entity.
5131 /// \param Suggested Filled in with the declaration that should be made visible
5132 /// in order to provide a definition of this entity.
hasVisibleDefinition(NamedDecl * D,NamedDecl ** Suggested)5133 bool Sema::hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested) {
5134 // Easy case: if we don't have modules, all declarations are visible.
5135 if (!getLangOpts().Modules)
5136 return true;
5137
5138 // If this definition was instantiated from a template, map back to the
5139 // pattern from which it was instantiated.
5140 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
5141 if (auto *Pattern = RD->getTemplateInstantiationPattern())
5142 RD = Pattern;
5143 D = RD->getDefinition();
5144 } else if (auto *ED = dyn_cast<EnumDecl>(D)) {
5145 while (auto *NewED = ED->getInstantiatedFromMemberEnum())
5146 ED = NewED;
5147 if (ED->isFixed()) {
5148 // If the enum has a fixed underlying type, any declaration of it will do.
5149 *Suggested = nullptr;
5150 for (auto *Redecl : ED->redecls()) {
5151 if (LookupResult::isVisible(*this, Redecl))
5152 return true;
5153 if (Redecl->isThisDeclarationADefinition() ||
5154 (Redecl->isCanonicalDecl() && !*Suggested))
5155 *Suggested = Redecl;
5156 }
5157 return false;
5158 }
5159 D = ED->getDefinition();
5160 }
5161 assert(D && "missing definition for pattern of instantiated definition");
5162
5163 // FIXME: If we merged any other decl into D, and that declaration is visible,
5164 // then we should consider a definition to be visible.
5165 *Suggested = D;
5166 return LookupResult::isVisible(*this, D);
5167 }
5168
5169 /// Locks in the inheritance model for the given class and all of its bases.
assignInheritanceModel(Sema & S,CXXRecordDecl * RD)5170 static void assignInheritanceModel(Sema &S, CXXRecordDecl *RD) {
5171 RD = RD->getMostRecentDecl();
5172 if (!RD->hasAttr<MSInheritanceAttr>()) {
5173 MSInheritanceAttr::Spelling IM;
5174
5175 switch (S.MSPointerToMemberRepresentationMethod) {
5176 case LangOptions::PPTMK_BestCase:
5177 IM = RD->calculateInheritanceModel();
5178 break;
5179 case LangOptions::PPTMK_FullGeneralitySingleInheritance:
5180 IM = MSInheritanceAttr::Keyword_single_inheritance;
5181 break;
5182 case LangOptions::PPTMK_FullGeneralityMultipleInheritance:
5183 IM = MSInheritanceAttr::Keyword_multiple_inheritance;
5184 break;
5185 case LangOptions::PPTMK_FullGeneralityVirtualInheritance:
5186 IM = MSInheritanceAttr::Keyword_unspecified_inheritance;
5187 break;
5188 }
5189
5190 RD->addAttr(MSInheritanceAttr::CreateImplicit(
5191 S.getASTContext(), IM,
5192 /*BestCase=*/S.MSPointerToMemberRepresentationMethod ==
5193 LangOptions::PPTMK_BestCase,
5194 S.ImplicitMSInheritanceAttrLoc.isValid()
5195 ? S.ImplicitMSInheritanceAttrLoc
5196 : RD->getSourceRange()));
5197 }
5198 }
5199
5200 /// \brief The implementation of RequireCompleteType
RequireCompleteTypeImpl(SourceLocation Loc,QualType T,TypeDiagnoser & Diagnoser)5201 bool Sema::RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
5202 TypeDiagnoser &Diagnoser) {
5203 // FIXME: Add this assertion to make sure we always get instantiation points.
5204 // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
5205 // FIXME: Add this assertion to help us flush out problems with
5206 // checking for dependent types and type-dependent expressions.
5207 //
5208 // assert(!T->isDependentType() &&
5209 // "Can't ask whether a dependent type is complete");
5210
5211 // If we have a complete type, we're done.
5212 NamedDecl *Def = nullptr;
5213 if (!T->isIncompleteType(&Def)) {
5214 // If we know about the definition but it is not visible, complain.
5215 NamedDecl *SuggestedDef = nullptr;
5216 if (!Diagnoser.Suppressed && Def &&
5217 !hasVisibleDefinition(Def, &SuggestedDef)) {
5218 // Suppress this error outside of a SFINAE context if we've already
5219 // emitted the error once for this type. There's no usefulness in
5220 // repeating the diagnostic.
5221 // FIXME: Add a Fix-It that imports the corresponding module or includes
5222 // the header.
5223 Module *Owner = SuggestedDef->getOwningModule();
5224 Diag(Loc, diag::err_module_private_definition)
5225 << T << Owner->getFullModuleName();
5226 Diag(SuggestedDef->getLocation(), diag::note_previous_definition);
5227
5228 // Try to recover by implicitly importing this module.
5229 createImplicitModuleImportForErrorRecovery(Loc, Owner);
5230 }
5231
5232 // We lock in the inheritance model once somebody has asked us to ensure
5233 // that a pointer-to-member type is complete.
5234 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5235 if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>()) {
5236 if (!MPTy->getClass()->isDependentType()) {
5237 RequireCompleteType(Loc, QualType(MPTy->getClass(), 0), 0);
5238 assignInheritanceModel(*this, MPTy->getMostRecentCXXRecordDecl());
5239 }
5240 }
5241 }
5242
5243 return false;
5244 }
5245
5246 const TagType *Tag = T->getAs<TagType>();
5247 const ObjCInterfaceType *IFace = T->getAs<ObjCInterfaceType>();
5248
5249 // If there's an unimported definition of this type in a module (for
5250 // instance, because we forward declared it, then imported the definition),
5251 // import that definition now.
5252 //
5253 // FIXME: What about other cases where an import extends a redeclaration
5254 // chain for a declaration that can be accessed through a mechanism other
5255 // than name lookup (eg, referenced in a template, or a variable whose type
5256 // could be completed by the module)?
5257 if (Tag || IFace) {
5258 NamedDecl *D =
5259 Tag ? static_cast<NamedDecl *>(Tag->getDecl()) : IFace->getDecl();
5260
5261 // Avoid diagnosing invalid decls as incomplete.
5262 if (D->isInvalidDecl())
5263 return true;
5264
5265 // Give the external AST source a chance to complete the type.
5266 if (auto *Source = Context.getExternalSource()) {
5267 if (Tag)
5268 Source->CompleteType(Tag->getDecl());
5269 else
5270 Source->CompleteType(IFace->getDecl());
5271
5272 // If the external source completed the type, go through the motions
5273 // again to ensure we're allowed to use the completed type.
5274 if (!T->isIncompleteType())
5275 return RequireCompleteTypeImpl(Loc, T, Diagnoser);
5276 }
5277 }
5278
5279 // If we have a class template specialization or a class member of a
5280 // class template specialization, or an array with known size of such,
5281 // try to instantiate it.
5282 QualType MaybeTemplate = T;
5283 while (const ConstantArrayType *Array
5284 = Context.getAsConstantArrayType(MaybeTemplate))
5285 MaybeTemplate = Array->getElementType();
5286 if (const RecordType *Record = MaybeTemplate->getAs<RecordType>()) {
5287 if (ClassTemplateSpecializationDecl *ClassTemplateSpec
5288 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
5289 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared)
5290 return InstantiateClassTemplateSpecialization(Loc, ClassTemplateSpec,
5291 TSK_ImplicitInstantiation,
5292 /*Complain=*/!Diagnoser.Suppressed);
5293 } else if (CXXRecordDecl *Rec
5294 = dyn_cast<CXXRecordDecl>(Record->getDecl())) {
5295 CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass();
5296 if (!Rec->isBeingDefined() && Pattern) {
5297 MemberSpecializationInfo *MSI = Rec->getMemberSpecializationInfo();
5298 assert(MSI && "Missing member specialization information?");
5299 // This record was instantiated from a class within a template.
5300 if (MSI->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
5301 return InstantiateClass(Loc, Rec, Pattern,
5302 getTemplateInstantiationArgs(Rec),
5303 TSK_ImplicitInstantiation,
5304 /*Complain=*/!Diagnoser.Suppressed);
5305 }
5306 }
5307 }
5308
5309 if (Diagnoser.Suppressed)
5310 return true;
5311
5312 // We have an incomplete type. Produce a diagnostic.
5313 if (Ident___float128 &&
5314 T == Context.getTypeDeclType(Context.getFloat128StubType())) {
5315 Diag(Loc, diag::err_typecheck_decl_incomplete_type___float128);
5316 return true;
5317 }
5318
5319 Diagnoser.diagnose(*this, Loc, T);
5320
5321 // If the type was a forward declaration of a class/struct/union
5322 // type, produce a note.
5323 if (Tag && !Tag->getDecl()->isInvalidDecl())
5324 Diag(Tag->getDecl()->getLocation(),
5325 Tag->isBeingDefined() ? diag::note_type_being_defined
5326 : diag::note_forward_declaration)
5327 << QualType(Tag, 0);
5328
5329 // If the Objective-C class was a forward declaration, produce a note.
5330 if (IFace && !IFace->getDecl()->isInvalidDecl())
5331 Diag(IFace->getDecl()->getLocation(), diag::note_forward_class);
5332
5333 // If we have external information that we can use to suggest a fix,
5334 // produce a note.
5335 if (ExternalSource)
5336 ExternalSource->MaybeDiagnoseMissingCompleteType(Loc, T);
5337
5338 return true;
5339 }
5340
RequireCompleteType(SourceLocation Loc,QualType T,unsigned DiagID)5341 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
5342 unsigned DiagID) {
5343 TypeDiagnoserDiag Diagnoser(DiagID);
5344 return RequireCompleteType(Loc, T, Diagnoser);
5345 }
5346
5347 /// \brief Get diagnostic %select index for tag kind for
5348 /// literal type diagnostic message.
5349 /// WARNING: Indexes apply to particular diagnostics only!
5350 ///
5351 /// \returns diagnostic %select index.
getLiteralDiagFromTagKind(TagTypeKind Tag)5352 static unsigned getLiteralDiagFromTagKind(TagTypeKind Tag) {
5353 switch (Tag) {
5354 case TTK_Struct: return 0;
5355 case TTK_Interface: return 1;
5356 case TTK_Class: return 2;
5357 default: llvm_unreachable("Invalid tag kind for literal type diagnostic!");
5358 }
5359 }
5360
5361 /// @brief Ensure that the type T is a literal type.
5362 ///
5363 /// This routine checks whether the type @p T is a literal type. If @p T is an
5364 /// incomplete type, an attempt is made to complete it. If @p T is a literal
5365 /// type, or @p AllowIncompleteType is true and @p T is an incomplete type,
5366 /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving
5367 /// it the type @p T), along with notes explaining why the type is not a
5368 /// literal type, and returns true.
5369 ///
5370 /// @param Loc The location in the source that the non-literal type
5371 /// diagnostic should refer to.
5372 ///
5373 /// @param T The type that this routine is examining for literalness.
5374 ///
5375 /// @param Diagnoser Emits a diagnostic if T is not a literal type.
5376 ///
5377 /// @returns @c true if @p T is not a literal type and a diagnostic was emitted,
5378 /// @c false otherwise.
RequireLiteralType(SourceLocation Loc,QualType T,TypeDiagnoser & Diagnoser)5379 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T,
5380 TypeDiagnoser &Diagnoser) {
5381 assert(!T->isDependentType() && "type should not be dependent");
5382
5383 QualType ElemType = Context.getBaseElementType(T);
5384 RequireCompleteType(Loc, ElemType, 0);
5385
5386 if (T->isLiteralType(Context))
5387 return false;
5388
5389 if (Diagnoser.Suppressed)
5390 return true;
5391
5392 Diagnoser.diagnose(*this, Loc, T);
5393
5394 if (T->isVariableArrayType())
5395 return true;
5396
5397 const RecordType *RT = ElemType->getAs<RecordType>();
5398 if (!RT)
5399 return true;
5400
5401 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
5402
5403 // A partially-defined class type can't be a literal type, because a literal
5404 // class type must have a trivial destructor (which can't be checked until
5405 // the class definition is complete).
5406 if (!RD->isCompleteDefinition()) {
5407 RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T);
5408 return true;
5409 }
5410
5411 // If the class has virtual base classes, then it's not an aggregate, and
5412 // cannot have any constexpr constructors or a trivial default constructor,
5413 // so is non-literal. This is better to diagnose than the resulting absence
5414 // of constexpr constructors.
5415 if (RD->getNumVBases()) {
5416 Diag(RD->getLocation(), diag::note_non_literal_virtual_base)
5417 << getLiteralDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
5418 for (const auto &I : RD->vbases())
5419 Diag(I.getLocStart(), diag::note_constexpr_virtual_base_here)
5420 << I.getSourceRange();
5421 } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() &&
5422 !RD->hasTrivialDefaultConstructor()) {
5423 Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD;
5424 } else if (RD->hasNonLiteralTypeFieldsOrBases()) {
5425 for (const auto &I : RD->bases()) {
5426 if (!I.getType()->isLiteralType(Context)) {
5427 Diag(I.getLocStart(),
5428 diag::note_non_literal_base_class)
5429 << RD << I.getType() << I.getSourceRange();
5430 return true;
5431 }
5432 }
5433 for (const auto *I : RD->fields()) {
5434 if (!I->getType()->isLiteralType(Context) ||
5435 I->getType().isVolatileQualified()) {
5436 Diag(I->getLocation(), diag::note_non_literal_field)
5437 << RD << I << I->getType()
5438 << I->getType().isVolatileQualified();
5439 return true;
5440 }
5441 }
5442 } else if (!RD->hasTrivialDestructor()) {
5443 // All fields and bases are of literal types, so have trivial destructors.
5444 // If this class's destructor is non-trivial it must be user-declared.
5445 CXXDestructorDecl *Dtor = RD->getDestructor();
5446 assert(Dtor && "class has literal fields and bases but no dtor?");
5447 if (!Dtor)
5448 return true;
5449
5450 Diag(Dtor->getLocation(), Dtor->isUserProvided() ?
5451 diag::note_non_literal_user_provided_dtor :
5452 diag::note_non_literal_nontrivial_dtor) << RD;
5453 if (!Dtor->isUserProvided())
5454 SpecialMemberIsTrivial(Dtor, CXXDestructor, /*Diagnose*/true);
5455 }
5456
5457 return true;
5458 }
5459
RequireLiteralType(SourceLocation Loc,QualType T,unsigned DiagID)5460 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) {
5461 TypeDiagnoserDiag Diagnoser(DiagID);
5462 return RequireLiteralType(Loc, T, Diagnoser);
5463 }
5464
5465 /// \brief Retrieve a version of the type 'T' that is elaborated by Keyword
5466 /// and qualified by the nested-name-specifier contained in SS.
getElaboratedType(ElaboratedTypeKeyword Keyword,const CXXScopeSpec & SS,QualType T)5467 QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword,
5468 const CXXScopeSpec &SS, QualType T) {
5469 if (T.isNull())
5470 return T;
5471 NestedNameSpecifier *NNS;
5472 if (SS.isValid())
5473 NNS = SS.getScopeRep();
5474 else {
5475 if (Keyword == ETK_None)
5476 return T;
5477 NNS = nullptr;
5478 }
5479 return Context.getElaboratedType(Keyword, NNS, T);
5480 }
5481
BuildTypeofExprType(Expr * E,SourceLocation Loc)5482 QualType Sema::BuildTypeofExprType(Expr *E, SourceLocation Loc) {
5483 ExprResult ER = CheckPlaceholderExpr(E);
5484 if (ER.isInvalid()) return QualType();
5485 E = ER.get();
5486
5487 if (!E->isTypeDependent()) {
5488 QualType T = E->getType();
5489 if (const TagType *TT = T->getAs<TagType>())
5490 DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc());
5491 }
5492 return Context.getTypeOfExprType(E);
5493 }
5494
5495 /// getDecltypeForExpr - Given an expr, will return the decltype for
5496 /// that expression, according to the rules in C++11
5497 /// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18.
getDecltypeForExpr(Sema & S,Expr * E)5498 static QualType getDecltypeForExpr(Sema &S, Expr *E) {
5499 if (E->isTypeDependent())
5500 return S.Context.DependentTy;
5501
5502 // C++11 [dcl.type.simple]p4:
5503 // The type denoted by decltype(e) is defined as follows:
5504 //
5505 // - if e is an unparenthesized id-expression or an unparenthesized class
5506 // member access (5.2.5), decltype(e) is the type of the entity named
5507 // by e. If there is no such entity, or if e names a set of overloaded
5508 // functions, the program is ill-formed;
5509 //
5510 // We apply the same rules for Objective-C ivar and property references.
5511 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
5512 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
5513 return VD->getType();
5514 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
5515 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
5516 return FD->getType();
5517 } else if (const ObjCIvarRefExpr *IR = dyn_cast<ObjCIvarRefExpr>(E)) {
5518 return IR->getDecl()->getType();
5519 } else if (const ObjCPropertyRefExpr *PR = dyn_cast<ObjCPropertyRefExpr>(E)) {
5520 if (PR->isExplicitProperty())
5521 return PR->getExplicitProperty()->getType();
5522 } else if (auto *PE = dyn_cast<PredefinedExpr>(E)) {
5523 return PE->getType();
5524 }
5525
5526 // C++11 [expr.lambda.prim]p18:
5527 // Every occurrence of decltype((x)) where x is a possibly
5528 // parenthesized id-expression that names an entity of automatic
5529 // storage duration is treated as if x were transformed into an
5530 // access to a corresponding data member of the closure type that
5531 // would have been declared if x were an odr-use of the denoted
5532 // entity.
5533 using namespace sema;
5534 if (S.getCurLambda()) {
5535 if (isa<ParenExpr>(E)) {
5536 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
5537 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
5538 QualType T = S.getCapturedDeclRefType(Var, DRE->getLocation());
5539 if (!T.isNull())
5540 return S.Context.getLValueReferenceType(T);
5541 }
5542 }
5543 }
5544 }
5545
5546
5547 // C++11 [dcl.type.simple]p4:
5548 // [...]
5549 QualType T = E->getType();
5550 switch (E->getValueKind()) {
5551 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
5552 // type of e;
5553 case VK_XValue: T = S.Context.getRValueReferenceType(T); break;
5554 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
5555 // type of e;
5556 case VK_LValue: T = S.Context.getLValueReferenceType(T); break;
5557 // - otherwise, decltype(e) is the type of e.
5558 case VK_RValue: break;
5559 }
5560
5561 return T;
5562 }
5563
BuildDecltypeType(Expr * E,SourceLocation Loc,bool AsUnevaluated)5564 QualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc,
5565 bool AsUnevaluated) {
5566 ExprResult ER = CheckPlaceholderExpr(E);
5567 if (ER.isInvalid()) return QualType();
5568 E = ER.get();
5569
5570 if (AsUnevaluated && ActiveTemplateInstantiations.empty() &&
5571 E->HasSideEffects(Context, false)) {
5572 // The expression operand for decltype is in an unevaluated expression
5573 // context, so side effects could result in unintended consequences.
5574 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
5575 }
5576
5577 return Context.getDecltypeType(E, getDecltypeForExpr(*this, E));
5578 }
5579
BuildUnaryTransformType(QualType BaseType,UnaryTransformType::UTTKind UKind,SourceLocation Loc)5580 QualType Sema::BuildUnaryTransformType(QualType BaseType,
5581 UnaryTransformType::UTTKind UKind,
5582 SourceLocation Loc) {
5583 switch (UKind) {
5584 case UnaryTransformType::EnumUnderlyingType:
5585 if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) {
5586 Diag(Loc, diag::err_only_enums_have_underlying_types);
5587 return QualType();
5588 } else {
5589 QualType Underlying = BaseType;
5590 if (!BaseType->isDependentType()) {
5591 // The enum could be incomplete if we're parsing its definition or
5592 // recovering from an error.
5593 NamedDecl *FwdDecl = nullptr;
5594 if (BaseType->isIncompleteType(&FwdDecl)) {
5595 Diag(Loc, diag::err_underlying_type_of_incomplete_enum) << BaseType;
5596 Diag(FwdDecl->getLocation(), diag::note_forward_declaration) << FwdDecl;
5597 return QualType();
5598 }
5599
5600 EnumDecl *ED = BaseType->getAs<EnumType>()->getDecl();
5601 assert(ED && "EnumType has no EnumDecl");
5602
5603 DiagnoseUseOfDecl(ED, Loc);
5604
5605 Underlying = ED->getIntegerType();
5606 assert(!Underlying.isNull());
5607 }
5608 return Context.getUnaryTransformType(BaseType, Underlying,
5609 UnaryTransformType::EnumUnderlyingType);
5610 }
5611 }
5612 llvm_unreachable("unknown unary transform type");
5613 }
5614
BuildAtomicType(QualType T,SourceLocation Loc)5615 QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) {
5616 if (!T->isDependentType()) {
5617 // FIXME: It isn't entirely clear whether incomplete atomic types
5618 // are allowed or not; for simplicity, ban them for the moment.
5619 if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0))
5620 return QualType();
5621
5622 int DisallowedKind = -1;
5623 if (T->isArrayType())
5624 DisallowedKind = 1;
5625 else if (T->isFunctionType())
5626 DisallowedKind = 2;
5627 else if (T->isReferenceType())
5628 DisallowedKind = 3;
5629 else if (T->isAtomicType())
5630 DisallowedKind = 4;
5631 else if (T.hasQualifiers())
5632 DisallowedKind = 5;
5633 else if (!T.isTriviallyCopyableType(Context))
5634 // Some other non-trivially-copyable type (probably a C++ class)
5635 DisallowedKind = 6;
5636
5637 if (DisallowedKind != -1) {
5638 Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T;
5639 return QualType();
5640 }
5641
5642 // FIXME: Do we need any handling for ARC here?
5643 }
5644
5645 // Build the pointer type.
5646 return Context.getAtomicType(T);
5647 }
5648