clang  7.0.0svn
SemaType.cpp
Go to the documentation of this file.
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 "TypeLocBuilder.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.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"
26 #include "clang/Basic/TargetInfo.h"
27 #include "clang/Lex/Preprocessor.h"
28 #include "clang/Sema/DeclSpec.h"
30 #include "clang/Sema/Lookup.h"
31 #include "clang/Sema/ScopeInfo.h"
33 #include "clang/Sema/Template.h"
35 #include "llvm/ADT/SmallPtrSet.h"
36 #include "llvm/ADT/SmallString.h"
37 #include "llvm/ADT/StringSwitch.h"
38 #include "llvm/Support/ErrorHandling.h"
39 
40 using namespace clang;
41 
46 };
47 
48 /// isOmittedBlockReturnType - Return true if this declarator is missing a
49 /// return type because this is a omitted return type on a block literal.
50 static bool isOmittedBlockReturnType(const Declarator &D) {
53  return false;
54 
55  if (D.getNumTypeObjects() == 0)
56  return true; // ^{ ... }
57 
58  if (D.getNumTypeObjects() == 1 &&
60  return true; // ^(int X, float Y) { ... }
61 
62  return false;
63 }
64 
65 /// diagnoseBadTypeAttribute - Diagnoses a type attribute which
66 /// doesn't apply to the given type.
67 static void diagnoseBadTypeAttribute(Sema &S, const AttributeList &attr,
68  QualType type) {
69  TypeDiagSelector WhichType;
70  bool useExpansionLoc = true;
71  switch (attr.getKind()) {
72  case AttributeList::AT_ObjCGC: WhichType = TDS_Pointer; break;
73  case AttributeList::AT_ObjCOwnership: WhichType = TDS_ObjCObjOrBlock; break;
74  default:
75  // Assume everything else was a function attribute.
76  WhichType = TDS_Function;
77  useExpansionLoc = false;
78  break;
79  }
80 
81  SourceLocation loc = attr.getLoc();
82  StringRef name = attr.getName()->getName();
83 
84  // The GC attributes are usually written with macros; special-case them.
85  IdentifierInfo *II = attr.isArgIdent(0) ? attr.getArgAsIdent(0)->Ident
86  : nullptr;
87  if (useExpansionLoc && loc.isMacroID() && II) {
88  if (II->isStr("strong")) {
89  if (S.findMacroSpelling(loc, "__strong")) name = "__strong";
90  } else if (II->isStr("weak")) {
91  if (S.findMacroSpelling(loc, "__weak")) name = "__weak";
92  }
93  }
94 
95  S.Diag(loc, diag::warn_type_attribute_wrong_type) << name << WhichType
96  << type;
97 }
98 
99 // objc_gc applies to Objective-C pointers or, otherwise, to the
100 // smallest available pointer type (i.e. 'void*' in 'void**').
101 #define OBJC_POINTER_TYPE_ATTRS_CASELIST \
102  case AttributeList::AT_ObjCGC: \
103  case AttributeList::AT_ObjCOwnership
104 
105 // Calling convention attributes.
106 #define CALLING_CONV_ATTRS_CASELIST \
107  case AttributeList::AT_CDecl: \
108  case AttributeList::AT_FastCall: \
109  case AttributeList::AT_StdCall: \
110  case AttributeList::AT_ThisCall: \
111  case AttributeList::AT_RegCall: \
112  case AttributeList::AT_Pascal: \
113  case AttributeList::AT_SwiftCall: \
114  case AttributeList::AT_VectorCall: \
115  case AttributeList::AT_MSABI: \
116  case AttributeList::AT_SysVABI: \
117  case AttributeList::AT_Pcs: \
118  case AttributeList::AT_IntelOclBicc: \
119  case AttributeList::AT_PreserveMost: \
120  case AttributeList::AT_PreserveAll
121 
122 // Function type attributes.
123 #define FUNCTION_TYPE_ATTRS_CASELIST \
124  case AttributeList::AT_NSReturnsRetained: \
125  case AttributeList::AT_NoReturn: \
126  case AttributeList::AT_Regparm: \
127  case AttributeList::AT_AnyX86NoCallerSavedRegisters: \
128  case AttributeList::AT_AnyX86NoCfCheck: \
129  CALLING_CONV_ATTRS_CASELIST
130 
131 // Microsoft-specific type qualifiers.
132 #define MS_TYPE_ATTRS_CASELIST \
133  case AttributeList::AT_Ptr32: \
134  case AttributeList::AT_Ptr64: \
135  case AttributeList::AT_SPtr: \
136  case AttributeList::AT_UPtr
137 
138 // Nullability qualifiers.
139 #define NULLABILITY_TYPE_ATTRS_CASELIST \
140  case AttributeList::AT_TypeNonNull: \
141  case AttributeList::AT_TypeNullable: \
142  case AttributeList::AT_TypeNullUnspecified
143 
144 namespace {
145  /// An object which stores processing state for the entire
146  /// GetTypeForDeclarator process.
147  class TypeProcessingState {
148  Sema &sema;
149 
150  /// The declarator being processed.
151  Declarator &declarator;
152 
153  /// The index of the declarator chunk we're currently processing.
154  /// May be the total number of valid chunks, indicating the
155  /// DeclSpec.
156  unsigned chunkIndex;
157 
158  /// Whether there are non-trivial modifications to the decl spec.
159  bool trivial;
160 
161  /// Whether we saved the attributes in the decl spec.
162  bool hasSavedAttrs;
163 
164  /// The original set of attributes on the DeclSpec.
166 
167  /// A list of attributes to diagnose the uselessness of when the
168  /// processing is complete.
169  SmallVector<AttributeList*, 2> ignoredTypeAttrs;
170 
171  public:
172  TypeProcessingState(Sema &sema, Declarator &declarator)
173  : sema(sema), declarator(declarator),
174  chunkIndex(declarator.getNumTypeObjects()),
175  trivial(true), hasSavedAttrs(false) {}
176 
177  Sema &getSema() const {
178  return sema;
179  }
180 
181  Declarator &getDeclarator() const {
182  return declarator;
183  }
184 
185  bool isProcessingDeclSpec() const {
186  return chunkIndex == declarator.getNumTypeObjects();
187  }
188 
189  unsigned getCurrentChunkIndex() const {
190  return chunkIndex;
191  }
192 
193  void setCurrentChunkIndex(unsigned idx) {
194  assert(idx <= declarator.getNumTypeObjects());
195  chunkIndex = idx;
196  }
197 
198  AttributeList *&getCurrentAttrListRef() const {
199  if (isProcessingDeclSpec())
200  return getMutableDeclSpec().getAttributes().getListRef();
201  return declarator.getTypeObject(chunkIndex).getAttrListRef();
202  }
203 
204  /// Save the current set of attributes on the DeclSpec.
205  void saveDeclSpecAttrs() {
206  // Don't try to save them multiple times.
207  if (hasSavedAttrs) return;
208 
209  DeclSpec &spec = getMutableDeclSpec();
210  for (AttributeList *attr = spec.getAttributes().getList(); attr;
211  attr = attr->getNext())
212  savedAttrs.push_back(attr);
213  trivial &= savedAttrs.empty();
214  hasSavedAttrs = true;
215  }
216 
217  /// Record that we had nowhere to put the given type attribute.
218  /// We will diagnose such attributes later.
219  void addIgnoredTypeAttr(AttributeList &attr) {
220  ignoredTypeAttrs.push_back(&attr);
221  }
222 
223  /// Diagnose all the ignored type attributes, given that the
224  /// declarator worked out to the given type.
225  void diagnoseIgnoredTypeAttrs(QualType type) const {
226  for (auto *Attr : ignoredTypeAttrs)
227  diagnoseBadTypeAttribute(getSema(), *Attr, type);
228  }
229 
230  ~TypeProcessingState() {
231  if (trivial) return;
232 
233  restoreDeclSpecAttrs();
234  }
235 
236  private:
237  DeclSpec &getMutableDeclSpec() const {
238  return const_cast<DeclSpec&>(declarator.getDeclSpec());
239  }
240 
241  void restoreDeclSpecAttrs() {
242  assert(hasSavedAttrs);
243 
244  if (savedAttrs.empty()) {
245  getMutableDeclSpec().getAttributes().set(nullptr);
246  return;
247  }
248 
249  getMutableDeclSpec().getAttributes().set(savedAttrs[0]);
250  for (unsigned i = 0, e = savedAttrs.size() - 1; i != e; ++i)
251  savedAttrs[i]->setNext(savedAttrs[i+1]);
252  savedAttrs.back()->setNext(nullptr);
253  }
254  };
255 } // end anonymous namespace
256 
257 static void spliceAttrIntoList(AttributeList &attr, AttributeList *&head) {
258  attr.setNext(head);
259  head = &attr;
260 }
261 
262 static void spliceAttrOutOfList(AttributeList &attr, AttributeList *&head) {
263  if (head == &attr) {
264  head = attr.getNext();
265  return;
266  }
267 
268  AttributeList *cur = head;
269  while (true) {
270  assert(cur && cur->getNext() && "ran out of attrs?");
271  if (cur->getNext() == &attr) {
272  cur->setNext(attr.getNext());
273  return;
274  }
275  cur = cur->getNext();
276  }
277 }
278 
280  AttributeList *&fromList,
281  AttributeList *&toList) {
282  spliceAttrOutOfList(attr, fromList);
283  spliceAttrIntoList(attr, toList);
284 }
285 
286 /// The location of a type attribute.
288  /// The attribute is in the decl-specifier-seq.
290  /// The attribute is part of a DeclaratorChunk.
292  /// The attribute is immediately after the declaration's name.
294 };
295 
296 static void processTypeAttrs(TypeProcessingState &state,
298  AttributeList *attrs);
299 
300 static bool handleFunctionTypeAttr(TypeProcessingState &state,
301  AttributeList &attr,
302  QualType &type);
303 
304 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &state,
305  AttributeList &attr,
306  QualType &type);
307 
308 static bool handleObjCGCTypeAttr(TypeProcessingState &state,
309  AttributeList &attr, QualType &type);
310 
311 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
312  AttributeList &attr, QualType &type);
313 
314 static bool handleObjCPointerTypeAttr(TypeProcessingState &state,
315  AttributeList &attr, QualType &type) {
316  if (attr.getKind() == AttributeList::AT_ObjCGC)
317  return handleObjCGCTypeAttr(state, attr, type);
318  assert(attr.getKind() == AttributeList::AT_ObjCOwnership);
319  return handleObjCOwnershipTypeAttr(state, attr, type);
320 }
321 
322 /// Given the index of a declarator chunk, check whether that chunk
323 /// directly specifies the return type of a function and, if so, find
324 /// an appropriate place for it.
325 ///
326 /// \param i - a notional index which the search will start
327 /// immediately inside
328 ///
329 /// \param onlyBlockPointers Whether we should only look into block
330 /// pointer types (vs. all pointer types).
332  unsigned i,
333  bool onlyBlockPointers) {
334  assert(i <= declarator.getNumTypeObjects());
335 
336  DeclaratorChunk *result = nullptr;
337 
338  // First, look inwards past parens for a function declarator.
339  for (; i != 0; --i) {
340  DeclaratorChunk &fnChunk = declarator.getTypeObject(i-1);
341  switch (fnChunk.Kind) {
343  continue;
344 
345  // If we find anything except a function, bail out.
352  return result;
353 
354  // If we do find a function declarator, scan inwards from that,
355  // looking for a (block-)pointer declarator.
357  for (--i; i != 0; --i) {
358  DeclaratorChunk &ptrChunk = declarator.getTypeObject(i-1);
359  switch (ptrChunk.Kind) {
365  continue;
366 
369  if (onlyBlockPointers)
370  continue;
371 
372  LLVM_FALLTHROUGH;
373 
375  result = &ptrChunk;
376  goto continue_outer;
377  }
378  llvm_unreachable("bad declarator chunk kind");
379  }
380 
381  // If we run out of declarators doing that, we're done.
382  return result;
383  }
384  llvm_unreachable("bad declarator chunk kind");
385 
386  // Okay, reconsider from our new point.
387  continue_outer: ;
388  }
389 
390  // Ran out of chunks, bail out.
391  return result;
392 }
393 
394 /// Given that an objc_gc attribute was written somewhere on a
395 /// declaration *other* than on the declarator itself (for which, use
396 /// distributeObjCPointerTypeAttrFromDeclarator), and given that it
397 /// didn't apply in whatever position it was written in, try to move
398 /// it to a more appropriate position.
399 static void distributeObjCPointerTypeAttr(TypeProcessingState &state,
400  AttributeList &attr,
401  QualType type) {
402  Declarator &declarator = state.getDeclarator();
403 
404  // Move it to the outermost normal or block pointer declarator.
405  for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
406  DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
407  switch (chunk.Kind) {
410  // But don't move an ARC ownership attribute to the return type
411  // of a block.
412  DeclaratorChunk *destChunk = nullptr;
413  if (state.isProcessingDeclSpec() &&
414  attr.getKind() == AttributeList::AT_ObjCOwnership)
415  destChunk = maybeMovePastReturnType(declarator, i - 1,
416  /*onlyBlockPointers=*/true);
417  if (!destChunk) destChunk = &chunk;
418 
419  moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
420  destChunk->getAttrListRef());
421  return;
422  }
423 
426  continue;
427 
428  // We may be starting at the return type of a block.
430  if (state.isProcessingDeclSpec() &&
431  attr.getKind() == AttributeList::AT_ObjCOwnership) {
433  declarator, i,
434  /*onlyBlockPointers=*/true)) {
435  moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
436  dest->getAttrListRef());
437  return;
438  }
439  }
440  goto error;
441 
442  // Don't walk through these.
446  goto error;
447  }
448  }
449  error:
450 
451  diagnoseBadTypeAttribute(state.getSema(), attr, type);
452 }
453 
454 /// Distribute an objc_gc type attribute that was written on the
455 /// declarator.
456 static void
458  AttributeList &attr,
459  QualType &declSpecType) {
460  Declarator &declarator = state.getDeclarator();
461 
462  // objc_gc goes on the innermost pointer to something that's not a
463  // pointer.
464  unsigned innermost = -1U;
465  bool considerDeclSpec = true;
466  for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
467  DeclaratorChunk &chunk = declarator.getTypeObject(i);
468  switch (chunk.Kind) {
471  innermost = i;
472  continue;
473 
479  continue;
480 
482  considerDeclSpec = false;
483  goto done;
484  }
485  }
486  done:
487 
488  // That might actually be the decl spec if we weren't blocked by
489  // anything in the declarator.
490  if (considerDeclSpec) {
491  if (handleObjCPointerTypeAttr(state, attr, declSpecType)) {
492  // Splice the attribute into the decl spec. Prevents the
493  // attribute from being applied multiple times and gives
494  // the source-location-filler something to work with.
495  state.saveDeclSpecAttrs();
496  moveAttrFromListToList(attr, declarator.getAttrListRef(),
497  declarator.getMutableDeclSpec().getAttributes().getListRef());
498  return;
499  }
500  }
501 
502  // Otherwise, if we found an appropriate chunk, splice the attribute
503  // into it.
504  if (innermost != -1U) {
505  moveAttrFromListToList(attr, declarator.getAttrListRef(),
506  declarator.getTypeObject(innermost).getAttrListRef());
507  return;
508  }
509 
510  // Otherwise, diagnose when we're done building the type.
511  spliceAttrOutOfList(attr, declarator.getAttrListRef());
512  state.addIgnoredTypeAttr(attr);
513 }
514 
515 /// A function type attribute was written somewhere in a declaration
516 /// *other* than on the declarator itself or in the decl spec. Given
517 /// that it didn't apply in whatever position it was written in, try
518 /// to move it to a more appropriate position.
519 static void distributeFunctionTypeAttr(TypeProcessingState &state,
520  AttributeList &attr,
521  QualType type) {
522  Declarator &declarator = state.getDeclarator();
523 
524  // Try to push the attribute from the return type of a function to
525  // the function itself.
526  for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
527  DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
528  switch (chunk.Kind) {
530  moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
531  chunk.getAttrListRef());
532  return;
533 
541  continue;
542  }
543  }
544 
545  diagnoseBadTypeAttribute(state.getSema(), attr, type);
546 }
547 
548 /// Try to distribute a function type attribute to the innermost
549 /// function chunk or type. Returns true if the attribute was
550 /// distributed, false if no location was found.
551 static bool
553  AttributeList &attr,
554  AttributeList *&attrList,
555  QualType &declSpecType) {
556  Declarator &declarator = state.getDeclarator();
557 
558  // Put it on the innermost function chunk, if there is one.
559  for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
560  DeclaratorChunk &chunk = declarator.getTypeObject(i);
561  if (chunk.Kind != DeclaratorChunk::Function) continue;
562 
563  moveAttrFromListToList(attr, attrList, chunk.getAttrListRef());
564  return true;
565  }
566 
567  return handleFunctionTypeAttr(state, attr, declSpecType);
568 }
569 
570 /// A function type attribute was written in the decl spec. Try to
571 /// apply it somewhere.
572 static void
574  AttributeList &attr,
575  QualType &declSpecType) {
576  state.saveDeclSpecAttrs();
577 
578  // C++11 attributes before the decl specifiers actually appertain to
579  // the declarators. Move them straight there. We don't support the
580  // 'put them wherever you like' semantics we allow for GNU attributes.
581  if (attr.isCXX11Attribute()) {
582  moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
583  state.getDeclarator().getAttrListRef());
584  return;
585  }
586 
587  // Try to distribute to the innermost.
589  state.getCurrentAttrListRef(),
590  declSpecType))
591  return;
592 
593  // If that failed, diagnose the bad attribute when the declarator is
594  // fully built.
595  state.addIgnoredTypeAttr(attr);
596 }
597 
598 /// A function type attribute was written on the declarator. Try to
599 /// apply it somewhere.
600 static void
602  AttributeList &attr,
603  QualType &declSpecType) {
604  Declarator &declarator = state.getDeclarator();
605 
606  // Try to distribute to the innermost.
608  declarator.getAttrListRef(),
609  declSpecType))
610  return;
611 
612  // If that failed, diagnose the bad attribute when the declarator is
613  // fully built.
614  spliceAttrOutOfList(attr, declarator.getAttrListRef());
615  state.addIgnoredTypeAttr(attr);
616 }
617 
618 /// Given that there are attributes written on the declarator
619 /// itself, try to distribute any type attributes to the appropriate
620 /// declarator chunk.
621 ///
622 /// These are attributes like the following:
623 /// int f ATTR;
624 /// int (f ATTR)();
625 /// but not necessarily this:
626 /// int f() ATTR;
627 static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state,
628  QualType &declSpecType) {
629  // Collect all the type attributes from the declarator itself.
630  assert(state.getDeclarator().getAttributes() && "declarator has no attrs!");
631  AttributeList *attr = state.getDeclarator().getAttributes();
632  AttributeList *next;
633  do {
634  next = attr->getNext();
635 
636  // Do not distribute C++11 attributes. They have strict rules for what
637  // they appertain to.
638  if (attr->isCXX11Attribute())
639  continue;
640 
641  switch (attr->getKind()) {
643  distributeObjCPointerTypeAttrFromDeclarator(state, *attr, declSpecType);
644  break;
645 
647  distributeFunctionTypeAttrFromDeclarator(state, *attr, declSpecType);
648  break;
649 
651  // Microsoft type attributes cannot go after the declarator-id.
652  continue;
653 
655  // Nullability specifiers cannot go after the declarator-id.
656 
657  // Objective-C __kindof does not get distributed.
658  case AttributeList::AT_ObjCKindOf:
659  continue;
660 
661  default:
662  break;
663  }
664  } while ((attr = next));
665 }
666 
667 /// Add a synthetic '()' to a block-literal declarator if it is
668 /// required, given the return type.
669 static void maybeSynthesizeBlockSignature(TypeProcessingState &state,
670  QualType declSpecType) {
671  Declarator &declarator = state.getDeclarator();
672 
673  // First, check whether the declarator would produce a function,
674  // i.e. whether the innermost semantic chunk is a function.
675  if (declarator.isFunctionDeclarator()) {
676  // If so, make that declarator a prototyped declarator.
677  declarator.getFunctionTypeInfo().hasPrototype = true;
678  return;
679  }
680 
681  // If there are any type objects, the type as written won't name a
682  // function, regardless of the decl spec type. This is because a
683  // block signature declarator is always an abstract-declarator, and
684  // abstract-declarators can't just be parentheses chunks. Therefore
685  // we need to build a function chunk unless there are no type
686  // objects and the decl spec type is a function.
687  if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType())
688  return;
689 
690  // Note that there *are* cases with invalid declarators where
691  // declarators consist solely of parentheses. In general, these
692  // occur only in failed efforts to make function declarators, so
693  // faking up the function chunk is still the right thing to do.
694 
695  // Otherwise, we need to fake up a function declarator.
696  SourceLocation loc = declarator.getLocStart();
697 
698  // ...and *prepend* it to the declarator.
699  SourceLocation NoLoc;
701  /*HasProto=*/true,
702  /*IsAmbiguous=*/false,
703  /*LParenLoc=*/NoLoc,
704  /*ArgInfo=*/nullptr,
705  /*NumArgs=*/0,
706  /*EllipsisLoc=*/NoLoc,
707  /*RParenLoc=*/NoLoc,
708  /*TypeQuals=*/0,
709  /*RefQualifierIsLvalueRef=*/true,
710  /*RefQualifierLoc=*/NoLoc,
711  /*ConstQualifierLoc=*/NoLoc,
712  /*VolatileQualifierLoc=*/NoLoc,
713  /*RestrictQualifierLoc=*/NoLoc,
714  /*MutableLoc=*/NoLoc, EST_None,
715  /*ESpecRange=*/SourceRange(),
716  /*Exceptions=*/nullptr,
717  /*ExceptionRanges=*/nullptr,
718  /*NumExceptions=*/0,
719  /*NoexceptExpr=*/nullptr,
720  /*ExceptionSpecTokens=*/nullptr,
721  /*DeclsInPrototype=*/None,
722  loc, loc, declarator));
723 
724  // For consistency, make sure the state still has us as processing
725  // the decl spec.
726  assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1);
727  state.setCurrentChunkIndex(declarator.getNumTypeObjects());
728 }
729 
731  unsigned &TypeQuals,
732  QualType TypeSoFar,
733  unsigned RemoveTQs,
734  unsigned DiagID) {
735  // If this occurs outside a template instantiation, warn the user about
736  // it; they probably didn't mean to specify a redundant qualifier.
737  typedef std::pair<DeclSpec::TQ, SourceLocation> QualLoc;
738  for (QualLoc Qual : {QualLoc(DeclSpec::TQ_const, DS.getConstSpecLoc()),
741  QualLoc(DeclSpec::TQ_atomic, DS.getAtomicSpecLoc())}) {
742  if (!(RemoveTQs & Qual.first))
743  continue;
744 
745  if (!S.inTemplateInstantiation()) {
746  if (TypeQuals & Qual.first)
747  S.Diag(Qual.second, DiagID)
748  << DeclSpec::getSpecifierName(Qual.first) << TypeSoFar
749  << FixItHint::CreateRemoval(Qual.second);
750  }
751 
752  TypeQuals &= ~Qual.first;
753  }
754 }
755 
756 /// Return true if this is omitted block return type. Also check type
757 /// attributes and type qualifiers when returning true.
758 static bool checkOmittedBlockReturnType(Sema &S, Declarator &declarator,
759  QualType Result) {
760  if (!isOmittedBlockReturnType(declarator))
761  return false;
762 
763  // Warn if we see type attributes for omitted return type on a block literal.
764  AttributeList *&attrs =
766  AttributeList *prev = nullptr;
767  for (AttributeList *cur = attrs; cur; cur = cur->getNext()) {
768  AttributeList &attr = *cur;
769  // Skip attributes that were marked to be invalid or non-type
770  // attributes.
771  if (attr.isInvalid() || !attr.isTypeAttr()) {
772  prev = cur;
773  continue;
774  }
775  S.Diag(attr.getLoc(),
776  diag::warn_block_literal_attributes_on_omitted_return_type)
777  << attr.getName();
778  // Remove cur from the list.
779  if (prev) {
780  prev->setNext(cur->getNext());
781  prev = cur;
782  } else {
783  attrs = cur->getNext();
784  }
785  }
786 
787  // Warn if we see type qualifiers for omitted return type on a block literal.
788  const DeclSpec &DS = declarator.getDeclSpec();
789  unsigned TypeQuals = DS.getTypeQualifiers();
790  diagnoseAndRemoveTypeQualifiers(S, DS, TypeQuals, Result, (unsigned)-1,
791  diag::warn_block_literal_qualifiers_on_omitted_return_type);
793 
794  return true;
795 }
796 
797 /// Apply Objective-C type arguments to the given type.
800  SourceRange typeArgsRange,
801  bool failOnError = false) {
802  // We can only apply type arguments to an Objective-C class type.
803  const auto *objcObjectType = type->getAs<ObjCObjectType>();
804  if (!objcObjectType || !objcObjectType->getInterface()) {
805  S.Diag(loc, diag::err_objc_type_args_non_class)
806  << type
807  << typeArgsRange;
808 
809  if (failOnError)
810  return QualType();
811  return type;
812  }
813 
814  // The class type must be parameterized.
815  ObjCInterfaceDecl *objcClass = objcObjectType->getInterface();
816  ObjCTypeParamList *typeParams = objcClass->getTypeParamList();
817  if (!typeParams) {
818  S.Diag(loc, diag::err_objc_type_args_non_parameterized_class)
819  << objcClass->getDeclName()
820  << FixItHint::CreateRemoval(typeArgsRange);
821 
822  if (failOnError)
823  return QualType();
824 
825  return type;
826  }
827 
828  // The type must not already be specialized.
829  if (objcObjectType->isSpecialized()) {
830  S.Diag(loc, diag::err_objc_type_args_specialized_class)
831  << type
832  << FixItHint::CreateRemoval(typeArgsRange);
833 
834  if (failOnError)
835  return QualType();
836 
837  return type;
838  }
839 
840  // Check the type arguments.
841  SmallVector<QualType, 4> finalTypeArgs;
842  unsigned numTypeParams = typeParams->size();
843  bool anyPackExpansions = false;
844  for (unsigned i = 0, n = typeArgs.size(); i != n; ++i) {
845  TypeSourceInfo *typeArgInfo = typeArgs[i];
846  QualType typeArg = typeArgInfo->getType();
847 
848  // Type arguments cannot have explicit qualifiers or nullability.
849  // We ignore indirect sources of these, e.g. behind typedefs or
850  // template arguments.
851  if (TypeLoc qual = typeArgInfo->getTypeLoc().findExplicitQualifierLoc()) {
852  bool diagnosed = false;
853  SourceRange rangeToRemove;
854  if (auto attr = qual.getAs<AttributedTypeLoc>()) {
855  rangeToRemove = attr.getLocalSourceRange();
856  if (attr.getTypePtr()->getImmediateNullability()) {
857  typeArg = attr.getTypePtr()->getModifiedType();
858  S.Diag(attr.getLocStart(),
859  diag::err_objc_type_arg_explicit_nullability)
860  << typeArg << FixItHint::CreateRemoval(rangeToRemove);
861  diagnosed = true;
862  }
863  }
864 
865  if (!diagnosed) {
866  S.Diag(qual.getLocStart(), diag::err_objc_type_arg_qualified)
867  << typeArg << typeArg.getQualifiers().getAsString()
868  << FixItHint::CreateRemoval(rangeToRemove);
869  }
870  }
871 
872  // Remove qualifiers even if they're non-local.
873  typeArg = typeArg.getUnqualifiedType();
874 
875  finalTypeArgs.push_back(typeArg);
876 
877  if (typeArg->getAs<PackExpansionType>())
878  anyPackExpansions = true;
879 
880  // Find the corresponding type parameter, if there is one.
881  ObjCTypeParamDecl *typeParam = nullptr;
882  if (!anyPackExpansions) {
883  if (i < numTypeParams) {
884  typeParam = typeParams->begin()[i];
885  } else {
886  // Too many arguments.
887  S.Diag(loc, diag::err_objc_type_args_wrong_arity)
888  << false
889  << objcClass->getDeclName()
890  << (unsigned)typeArgs.size()
891  << numTypeParams;
892  S.Diag(objcClass->getLocation(), diag::note_previous_decl)
893  << objcClass;
894 
895  if (failOnError)
896  return QualType();
897 
898  return type;
899  }
900  }
901 
902  // Objective-C object pointer types must be substitutable for the bounds.
903  if (const auto *typeArgObjC = typeArg->getAs<ObjCObjectPointerType>()) {
904  // If we don't have a type parameter to match against, assume
905  // everything is fine. There was a prior pack expansion that
906  // means we won't be able to match anything.
907  if (!typeParam) {
908  assert(anyPackExpansions && "Too many arguments?");
909  continue;
910  }
911 
912  // Retrieve the bound.
913  QualType bound = typeParam->getUnderlyingType();
914  const auto *boundObjC = bound->getAs<ObjCObjectPointerType>();
915 
916  // Determine whether the type argument is substitutable for the bound.
917  if (typeArgObjC->isObjCIdType()) {
918  // When the type argument is 'id', the only acceptable type
919  // parameter bound is 'id'.
920  if (boundObjC->isObjCIdType())
921  continue;
922  } else if (S.Context.canAssignObjCInterfaces(boundObjC, typeArgObjC)) {
923  // Otherwise, we follow the assignability rules.
924  continue;
925  }
926 
927  // Diagnose the mismatch.
928  S.Diag(typeArgInfo->getTypeLoc().getLocStart(),
929  diag::err_objc_type_arg_does_not_match_bound)
930  << typeArg << bound << typeParam->getDeclName();
931  S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here)
932  << typeParam->getDeclName();
933 
934  if (failOnError)
935  return QualType();
936 
937  return type;
938  }
939 
940  // Block pointer types are permitted for unqualified 'id' bounds.
941  if (typeArg->isBlockPointerType()) {
942  // If we don't have a type parameter to match against, assume
943  // everything is fine. There was a prior pack expansion that
944  // means we won't be able to match anything.
945  if (!typeParam) {
946  assert(anyPackExpansions && "Too many arguments?");
947  continue;
948  }
949 
950  // Retrieve the bound.
951  QualType bound = typeParam->getUnderlyingType();
953  continue;
954 
955  // Diagnose the mismatch.
956  S.Diag(typeArgInfo->getTypeLoc().getLocStart(),
957  diag::err_objc_type_arg_does_not_match_bound)
958  << typeArg << bound << typeParam->getDeclName();
959  S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here)
960  << typeParam->getDeclName();
961 
962  if (failOnError)
963  return QualType();
964 
965  return type;
966  }
967 
968  // Dependent types will be checked at instantiation time.
969  if (typeArg->isDependentType()) {
970  continue;
971  }
972 
973  // Diagnose non-id-compatible type arguments.
974  S.Diag(typeArgInfo->getTypeLoc().getLocStart(),
975  diag::err_objc_type_arg_not_id_compatible)
976  << typeArg
977  << typeArgInfo->getTypeLoc().getSourceRange();
978 
979  if (failOnError)
980  return QualType();
981 
982  return type;
983  }
984 
985  // Make sure we didn't have the wrong number of arguments.
986  if (!anyPackExpansions && finalTypeArgs.size() != numTypeParams) {
987  S.Diag(loc, diag::err_objc_type_args_wrong_arity)
988  << (typeArgs.size() < typeParams->size())
989  << objcClass->getDeclName()
990  << (unsigned)finalTypeArgs.size()
991  << (unsigned)numTypeParams;
992  S.Diag(objcClass->getLocation(), diag::note_previous_decl)
993  << objcClass;
994 
995  if (failOnError)
996  return QualType();
997 
998  return type;
999  }
1000 
1001  // Success. Form the specialized type.
1002  return S.Context.getObjCObjectType(type, finalTypeArgs, { }, false);
1003 }
1004 
1006  SourceLocation ProtocolLAngleLoc,
1007  ArrayRef<ObjCProtocolDecl *> Protocols,
1008  ArrayRef<SourceLocation> ProtocolLocs,
1009  SourceLocation ProtocolRAngleLoc,
1010  bool FailOnError) {
1011  QualType Result = QualType(Decl->getTypeForDecl(), 0);
1012  if (!Protocols.empty()) {
1013  bool HasError;
1014  Result = Context.applyObjCProtocolQualifiers(Result, Protocols,
1015  HasError);
1016  if (HasError) {
1017  Diag(SourceLocation(), diag::err_invalid_protocol_qualifiers)
1018  << SourceRange(ProtocolLAngleLoc, ProtocolRAngleLoc);
1019  if (FailOnError) Result = QualType();
1020  }
1021  if (FailOnError && Result.isNull())
1022  return QualType();
1023  }
1024 
1025  return Result;
1026 }
1027 
1029  SourceLocation Loc,
1030  SourceLocation TypeArgsLAngleLoc,
1031  ArrayRef<TypeSourceInfo *> TypeArgs,
1032  SourceLocation TypeArgsRAngleLoc,
1033  SourceLocation ProtocolLAngleLoc,
1034  ArrayRef<ObjCProtocolDecl *> Protocols,
1035  ArrayRef<SourceLocation> ProtocolLocs,
1036  SourceLocation ProtocolRAngleLoc,
1037  bool FailOnError) {
1038  QualType Result = BaseType;
1039  if (!TypeArgs.empty()) {
1040  Result = applyObjCTypeArgs(*this, Loc, Result, TypeArgs,
1041  SourceRange(TypeArgsLAngleLoc,
1042  TypeArgsRAngleLoc),
1043  FailOnError);
1044  if (FailOnError && Result.isNull())
1045  return QualType();
1046  }
1047 
1048  if (!Protocols.empty()) {
1049  bool HasError;
1050  Result = Context.applyObjCProtocolQualifiers(Result, Protocols,
1051  HasError);
1052  if (HasError) {
1053  Diag(Loc, diag::err_invalid_protocol_qualifiers)
1054  << SourceRange(ProtocolLAngleLoc, ProtocolRAngleLoc);
1055  if (FailOnError) Result = QualType();
1056  }
1057  if (FailOnError && Result.isNull())
1058  return QualType();
1059  }
1060 
1061  return Result;
1062 }
1063 
1065  SourceLocation lAngleLoc,
1066  ArrayRef<Decl *> protocols,
1067  ArrayRef<SourceLocation> protocolLocs,
1068  SourceLocation rAngleLoc) {
1069  // Form id<protocol-list>.
1070  QualType Result = Context.getObjCObjectType(
1071  Context.ObjCBuiltinIdTy, { },
1072  llvm::makeArrayRef(
1073  (ObjCProtocolDecl * const *)protocols.data(),
1074  protocols.size()),
1075  false);
1076  Result = Context.getObjCObjectPointerType(Result);
1077 
1078  TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result);
1079  TypeLoc ResultTL = ResultTInfo->getTypeLoc();
1080 
1081  auto ObjCObjectPointerTL = ResultTL.castAs<ObjCObjectPointerTypeLoc>();
1082  ObjCObjectPointerTL.setStarLoc(SourceLocation()); // implicit
1083 
1084  auto ObjCObjectTL = ObjCObjectPointerTL.getPointeeLoc()
1085  .castAs<ObjCObjectTypeLoc>();
1086  ObjCObjectTL.setHasBaseTypeAsWritten(false);
1087  ObjCObjectTL.getBaseLoc().initialize(Context, SourceLocation());
1088 
1089  // No type arguments.
1090  ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation());
1091  ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation());
1092 
1093  // Fill in protocol qualifiers.
1094  ObjCObjectTL.setProtocolLAngleLoc(lAngleLoc);
1095  ObjCObjectTL.setProtocolRAngleLoc(rAngleLoc);
1096  for (unsigned i = 0, n = protocols.size(); i != n; ++i)
1097  ObjCObjectTL.setProtocolLoc(i, protocolLocs[i]);
1098 
1099  // We're done. Return the completed type to the parser.
1100  return CreateParsedType(Result, ResultTInfo);
1101 }
1102 
1104  Scope *S,
1105  SourceLocation Loc,
1106  ParsedType BaseType,
1107  SourceLocation TypeArgsLAngleLoc,
1108  ArrayRef<ParsedType> TypeArgs,
1109  SourceLocation TypeArgsRAngleLoc,
1110  SourceLocation ProtocolLAngleLoc,
1111  ArrayRef<Decl *> Protocols,
1112  ArrayRef<SourceLocation> ProtocolLocs,
1113  SourceLocation ProtocolRAngleLoc) {
1114  TypeSourceInfo *BaseTypeInfo = nullptr;
1115  QualType T = GetTypeFromParser(BaseType, &BaseTypeInfo);
1116  if (T.isNull())
1117  return true;
1118 
1119  // Handle missing type-source info.
1120  if (!BaseTypeInfo)
1121  BaseTypeInfo = Context.getTrivialTypeSourceInfo(T, Loc);
1122 
1123  // Extract type arguments.
1124  SmallVector<TypeSourceInfo *, 4> ActualTypeArgInfos;
1125  for (unsigned i = 0, n = TypeArgs.size(); i != n; ++i) {
1126  TypeSourceInfo *TypeArgInfo = nullptr;
1127  QualType TypeArg = GetTypeFromParser(TypeArgs[i], &TypeArgInfo);
1128  if (TypeArg.isNull()) {
1129  ActualTypeArgInfos.clear();
1130  break;
1131  }
1132 
1133  assert(TypeArgInfo && "No type source info?");
1134  ActualTypeArgInfos.push_back(TypeArgInfo);
1135  }
1136 
1137  // Build the object type.
1138  QualType Result = BuildObjCObjectType(
1139  T, BaseTypeInfo->getTypeLoc().getSourceRange().getBegin(),
1140  TypeArgsLAngleLoc, ActualTypeArgInfos, TypeArgsRAngleLoc,
1141  ProtocolLAngleLoc,
1142  llvm::makeArrayRef((ObjCProtocolDecl * const *)Protocols.data(),
1143  Protocols.size()),
1144  ProtocolLocs, ProtocolRAngleLoc,
1145  /*FailOnError=*/false);
1146 
1147  if (Result == T)
1148  return BaseType;
1149 
1150  // Create source information for this type.
1151  TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result);
1152  TypeLoc ResultTL = ResultTInfo->getTypeLoc();
1153 
1154  // For id<Proto1, Proto2> or Class<Proto1, Proto2>, we'll have an
1155  // object pointer type. Fill in source information for it.
1156  if (auto ObjCObjectPointerTL = ResultTL.getAs<ObjCObjectPointerTypeLoc>()) {
1157  // The '*' is implicit.
1158  ObjCObjectPointerTL.setStarLoc(SourceLocation());
1159  ResultTL = ObjCObjectPointerTL.getPointeeLoc();
1160  }
1161 
1162  if (auto OTPTL = ResultTL.getAs<ObjCTypeParamTypeLoc>()) {
1163  // Protocol qualifier information.
1164  if (OTPTL.getNumProtocols() > 0) {
1165  assert(OTPTL.getNumProtocols() == Protocols.size());
1166  OTPTL.setProtocolLAngleLoc(ProtocolLAngleLoc);
1167  OTPTL.setProtocolRAngleLoc(ProtocolRAngleLoc);
1168  for (unsigned i = 0, n = Protocols.size(); i != n; ++i)
1169  OTPTL.setProtocolLoc(i, ProtocolLocs[i]);
1170  }
1171 
1172  // We're done. Return the completed type to the parser.
1173  return CreateParsedType(Result, ResultTInfo);
1174  }
1175 
1176  auto ObjCObjectTL = ResultTL.castAs<ObjCObjectTypeLoc>();
1177 
1178  // Type argument information.
1179  if (ObjCObjectTL.getNumTypeArgs() > 0) {
1180  assert(ObjCObjectTL.getNumTypeArgs() == ActualTypeArgInfos.size());
1181  ObjCObjectTL.setTypeArgsLAngleLoc(TypeArgsLAngleLoc);
1182  ObjCObjectTL.setTypeArgsRAngleLoc(TypeArgsRAngleLoc);
1183  for (unsigned i = 0, n = ActualTypeArgInfos.size(); i != n; ++i)
1184  ObjCObjectTL.setTypeArgTInfo(i, ActualTypeArgInfos[i]);
1185  } else {
1186  ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation());
1187  ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation());
1188  }
1189 
1190  // Protocol qualifier information.
1191  if (ObjCObjectTL.getNumProtocols() > 0) {
1192  assert(ObjCObjectTL.getNumProtocols() == Protocols.size());
1193  ObjCObjectTL.setProtocolLAngleLoc(ProtocolLAngleLoc);
1194  ObjCObjectTL.setProtocolRAngleLoc(ProtocolRAngleLoc);
1195  for (unsigned i = 0, n = Protocols.size(); i != n; ++i)
1196  ObjCObjectTL.setProtocolLoc(i, ProtocolLocs[i]);
1197  } else {
1198  ObjCObjectTL.setProtocolLAngleLoc(SourceLocation());
1199  ObjCObjectTL.setProtocolRAngleLoc(SourceLocation());
1200  }
1201 
1202  // Base type.
1203  ObjCObjectTL.setHasBaseTypeAsWritten(true);
1204  if (ObjCObjectTL.getType() == T)
1205  ObjCObjectTL.getBaseLoc().initializeFullCopy(BaseTypeInfo->getTypeLoc());
1206  else
1207  ObjCObjectTL.getBaseLoc().initialize(Context, Loc);
1208 
1209  // We're done. Return the completed type to the parser.
1210  return CreateParsedType(Result, ResultTInfo);
1211 }
1212 
1213 static OpenCLAccessAttr::Spelling getImageAccess(const AttributeList *Attrs) {
1214  if (Attrs) {
1215  const AttributeList *Next = Attrs;
1216  do {
1217  const AttributeList &Attr = *Next;
1218  Next = Attr.getNext();
1219  if (Attr.getKind() == AttributeList::AT_OpenCLAccess) {
1220  return static_cast<OpenCLAccessAttr::Spelling>(
1221  Attr.getSemanticSpelling());
1222  }
1223  } while (Next);
1224  }
1225  return OpenCLAccessAttr::Keyword_read_only;
1226 }
1227 
1228 /// Convert the specified declspec to the appropriate type
1229 /// object.
1230 /// \param state Specifies the declarator containing the declaration specifier
1231 /// to be converted, along with other associated processing state.
1232 /// \returns The type described by the declaration specifiers. This function
1233 /// never returns null.
1234 static QualType ConvertDeclSpecToType(TypeProcessingState &state) {
1235  // FIXME: Should move the logic from DeclSpec::Finish to here for validity
1236  // checking.
1237 
1238  Sema &S = state.getSema();
1239  Declarator &declarator = state.getDeclarator();
1240  const DeclSpec &DS = declarator.getDeclSpec();
1241  SourceLocation DeclLoc = declarator.getIdentifierLoc();
1242  if (DeclLoc.isInvalid())
1243  DeclLoc = DS.getLocStart();
1244 
1245  ASTContext &Context = S.Context;
1246 
1247  QualType Result;
1248  switch (DS.getTypeSpecType()) {
1249  case DeclSpec::TST_void:
1250  Result = Context.VoidTy;
1251  break;
1252  case DeclSpec::TST_char:
1254  Result = Context.CharTy;
1255  else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed)
1256  Result = Context.SignedCharTy;
1257  else {
1258  assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
1259  "Unknown TSS value");
1260  Result = Context.UnsignedCharTy;
1261  }
1262  break;
1263  case DeclSpec::TST_wchar:
1265  Result = Context.WCharTy;
1266  else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) {
1267  S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
1268  << DS.getSpecifierName(DS.getTypeSpecType(),
1269  Context.getPrintingPolicy());
1270  Result = Context.getSignedWCharType();
1271  } else {
1272  assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
1273  "Unknown TSS value");
1274  S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
1275  << DS.getSpecifierName(DS.getTypeSpecType(),
1276  Context.getPrintingPolicy());
1277  Result = Context.getUnsignedWCharType();
1278  }
1279  break;
1280  case DeclSpec::TST_char8:
1281  assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
1282  "Unknown TSS value");
1283  Result = Context.Char8Ty;
1284  break;
1285  case DeclSpec::TST_char16:
1286  assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
1287  "Unknown TSS value");
1288  Result = Context.Char16Ty;
1289  break;
1290  case DeclSpec::TST_char32:
1291  assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
1292  "Unknown TSS value");
1293  Result = Context.Char32Ty;
1294  break;
1296  // If this is a missing declspec in a block literal return context, then it
1297  // is inferred from the return statements inside the block.
1298  // The declspec is always missing in a lambda expr context; it is either
1299  // specified with a trailing return type or inferred.
1300  if (S.getLangOpts().CPlusPlus14 &&
1302  // In C++1y, a lambda's implicit return type is 'auto'.
1303  Result = Context.getAutoDeductType();
1304  break;
1305  } else if (declarator.getContext() ==
1307  checkOmittedBlockReturnType(S, declarator,
1308  Context.DependentTy)) {
1309  Result = Context.DependentTy;
1310  break;
1311  }
1312 
1313  // Unspecified typespec defaults to int in C90. However, the C90 grammar
1314  // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
1315  // type-qualifier, or storage-class-specifier. If not, emit an extwarn.
1316  // Note that the one exception to this is function definitions, which are
1317  // allowed to be completely missing a declspec. This is handled in the
1318  // parser already though by it pretending to have seen an 'int' in this
1319  // case.
1320  if (S.getLangOpts().ImplicitInt) {
1321  // In C89 mode, we only warn if there is a completely missing declspec
1322  // when one is not allowed.
1323  if (DS.isEmpty()) {
1324  S.Diag(DeclLoc, diag::ext_missing_declspec)
1325  << DS.getSourceRange()
1326  << FixItHint::CreateInsertion(DS.getLocStart(), "int");
1327  }
1328  } else if (!DS.hasTypeSpecifier()) {
1329  // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says:
1330  // "At least one type specifier shall be given in the declaration
1331  // specifiers in each declaration, and in the specifier-qualifier list in
1332  // each struct declaration and type name."
1333  if (S.getLangOpts().CPlusPlus) {
1334  S.Diag(DeclLoc, diag::err_missing_type_specifier)
1335  << DS.getSourceRange();
1336 
1337  // When this occurs in C++ code, often something is very broken with the
1338  // value being declared, poison it as invalid so we don't get chains of
1339  // errors.
1340  declarator.setInvalidType(true);
1341  } else if (S.getLangOpts().OpenCLVersion >= 200 && DS.isTypeSpecPipe()){
1342  S.Diag(DeclLoc, diag::err_missing_actual_pipe_type)
1343  << DS.getSourceRange();
1344  declarator.setInvalidType(true);
1345  } else {
1346  S.Diag(DeclLoc, diag::ext_missing_type_specifier)
1347  << DS.getSourceRange();
1348  }
1349  }
1350 
1351  LLVM_FALLTHROUGH;
1352  case DeclSpec::TST_int: {
1354  switch (DS.getTypeSpecWidth()) {
1355  case DeclSpec::TSW_unspecified: Result = Context.IntTy; break;
1356  case DeclSpec::TSW_short: Result = Context.ShortTy; break;
1357  case DeclSpec::TSW_long: Result = Context.LongTy; break;
1359  Result = Context.LongLongTy;
1360 
1361  // 'long long' is a C99 or C++11 feature.
1362  if (!S.getLangOpts().C99) {
1363  if (S.getLangOpts().CPlusPlus)
1364  S.Diag(DS.getTypeSpecWidthLoc(),
1365  S.getLangOpts().CPlusPlus11 ?
1366  diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
1367  else
1368  S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
1369  }
1370  break;
1371  }
1372  } else {
1373  switch (DS.getTypeSpecWidth()) {
1374  case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break;
1375  case DeclSpec::TSW_short: Result = Context.UnsignedShortTy; break;
1376  case DeclSpec::TSW_long: Result = Context.UnsignedLongTy; break;
1378  Result = Context.UnsignedLongLongTy;
1379 
1380  // 'long long' is a C99 or C++11 feature.
1381  if (!S.getLangOpts().C99) {
1382  if (S.getLangOpts().CPlusPlus)
1383  S.Diag(DS.getTypeSpecWidthLoc(),
1384  S.getLangOpts().CPlusPlus11 ?
1385  diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
1386  else
1387  S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
1388  }
1389  break;
1390  }
1391  }
1392  break;
1393  }
1394  case DeclSpec::TST_accum: {
1395  switch (DS.getTypeSpecWidth()) {
1396  case DeclSpec::TSW_short:
1397  Result = Context.ShortAccumTy;
1398  break;
1400  Result = Context.AccumTy;
1401  break;
1402  case DeclSpec::TSW_long:
1403  Result = Context.LongAccumTy;
1404  break;
1406  llvm_unreachable("Unable to specify long long as _Accum width");
1407  }
1408 
1410  Result = Context.getCorrespondingUnsignedType(Result);
1411 
1412  if (DS.isTypeSpecSat())
1413  Result = Context.getCorrespondingSaturatedType(Result);
1414 
1415  break;
1416  }
1417  case DeclSpec::TST_fract: {
1418  switch (DS.getTypeSpecWidth()) {
1419  case DeclSpec::TSW_short:
1420  Result = Context.ShortFractTy;
1421  break;
1423  Result = Context.FractTy;
1424  break;
1425  case DeclSpec::TSW_long:
1426  Result = Context.LongFractTy;
1427  break;
1429  llvm_unreachable("Unable to specify long long as _Fract width");
1430  }
1431 
1433  Result = Context.getCorrespondingUnsignedType(Result);
1434 
1435  if (DS.isTypeSpecSat())
1436  Result = Context.getCorrespondingSaturatedType(Result);
1437 
1438  break;
1439  }
1440  case DeclSpec::TST_int128:
1441  if (!S.Context.getTargetInfo().hasInt128Type())
1442  S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1443  << "__int128";
1445  Result = Context.UnsignedInt128Ty;
1446  else
1447  Result = Context.Int128Ty;
1448  break;
1449  case DeclSpec::TST_float16: Result = Context.Float16Ty; break;
1450  case DeclSpec::TST_half: Result = Context.HalfTy; break;
1451  case DeclSpec::TST_float: Result = Context.FloatTy; break;
1452  case DeclSpec::TST_double:
1454  Result = Context.LongDoubleTy;
1455  else
1456  Result = Context.DoubleTy;
1457  break;
1460  S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1461  << "__float128";
1462  Result = Context.Float128Ty;
1463  break;
1464  case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool
1465  break;
1466  case DeclSpec::TST_decimal32: // _Decimal32
1467  case DeclSpec::TST_decimal64: // _Decimal64
1468  case DeclSpec::TST_decimal128: // _Decimal128
1469  S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
1470  Result = Context.IntTy;
1471  declarator.setInvalidType(true);
1472  break;
1473  case DeclSpec::TST_class:
1474  case DeclSpec::TST_enum:
1475  case DeclSpec::TST_union:
1476  case DeclSpec::TST_struct:
1477  case DeclSpec::TST_interface: {
1478  TagDecl *D = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl());
1479  if (!D) {
1480  // This can happen in C++ with ambiguous lookups.
1481  Result = Context.IntTy;
1482  declarator.setInvalidType(true);
1483  break;
1484  }
1485 
1486  // If the type is deprecated or unavailable, diagnose it.
1488 
1489  assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
1490  DS.getTypeSpecSign() == 0 && "No qualifiers on tag names!");
1491 
1492  // TypeQuals handled by caller.
1493  Result = Context.getTypeDeclType(D);
1494 
1495  // In both C and C++, make an ElaboratedType.
1496  ElaboratedTypeKeyword Keyword
1498  Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result,
1499  DS.isTypeSpecOwned() ? D : nullptr);
1500  break;
1501  }
1502  case DeclSpec::TST_typename: {
1503  assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
1504  DS.getTypeSpecSign() == 0 &&
1505  "Can't handle qualifiers on typedef names yet!");
1506  Result = S.GetTypeFromParser(DS.getRepAsType());
1507  if (Result.isNull()) {
1508  declarator.setInvalidType(true);
1509  }
1510 
1511  // TypeQuals handled by caller.
1512  break;
1513  }
1515  // FIXME: Preserve type source info.
1516  Result = S.GetTypeFromParser(DS.getRepAsType());
1517  assert(!Result.isNull() && "Didn't get a type for typeof?");
1518  if (!Result->isDependentType())
1519  if (const TagType *TT = Result->getAs<TagType>())
1520  S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc());
1521  // TypeQuals handled by caller.
1522  Result = Context.getTypeOfType(Result);
1523  break;
1524  case DeclSpec::TST_typeofExpr: {
1525  Expr *E = DS.getRepAsExpr();
1526  assert(E && "Didn't get an expression for typeof?");
1527  // TypeQuals handled by caller.
1528  Result = S.BuildTypeofExprType(E, DS.getTypeSpecTypeLoc());
1529  if (Result.isNull()) {
1530  Result = Context.IntTy;
1531  declarator.setInvalidType(true);
1532  }
1533  break;
1534  }
1535  case DeclSpec::TST_decltype: {
1536  Expr *E = DS.getRepAsExpr();
1537  assert(E && "Didn't get an expression for decltype?");
1538  // TypeQuals handled by caller.
1539  Result = S.BuildDecltypeType(E, DS.getTypeSpecTypeLoc());
1540  if (Result.isNull()) {
1541  Result = Context.IntTy;
1542  declarator.setInvalidType(true);
1543  }
1544  break;
1545  }
1547  Result = S.GetTypeFromParser(DS.getRepAsType());
1548  assert(!Result.isNull() && "Didn't get a type for __underlying_type?");
1549  Result = S.BuildUnaryTransformType(Result,
1551  DS.getTypeSpecTypeLoc());
1552  if (Result.isNull()) {
1553  Result = Context.IntTy;
1554  declarator.setInvalidType(true);
1555  }
1556  break;
1557 
1558  case DeclSpec::TST_auto:
1559  Result = Context.getAutoType(QualType(), AutoTypeKeyword::Auto, false);
1560  break;
1561 
1563  Result = Context.getAutoType(QualType(), AutoTypeKeyword::GNUAutoType, false);
1564  break;
1565 
1568  /*IsDependent*/ false);
1569  break;
1570 
1572  Result = Context.UnknownAnyTy;
1573  break;
1574 
1575  case DeclSpec::TST_atomic:
1576  Result = S.GetTypeFromParser(DS.getRepAsType());
1577  assert(!Result.isNull() && "Didn't get a type for _Atomic?");
1578  Result = S.BuildAtomicType(Result, DS.getTypeSpecTypeLoc());
1579  if (Result.isNull()) {
1580  Result = Context.IntTy;
1581  declarator.setInvalidType(true);
1582  }
1583  break;
1584 
1585 #define GENERIC_IMAGE_TYPE(ImgType, Id) \
1586  case DeclSpec::TST_##ImgType##_t: \
1587  switch (getImageAccess(DS.getAttributes().getList())) { \
1588  case OpenCLAccessAttr::Keyword_write_only: \
1589  Result = Context.Id##WOTy; break; \
1590  case OpenCLAccessAttr::Keyword_read_write: \
1591  Result = Context.Id##RWTy; break; \
1592  case OpenCLAccessAttr::Keyword_read_only: \
1593  Result = Context.Id##ROTy; break; \
1594  } \
1595  break;
1596 #include "clang/Basic/OpenCLImageTypes.def"
1597 
1598  case DeclSpec::TST_error:
1599  Result = Context.IntTy;
1600  declarator.setInvalidType(true);
1601  break;
1602  }
1603 
1604  if (S.getLangOpts().OpenCL &&
1606  declarator.setInvalidType(true);
1607 
1608  bool IsFixedPointType = DS.getTypeSpecType() == DeclSpec::TST_accum ||
1609  DS.getTypeSpecType() == DeclSpec::TST_fract;
1610 
1611  // Only fixed point types can be saturated
1612  if (DS.isTypeSpecSat() && !IsFixedPointType)
1613  S.Diag(DS.getTypeSpecSatLoc(), diag::err_invalid_saturation_spec)
1614  << DS.getSpecifierName(DS.getTypeSpecType(),
1615  Context.getPrintingPolicy());
1616 
1617  // Handle complex types.
1618  if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
1619  if (S.getLangOpts().Freestanding)
1620  S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
1621  Result = Context.getComplexType(Result);
1622  } else if (DS.isTypeAltiVecVector()) {
1623  unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result));
1624  assert(typeSize > 0 && "type size for vector must be greater than 0 bits");
1626  if (DS.isTypeAltiVecPixel())
1627  VecKind = VectorType::AltiVecPixel;
1628  else if (DS.isTypeAltiVecBool())
1629  VecKind = VectorType::AltiVecBool;
1630  Result = Context.getVectorType(Result, 128/typeSize, VecKind);
1631  }
1632 
1633  // FIXME: Imaginary.
1634  if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary)
1635  S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported);
1636 
1637  // Before we process any type attributes, synthesize a block literal
1638  // function declarator if necessary.
1639  if (declarator.getContext() == DeclaratorContext::BlockLiteralContext)
1641 
1642  // Apply any type attributes from the decl spec. This may cause the
1643  // list of type attributes to be temporarily saved while the type
1644  // attributes are pushed around.
1645  // pipe attributes will be handled later ( at GetFullTypeForDeclarator )
1646  if (!DS.isTypeSpecPipe())
1647  processTypeAttrs(state, Result, TAL_DeclSpec, DS.getAttributes().getList());
1648 
1649  // Apply const/volatile/restrict qualifiers to T.
1650  if (unsigned TypeQuals = DS.getTypeQualifiers()) {
1651  // Warn about CV qualifiers on function types.
1652  // C99 6.7.3p8:
1653  // If the specification of a function type includes any type qualifiers,
1654  // the behavior is undefined.
1655  // C++11 [dcl.fct]p7:
1656  // The effect of a cv-qualifier-seq in a function declarator is not the
1657  // same as adding cv-qualification on top of the function type. In the
1658  // latter case, the cv-qualifiers are ignored.
1659  if (TypeQuals && Result->isFunctionType()) {
1661  S, DS, TypeQuals, Result, DeclSpec::TQ_const | DeclSpec::TQ_volatile,
1662  S.getLangOpts().CPlusPlus
1663  ? diag::warn_typecheck_function_qualifiers_ignored
1664  : diag::warn_typecheck_function_qualifiers_unspecified);
1665  // No diagnostic for 'restrict' or '_Atomic' applied to a
1666  // function type; we'll diagnose those later, in BuildQualifiedType.
1667  }
1668 
1669  // C++11 [dcl.ref]p1:
1670  // Cv-qualified references are ill-formed except when the
1671  // cv-qualifiers are introduced through the use of a typedef-name
1672  // or decltype-specifier, in which case the cv-qualifiers are ignored.
1673  //
1674  // There don't appear to be any other contexts in which a cv-qualified
1675  // reference type could be formed, so the 'ill-formed' clause here appears
1676  // to never happen.
1677  if (TypeQuals && Result->isReferenceType()) {
1679  S, DS, TypeQuals, Result,
1681  diag::warn_typecheck_reference_qualifiers);
1682  }
1683 
1684  // C90 6.5.3 constraints: "The same type qualifier shall not appear more
1685  // than once in the same specifier-list or qualifier-list, either directly
1686  // or via one or more typedefs."
1687  if (!S.getLangOpts().C99 && !S.getLangOpts().CPlusPlus
1688  && TypeQuals & Result.getCVRQualifiers()) {
1689  if (TypeQuals & DeclSpec::TQ_const && Result.isConstQualified()) {
1690  S.Diag(DS.getConstSpecLoc(), diag::ext_duplicate_declspec)
1691  << "const";
1692  }
1693 
1694  if (TypeQuals & DeclSpec::TQ_volatile && Result.isVolatileQualified()) {
1695  S.Diag(DS.getVolatileSpecLoc(), diag::ext_duplicate_declspec)
1696  << "volatile";
1697  }
1698 
1699  // C90 doesn't have restrict nor _Atomic, so it doesn't force us to
1700  // produce a warning in this case.
1701  }
1702 
1703  QualType Qualified = S.BuildQualifiedType(Result, DeclLoc, TypeQuals, &DS);
1704 
1705  // If adding qualifiers fails, just use the unqualified type.
1706  if (Qualified.isNull())
1707  declarator.setInvalidType(true);
1708  else
1709  Result = Qualified;
1710  }
1711 
1712  assert(!Result.isNull() && "This function should not return a null type");
1713  return Result;
1714 }
1715 
1716 static std::string getPrintableNameForEntity(DeclarationName Entity) {
1717  if (Entity)
1718  return Entity.getAsString();
1719 
1720  return "type name";
1721 }
1722 
1724  Qualifiers Qs, const DeclSpec *DS) {
1725  if (T.isNull())
1726  return QualType();
1727 
1728  // Ignore any attempt to form a cv-qualified reference.
1729  if (T->isReferenceType()) {
1730  Qs.removeConst();
1731  Qs.removeVolatile();
1732  }
1733 
1734  // Enforce C99 6.7.3p2: "Types other than pointer types derived from
1735  // object or incomplete types shall not be restrict-qualified."
1736  if (Qs.hasRestrict()) {
1737  unsigned DiagID = 0;
1738  QualType ProblemTy;
1739 
1740  if (T->isAnyPointerType() || T->isReferenceType() ||
1741  T->isMemberPointerType()) {
1742  QualType EltTy;
1743  if (T->isObjCObjectPointerType())
1744  EltTy = T;
1745  else if (const MemberPointerType *PTy = T->getAs<MemberPointerType>())
1746  EltTy = PTy->getPointeeType();
1747  else
1748  EltTy = T->getPointeeType();
1749 
1750  // If we have a pointer or reference, the pointee must have an object
1751  // incomplete type.
1752  if (!EltTy->isIncompleteOrObjectType()) {
1753  DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1754  ProblemTy = EltTy;
1755  }
1756  } else if (!T->isDependentType()) {
1757  DiagID = diag::err_typecheck_invalid_restrict_not_pointer;
1758  ProblemTy = T;
1759  }
1760 
1761  if (DiagID) {
1762  Diag(DS ? DS->getRestrictSpecLoc() : Loc, DiagID) << ProblemTy;
1763  Qs.removeRestrict();
1764  }
1765  }
1766 
1767  return Context.getQualifiedType(T, Qs);
1768 }
1769 
1771  unsigned CVRAU, const DeclSpec *DS) {
1772  if (T.isNull())
1773  return QualType();
1774 
1775  // Ignore any attempt to form a cv-qualified reference.
1776  if (T->isReferenceType())
1777  CVRAU &=
1779 
1780  // Convert from DeclSpec::TQ to Qualifiers::TQ by just dropping TQ_atomic and
1781  // TQ_unaligned;
1782  unsigned CVR = CVRAU & ~(DeclSpec::TQ_atomic | DeclSpec::TQ_unaligned);
1783 
1784  // C11 6.7.3/5:
1785  // If the same qualifier appears more than once in the same
1786  // specifier-qualifier-list, either directly or via one or more typedefs,
1787  // the behavior is the same as if it appeared only once.
1788  //
1789  // It's not specified what happens when the _Atomic qualifier is applied to
1790  // a type specified with the _Atomic specifier, but we assume that this
1791  // should be treated as if the _Atomic qualifier appeared multiple times.
1792  if (CVRAU & DeclSpec::TQ_atomic && !T->isAtomicType()) {
1793  // C11 6.7.3/5:
1794  // If other qualifiers appear along with the _Atomic qualifier in a
1795  // specifier-qualifier-list, the resulting type is the so-qualified
1796  // atomic type.
1797  //
1798  // Don't need to worry about array types here, since _Atomic can't be
1799  // applied to such types.
1801  T = BuildAtomicType(QualType(Split.Ty, 0),
1802  DS ? DS->getAtomicSpecLoc() : Loc);
1803  if (T.isNull())
1804  return T;
1805  Split.Quals.addCVRQualifiers(CVR);
1806  return BuildQualifiedType(T, Loc, Split.Quals);
1807  }
1808 
1811  return BuildQualifiedType(T, Loc, Q, DS);
1812 }
1813 
1814 /// Build a paren type including \p T.
1816  return Context.getParenType(T);
1817 }
1818 
1819 /// Given that we're building a pointer or reference to the given
1821  SourceLocation loc,
1822  bool isReference) {
1823  // Bail out if retention is unrequired or already specified.
1824  if (!type->isObjCLifetimeType() ||
1826  return type;
1827 
1829 
1830  // If the object type is const-qualified, we can safely use
1831  // __unsafe_unretained. This is safe (because there are no read
1832  // barriers), and it'll be safe to coerce anything but __weak* to
1833  // the resulting type.
1834  if (type.isConstQualified()) {
1835  implicitLifetime = Qualifiers::OCL_ExplicitNone;
1836 
1837  // Otherwise, check whether the static type does not require
1838  // retaining. This currently only triggers for Class (possibly
1839  // protocol-qualifed, and arrays thereof).
1840  } else if (type->isObjCARCImplicitlyUnretainedType()) {
1841  implicitLifetime = Qualifiers::OCL_ExplicitNone;
1842 
1843  // If we are in an unevaluated context, like sizeof, skip adding a
1844  // qualification.
1845  } else if (S.isUnevaluatedContext()) {
1846  return type;
1847 
1848  // If that failed, give an error and recover using __strong. __strong
1849  // is the option most likely to prevent spurious second-order diagnostics,
1850  // like when binding a reference to a field.
1851  } else {
1852  // These types can show up in private ivars in system headers, so
1853  // we need this to not be an error in those cases. Instead we
1854  // want to delay.
1858  diag::err_arc_indirect_no_ownership, type, isReference));
1859  } else {
1860  S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference;
1861  }
1862  implicitLifetime = Qualifiers::OCL_Strong;
1863  }
1864  assert(implicitLifetime && "didn't infer any lifetime!");
1865 
1866  Qualifiers qs;
1867  qs.addObjCLifetime(implicitLifetime);
1868  return S.Context.getQualifiedType(type, qs);
1869 }
1870 
1871 static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){
1872  std::string Quals =
1874 
1875  switch (FnTy->getRefQualifier()) {
1876  case RQ_None:
1877  break;
1878 
1879  case RQ_LValue:
1880  if (!Quals.empty())
1881  Quals += ' ';
1882  Quals += '&';
1883  break;
1884 
1885  case RQ_RValue:
1886  if (!Quals.empty())
1887  Quals += ' ';
1888  Quals += "&&";
1889  break;
1890  }
1891 
1892  return Quals;
1893 }
1894 
1895 namespace {
1896 /// Kinds of declarator that cannot contain a qualified function type.
1897 ///
1898 /// C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6:
1899 /// a function type with a cv-qualifier or a ref-qualifier can only appear
1900 /// at the topmost level of a type.
1901 ///
1902 /// Parens and member pointers are permitted. We don't diagnose array and
1903 /// function declarators, because they don't allow function types at all.
1904 ///
1905 /// The values of this enum are used in diagnostics.
1906 enum QualifiedFunctionKind { QFK_BlockPointer, QFK_Pointer, QFK_Reference };
1907 } // end anonymous namespace
1908 
1909 /// Check whether the type T is a qualified function type, and if it is,
1910 /// diagnose that it cannot be contained within the given kind of declarator.
1912  QualifiedFunctionKind QFK) {
1913  // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
1914  const FunctionProtoType *FPT = T->getAs<FunctionProtoType>();
1915  if (!FPT || (FPT->getTypeQuals() == 0 && FPT->getRefQualifier() == RQ_None))
1916  return false;
1917 
1918  S.Diag(Loc, diag::err_compound_qualified_function_type)
1919  << QFK << isa<FunctionType>(T.IgnoreParens()) << T
1921  return true;
1922 }
1923 
1924 /// Build a pointer type.
1925 ///
1926 /// \param T The type to which we'll be building a pointer.
1927 ///
1928 /// \param Loc The location of the entity whose type involves this
1929 /// pointer type or, if there is no such entity, the location of the
1930 /// type that will have pointer type.
1931 ///
1932 /// \param Entity The name of the entity that involves the pointer
1933 /// type, if known.
1934 ///
1935 /// \returns A suitable pointer type, if there are no
1936 /// errors. Otherwise, returns a NULL type.
1938  SourceLocation Loc, DeclarationName Entity) {
1939  if (T->isReferenceType()) {
1940  // C++ 8.3.2p4: There shall be no ... pointers to references ...
1941  Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
1942  << getPrintableNameForEntity(Entity) << T;
1943  return QualType();
1944  }
1945 
1946  if (T->isFunctionType() && getLangOpts().OpenCL) {
1947  Diag(Loc, diag::err_opencl_function_pointer);
1948  return QualType();
1949  }
1950 
1951  if (checkQualifiedFunction(*this, T, Loc, QFK_Pointer))
1952  return QualType();
1953 
1954  assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType");
1955 
1956  // In ARC, it is forbidden to build pointers to unqualified pointers.
1957  if (getLangOpts().ObjCAutoRefCount)
1958  T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false);
1959 
1960  // Build the pointer type.
1961  return Context.getPointerType(T);
1962 }
1963 
1964 /// Build a reference type.
1965 ///
1966 /// \param T The type to which we'll be building a reference.
1967 ///
1968 /// \param Loc The location of the entity whose type involves this
1969 /// reference type or, if there is no such entity, the location of the
1970 /// type that will have reference type.
1971 ///
1972 /// \param Entity The name of the entity that involves the reference
1973 /// type, if known.
1974 ///
1975 /// \returns A suitable reference type, if there are no
1976 /// errors. Otherwise, returns a NULL type.
1978  SourceLocation Loc,
1979  DeclarationName Entity) {
1980  assert(Context.getCanonicalType(T) != Context.OverloadTy &&
1981  "Unresolved overloaded function type");
1982 
1983  // C++0x [dcl.ref]p6:
1984  // If a typedef (7.1.3), a type template-parameter (14.3.1), or a
1985  // decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a
1986  // type T, an attempt to create the type "lvalue reference to cv TR" creates
1987  // the type "lvalue reference to T", while an attempt to create the type
1988  // "rvalue reference to cv TR" creates the type TR.
1989  bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
1990 
1991  // C++ [dcl.ref]p4: There shall be no references to references.
1992  //
1993  // According to C++ DR 106, references to references are only
1994  // diagnosed when they are written directly (e.g., "int & &"),
1995  // but not when they happen via a typedef:
1996  //
1997  // typedef int& intref;
1998  // typedef intref& intref2;
1999  //
2000  // Parser::ParseDeclaratorInternal diagnoses the case where
2001  // references are written directly; here, we handle the
2002  // collapsing of references-to-references as described in C++0x.
2003  // DR 106 and 540 introduce reference-collapsing into C++98/03.
2004 
2005  // C++ [dcl.ref]p1:
2006  // A declarator that specifies the type "reference to cv void"
2007  // is ill-formed.
2008  if (T->isVoidType()) {
2009  Diag(Loc, diag::err_reference_to_void);
2010  return QualType();
2011  }
2012 
2013  if (checkQualifiedFunction(*this, T, Loc, QFK_Reference))
2014  return QualType();
2015 
2016  // In ARC, it is forbidden to build references to unqualified pointers.
2017  if (getLangOpts().ObjCAutoRefCount)
2018  T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true);
2019 
2020  // Handle restrict on references.
2021  if (LValueRef)
2022  return Context.getLValueReferenceType(T, SpelledAsLValue);
2023  return Context.getRValueReferenceType(T);
2024 }
2025 
2026 /// Build a Read-only Pipe type.
2027 ///
2028 /// \param T The type to which we'll be building a Pipe.
2029 ///
2030 /// \param Loc We do not use it for now.
2031 ///
2032 /// \returns A suitable pipe type, if there are no errors. Otherwise, returns a
2033 /// NULL type.
2035  return Context.getReadPipeType(T);
2036 }
2037 
2038 /// Build a Write-only Pipe type.
2039 ///
2040 /// \param T The type to which we'll be building a Pipe.
2041 ///
2042 /// \param Loc We do not use it for now.
2043 ///
2044 /// \returns A suitable pipe type, if there are no errors. Otherwise, returns a
2045 /// NULL type.
2047  return Context.getWritePipeType(T);
2048 }
2049 
2050 /// Check whether the specified array size makes the array type a VLA. If so,
2051 /// return true, if not, return the size of the array in SizeVal.
2052 static bool isArraySizeVLA(Sema &S, Expr *ArraySize, llvm::APSInt &SizeVal) {
2053  // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode
2054  // (like gnu99, but not c99) accept any evaluatable value as an extension.
2055  class VLADiagnoser : public Sema::VerifyICEDiagnoser {
2056  public:
2057  VLADiagnoser() : Sema::VerifyICEDiagnoser(true) {}
2058 
2059  void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
2060  }
2061 
2062  void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR) override {
2063  S.Diag(Loc, diag::ext_vla_folded_to_constant) << SR;
2064  }
2065  } Diagnoser;
2066 
2067  return S.VerifyIntegerConstantExpression(ArraySize, &SizeVal, Diagnoser,
2068  S.LangOpts.GNUMode ||
2069  S.LangOpts.OpenCL).isInvalid();
2070 }
2071 
2072 /// Build an array type.
2073 ///
2074 /// \param T The type of each element in the array.
2075 ///
2076 /// \param ASM C99 array size modifier (e.g., '*', 'static').
2077 ///
2078 /// \param ArraySize Expression describing the size of the array.
2079 ///
2080 /// \param Brackets The range from the opening '[' to the closing ']'.
2081 ///
2082 /// \param Entity The name of the entity that involves the array
2083 /// type, if known.
2084 ///
2085 /// \returns A suitable array type, if there are no errors. Otherwise,
2086 /// returns a NULL type.
2088  Expr *ArraySize, unsigned Quals,
2089  SourceRange Brackets, DeclarationName Entity) {
2090 
2091  SourceLocation Loc = Brackets.getBegin();
2092  if (getLangOpts().CPlusPlus) {
2093  // C++ [dcl.array]p1:
2094  // T is called the array element type; this type shall not be a reference
2095  // type, the (possibly cv-qualified) type void, a function type or an
2096  // abstract class type.
2097  //
2098  // C++ [dcl.array]p3:
2099  // When several "array of" specifications are adjacent, [...] only the
2100  // first of the constant expressions that specify the bounds of the arrays
2101  // may be omitted.
2102  //
2103  // Note: function types are handled in the common path with C.
2104  if (T->isReferenceType()) {
2105  Diag(Loc, diag::err_illegal_decl_array_of_references)
2106  << getPrintableNameForEntity(Entity) << T;
2107  return QualType();
2108  }
2109 
2110  if (T->isVoidType() || T->isIncompleteArrayType()) {
2111  Diag(Loc, diag::err_illegal_decl_array_incomplete_type) << T;
2112  return QualType();
2113  }
2114 
2115  if (RequireNonAbstractType(Brackets.getBegin(), T,
2116  diag::err_array_of_abstract_type))
2117  return QualType();
2118 
2119  // Mentioning a member pointer type for an array type causes us to lock in
2120  // an inheritance model, even if it's inside an unused typedef.
2121  if (Context.getTargetInfo().getCXXABI().isMicrosoft())
2122  if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>())
2123  if (!MPTy->getClass()->isDependentType())
2124  (void)isCompleteType(Loc, T);
2125 
2126  } else {
2127  // C99 6.7.5.2p1: If the element type is an incomplete or function type,
2128  // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
2129  if (RequireCompleteType(Loc, T,
2130  diag::err_illegal_decl_array_incomplete_type))
2131  return QualType();
2132  }
2133 
2134  if (T->isFunctionType()) {
2135  Diag(Loc, diag::err_illegal_decl_array_of_functions)
2136  << getPrintableNameForEntity(Entity) << T;
2137  return QualType();
2138  }
2139 
2140  if (const RecordType *EltTy = T->getAs<RecordType>()) {
2141  // If the element type is a struct or union that contains a variadic
2142  // array, accept it as a GNU extension: C99 6.7.2.1p2.
2143  if (EltTy->getDecl()->hasFlexibleArrayMember())
2144  Diag(Loc, diag::ext_flexible_array_in_array) << T;
2145  } else if (T->isObjCObjectType()) {
2146  Diag(Loc, diag::err_objc_array_of_interfaces) << T;
2147  return QualType();
2148  }
2149 
2150  // Do placeholder conversions on the array size expression.
2151  if (ArraySize && ArraySize->hasPlaceholderType()) {
2152  ExprResult Result = CheckPlaceholderExpr(ArraySize);
2153  if (Result.isInvalid()) return QualType();
2154  ArraySize = Result.get();
2155  }
2156 
2157  // Do lvalue-to-rvalue conversions on the array size expression.
2158  if (ArraySize && !ArraySize->isRValue()) {
2159  ExprResult Result = DefaultLvalueConversion(ArraySize);
2160  if (Result.isInvalid())
2161  return QualType();
2162 
2163  ArraySize = Result.get();
2164  }
2165 
2166  // C99 6.7.5.2p1: The size expression shall have integer type.
2167  // C++11 allows contextual conversions to such types.
2168  if (!getLangOpts().CPlusPlus11 &&
2169  ArraySize && !ArraySize->isTypeDependent() &&
2170  !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
2171  Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
2172  << ArraySize->getType() << ArraySize->getSourceRange();
2173  return QualType();
2174  }
2175 
2176  llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType()));
2177  if (!ArraySize) {
2178  if (ASM == ArrayType::Star)
2179  T = Context.getVariableArrayType(T, nullptr, ASM, Quals, Brackets);
2180  else
2181  T = Context.getIncompleteArrayType(T, ASM, Quals);
2182  } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) {
2183  T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets);
2184  } else if ((!T->isDependentType() && !T->isIncompleteType() &&
2185  !T->isConstantSizeType()) ||
2186  isArraySizeVLA(*this, ArraySize, ConstVal)) {
2187  // Even in C++11, don't allow contextual conversions in the array bound
2188  // of a VLA.
2189  if (getLangOpts().CPlusPlus11 &&
2190  !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
2191  Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
2192  << ArraySize->getType() << ArraySize->getSourceRange();
2193  return QualType();
2194  }
2195 
2196  // C99: an array with an element type that has a non-constant-size is a VLA.
2197  // C99: an array with a non-ICE size is a VLA. We accept any expression
2198  // that we can fold to a non-zero positive value as an extension.
2199  T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
2200  } else {
2201  // C99 6.7.5.2p1: If the expression is a constant expression, it shall
2202  // have a value greater than zero.
2203  if (ConstVal.isSigned() && ConstVal.isNegative()) {
2204  if (Entity)
2205  Diag(ArraySize->getLocStart(), diag::err_decl_negative_array_size)
2206  << getPrintableNameForEntity(Entity) << ArraySize->getSourceRange();
2207  else
2208  Diag(ArraySize->getLocStart(), diag::err_typecheck_negative_array_size)
2209  << ArraySize->getSourceRange();
2210  return QualType();
2211  }
2212  if (ConstVal == 0) {
2213  // GCC accepts zero sized static arrays. We allow them when
2214  // we're not in a SFINAE context.
2215  Diag(ArraySize->getLocStart(),
2216  isSFINAEContext()? diag::err_typecheck_zero_array_size
2217  : diag::ext_typecheck_zero_array_size)
2218  << ArraySize->getSourceRange();
2219 
2220  if (ASM == ArrayType::Static) {
2221  Diag(ArraySize->getLocStart(),
2222  diag::warn_typecheck_zero_static_array_size)
2223  << ArraySize->getSourceRange();
2224  ASM = ArrayType::Normal;
2225  }
2226  } else if (!T->isDependentType() && !T->isVariablyModifiedType() &&
2227  !T->isIncompleteType() && !T->isUndeducedType()) {
2228  // Is the array too large?
2229  unsigned ActiveSizeBits
2230  = ConstantArrayType::getNumAddressingBits(Context, T, ConstVal);
2231  if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
2232  Diag(ArraySize->getLocStart(), diag::err_array_too_large)
2233  << ConstVal.toString(10)
2234  << ArraySize->getSourceRange();
2235  return QualType();
2236  }
2237  }
2238 
2239  T = Context.getConstantArrayType(T, ConstVal, ASM, Quals);
2240  }
2241 
2242  // OpenCL v1.2 s6.9.d: variable length arrays are not supported.
2243  if (getLangOpts().OpenCL && T->isVariableArrayType()) {
2244  Diag(Loc, diag::err_opencl_vla);
2245  return QualType();
2246  }
2247 
2248  if (T->isVariableArrayType() && !Context.getTargetInfo().isVLASupported()) {
2249  if (getLangOpts().CUDA) {
2250  // CUDA device code doesn't support VLAs.
2251  CUDADiagIfDeviceCode(Loc, diag::err_cuda_vla) << CurrentCUDATarget();
2252  } else if (!getLangOpts().OpenMP ||
2253  shouldDiagnoseTargetSupportFromOpenMP()) {
2254  // Some targets don't support VLAs.
2255  Diag(Loc, diag::err_vla_unsupported);
2256  return QualType();
2257  }
2258  }
2259 
2260  // If this is not C99, extwarn about VLA's and C99 array size modifiers.
2261  if (!getLangOpts().C99) {
2262  if (T->isVariableArrayType()) {
2263  // Prohibit the use of VLAs during template argument deduction.
2264  if (isSFINAEContext()) {
2265  Diag(Loc, diag::err_vla_in_sfinae);
2266  return QualType();
2267  }
2268  // Just extwarn about VLAs.
2269  else
2270  Diag(Loc, diag::ext_vla);
2271  } else if (ASM != ArrayType::Normal || Quals != 0)
2272  Diag(Loc,
2273  getLangOpts().CPlusPlus? diag::err_c99_array_usage_cxx
2274  : diag::ext_c99_array_usage) << ASM;
2275  }
2276 
2277  if (T->isVariableArrayType()) {
2278  // Warn about VLAs for -Wvla.
2279  Diag(Loc, diag::warn_vla_used);
2280  }
2281 
2282  // OpenCL v2.0 s6.12.5 - Arrays of blocks are not supported.
2283  // OpenCL v2.0 s6.16.13.1 - Arrays of pipe type are not supported.
2284  // OpenCL v2.0 s6.9.b - Arrays of image/sampler type are not supported.
2285  if (getLangOpts().OpenCL) {
2286  const QualType ArrType = Context.getBaseElementType(T);
2287  if (ArrType->isBlockPointerType() || ArrType->isPipeType() ||
2288  ArrType->isSamplerT() || ArrType->isImageType()) {
2289  Diag(Loc, diag::err_opencl_invalid_type_array) << ArrType;
2290  return QualType();
2291  }
2292  }
2293 
2294  return T;
2295 }
2296 
2297 /// Build an ext-vector type.
2298 ///
2299 /// Run the required checks for the extended vector type.
2301  SourceLocation AttrLoc) {
2302  // Unlike gcc's vector_size attribute, we do not allow vectors to be defined
2303  // in conjunction with complex types (pointers, arrays, functions, etc.).
2304  //
2305  // Additionally, OpenCL prohibits vectors of booleans (they're considered a
2306  // reserved data type under OpenCL v2.0 s6.1.4), we don't support selects
2307  // on bitvectors, and we have no well-defined ABI for bitvectors, so vectors
2308  // of bool aren't allowed.
2309  if ((!T->isDependentType() && !T->isIntegerType() &&
2310  !T->isRealFloatingType()) ||
2311  T->isBooleanType()) {
2312  Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
2313  return QualType();
2314  }
2315 
2316  if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) {
2317  llvm::APSInt vecSize(32);
2318  if (!ArraySize->isIntegerConstantExpr(vecSize, Context)) {
2319  Diag(AttrLoc, diag::err_attribute_argument_type)
2320  << "ext_vector_type" << AANT_ArgumentIntegerConstant
2321  << ArraySize->getSourceRange();
2322  return QualType();
2323  }
2324 
2325  // Unlike gcc's vector_size attribute, the size is specified as the
2326  // number of elements, not the number of bytes.
2327  unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
2328 
2329  if (vectorSize == 0) {
2330  Diag(AttrLoc, diag::err_attribute_zero_size)
2331  << ArraySize->getSourceRange();
2332  return QualType();
2333  }
2334 
2335  if (VectorType::isVectorSizeTooLarge(vectorSize)) {
2336  Diag(AttrLoc, diag::err_attribute_size_too_large)
2337  << ArraySize->getSourceRange();
2338  return QualType();
2339  }
2340 
2341  return Context.getExtVectorType(T, vectorSize);
2342  }
2343 
2344  return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc);
2345 }
2346 
2348  if (T->isArrayType() || T->isFunctionType()) {
2349  Diag(Loc, diag::err_func_returning_array_function)
2350  << T->isFunctionType() << T;
2351  return true;
2352  }
2353 
2354  // Functions cannot return half FP.
2355  if (T->isHalfType() && !getLangOpts().HalfArgsAndReturns) {
2356  Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 <<
2357  FixItHint::CreateInsertion(Loc, "*");
2358  return true;
2359  }
2360 
2361  // Methods cannot return interface types. All ObjC objects are
2362  // passed by reference.
2363  if (T->isObjCObjectType()) {
2364  Diag(Loc, diag::err_object_cannot_be_passed_returned_by_value)
2365  << 0 << T << FixItHint::CreateInsertion(Loc, "*");
2366  return true;
2367  }
2368 
2369  return false;
2370 }
2371 
2372 /// Check the extended parameter information. Most of the necessary
2373 /// checking should occur when applying the parameter attribute; the
2374 /// only other checks required are positional restrictions.
2377  llvm::function_ref<SourceLocation(unsigned)> getParamLoc) {
2378  assert(EPI.ExtParameterInfos && "shouldn't get here without param infos");
2379 
2380  bool hasCheckedSwiftCall = false;
2381  auto checkForSwiftCC = [&](unsigned paramIndex) {
2382  // Only do this once.
2383  if (hasCheckedSwiftCall) return;
2384  hasCheckedSwiftCall = true;
2385  if (EPI.ExtInfo.getCC() == CC_Swift) return;
2386  S.Diag(getParamLoc(paramIndex), diag::err_swift_param_attr_not_swiftcall)
2387  << getParameterABISpelling(EPI.ExtParameterInfos[paramIndex].getABI());
2388  };
2389 
2390  for (size_t paramIndex = 0, numParams = paramTypes.size();
2391  paramIndex != numParams; ++paramIndex) {
2392  switch (EPI.ExtParameterInfos[paramIndex].getABI()) {
2393  // Nothing interesting to check for orindary-ABI parameters.
2395  continue;
2396 
2397  // swift_indirect_result parameters must be a prefix of the function
2398  // arguments.
2400  checkForSwiftCC(paramIndex);
2401  if (paramIndex != 0 &&
2402  EPI.ExtParameterInfos[paramIndex - 1].getABI()
2404  S.Diag(getParamLoc(paramIndex),
2405  diag::err_swift_indirect_result_not_first);
2406  }
2407  continue;
2408 
2410  checkForSwiftCC(paramIndex);
2411  continue;
2412 
2413  // swift_error parameters must be preceded by a swift_context parameter.
2415  checkForSwiftCC(paramIndex);
2416  if (paramIndex == 0 ||
2417  EPI.ExtParameterInfos[paramIndex - 1].getABI() !=
2419  S.Diag(getParamLoc(paramIndex),
2420  diag::err_swift_error_result_not_after_swift_context);
2421  }
2422  continue;
2423  }
2424  llvm_unreachable("bad ABI kind");
2425  }
2426 }
2427 
2429  MutableArrayRef<QualType> ParamTypes,
2430  SourceLocation Loc, DeclarationName Entity,
2431  const FunctionProtoType::ExtProtoInfo &EPI) {
2432  bool Invalid = false;
2433 
2434  Invalid |= CheckFunctionReturnType(T, Loc);
2435 
2436  for (unsigned Idx = 0, Cnt = ParamTypes.size(); Idx < Cnt; ++Idx) {
2437  // FIXME: Loc is too inprecise here, should use proper locations for args.
2438  QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]);
2439  if (ParamType->isVoidType()) {
2440  Diag(Loc, diag::err_param_with_void_type);
2441  Invalid = true;
2442  } else if (ParamType->isHalfType() && !getLangOpts().HalfArgsAndReturns) {
2443  // Disallow half FP arguments.
2444  Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 <<
2445  FixItHint::CreateInsertion(Loc, "*");
2446  Invalid = true;
2447  }
2448 
2449  ParamTypes[Idx] = ParamType;
2450  }
2451 
2452  if (EPI.ExtParameterInfos) {
2453  checkExtParameterInfos(*this, ParamTypes, EPI,
2454  [=](unsigned i) { return Loc; });
2455  }
2456 
2457  if (EPI.ExtInfo.getProducesResult()) {
2458  // This is just a warning, so we can't fail to build if we see it.
2459  checkNSReturnsRetainedReturnType(Loc, T);
2460  }
2461 
2462  if (Invalid)
2463  return QualType();
2464 
2465  return Context.getFunctionType(T, ParamTypes, EPI);
2466 }
2467 
2468 /// Build a member pointer type \c T Class::*.
2469 ///
2470 /// \param T the type to which the member pointer refers.
2471 /// \param Class the class type into which the member pointer points.
2472 /// \param Loc the location where this type begins
2473 /// \param Entity the name of the entity that will have this member pointer type
2474 ///
2475 /// \returns a member pointer type, if successful, or a NULL type if there was
2476 /// an error.
2478  SourceLocation Loc,
2479  DeclarationName Entity) {
2480  // Verify that we're not building a pointer to pointer to function with
2481  // exception specification.
2482  if (CheckDistantExceptionSpec(T)) {
2483  Diag(Loc, diag::err_distant_exception_spec);
2484  return QualType();
2485  }
2486 
2487  // C++ 8.3.3p3: A pointer to member shall not point to ... a member
2488  // with reference type, or "cv void."
2489  if (T->isReferenceType()) {
2490  Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
2491  << getPrintableNameForEntity(Entity) << T;
2492  return QualType();
2493  }
2494 
2495  if (T->isVoidType()) {
2496  Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
2497  << getPrintableNameForEntity(Entity);
2498  return QualType();
2499  }
2500 
2501  if (!Class->isDependentType() && !Class->isRecordType()) {
2502  Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
2503  return QualType();
2504  }
2505 
2506  // Adjust the default free function calling convention to the default method
2507  // calling convention.
2508  bool IsCtorOrDtor =
2511  if (T->isFunctionType())
2512  adjustMemberFunctionCC(T, /*IsStatic=*/false, IsCtorOrDtor, Loc);
2513 
2514  return Context.getMemberPointerType(T, Class.getTypePtr());
2515 }
2516 
2517 /// Build a block pointer type.
2518 ///
2519 /// \param T The type to which we'll be building a block pointer.
2520 ///
2521 /// \param Loc The source location, used for diagnostics.
2522 ///
2523 /// \param Entity The name of the entity that involves the block pointer
2524 /// type, if known.
2525 ///
2526 /// \returns A suitable block pointer type, if there are no
2527 /// errors. Otherwise, returns a NULL type.
2529  SourceLocation Loc,
2530  DeclarationName Entity) {
2531  if (!T->isFunctionType()) {
2532  Diag(Loc, diag::err_nonfunction_block_type);
2533  return QualType();
2534  }
2535 
2536  if (checkQualifiedFunction(*this, T, Loc, QFK_BlockPointer))
2537  return QualType();
2538 
2539  return Context.getBlockPointerType(T);
2540 }
2541 
2543  QualType QT = Ty.get();
2544  if (QT.isNull()) {
2545  if (TInfo) *TInfo = nullptr;
2546  return QualType();
2547  }
2548 
2549  TypeSourceInfo *DI = nullptr;
2550  if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
2551  QT = LIT->getType();
2552  DI = LIT->getTypeSourceInfo();
2553  }
2554 
2555  if (TInfo) *TInfo = DI;
2556  return QT;
2557 }
2558 
2559 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
2560  Qualifiers::ObjCLifetime ownership,
2561  unsigned chunkIndex);
2562 
2563 /// Given that this is the declaration of a parameter under ARC,
2564 /// attempt to infer attributes and such for pointer-to-whatever
2565 /// types.
2566 static void inferARCWriteback(TypeProcessingState &state,
2567  QualType &declSpecType) {
2568  Sema &S = state.getSema();
2569  Declarator &declarator = state.getDeclarator();
2570 
2571  // TODO: should we care about decl qualifiers?
2572 
2573  // Check whether the declarator has the expected form. We walk
2574  // from the inside out in order to make the block logic work.
2575  unsigned outermostPointerIndex = 0;
2576  bool isBlockPointer = false;
2577  unsigned numPointers = 0;
2578  for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
2579  unsigned chunkIndex = i;
2580  DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex);
2581  switch (chunk.Kind) {
2583  // Ignore parens.
2584  break;
2585 
2588  // Count the number of pointers. Treat references
2589  // interchangeably as pointers; if they're mis-ordered, normal
2590  // type building will discover that.
2591  outermostPointerIndex = chunkIndex;
2592  numPointers++;
2593  break;
2594 
2596  // If we have a pointer to block pointer, that's an acceptable
2597  // indirect reference; anything else is not an application of
2598  // the rules.
2599  if (numPointers != 1) return;
2600  numPointers++;
2601  outermostPointerIndex = chunkIndex;
2602  isBlockPointer = true;
2603 
2604  // We don't care about pointer structure in return values here.
2605  goto done;
2606 
2607  case DeclaratorChunk::Array: // suppress if written (id[])?
2610  case DeclaratorChunk::Pipe:
2611  return;
2612  }
2613  }
2614  done:
2615 
2616  // If we have *one* pointer, then we want to throw the qualifier on
2617  // the declaration-specifiers, which means that it needs to be a
2618  // retainable object type.
2619  if (numPointers == 1) {
2620  // If it's not a retainable object type, the rule doesn't apply.
2621  if (!declSpecType->isObjCRetainableType()) return;
2622 
2623  // If it already has lifetime, don't do anything.
2624  if (declSpecType.getObjCLifetime()) return;
2625 
2626  // Otherwise, modify the type in-place.
2627  Qualifiers qs;
2628 
2629  if (declSpecType->isObjCARCImplicitlyUnretainedType())
2631  else
2633  declSpecType = S.Context.getQualifiedType(declSpecType, qs);
2634 
2635  // If we have *two* pointers, then we want to throw the qualifier on
2636  // the outermost pointer.
2637  } else if (numPointers == 2) {
2638  // If we don't have a block pointer, we need to check whether the
2639  // declaration-specifiers gave us something that will turn into a
2640  // retainable object pointer after we slap the first pointer on it.
2641  if (!isBlockPointer && !declSpecType->isObjCObjectType())
2642  return;
2643 
2644  // Look for an explicit lifetime attribute there.
2645  DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex);
2646  if (chunk.Kind != DeclaratorChunk::Pointer &&
2648  return;
2649  for (const AttributeList *attr = chunk.getAttrs(); attr;
2650  attr = attr->getNext())
2651  if (attr->getKind() == AttributeList::AT_ObjCOwnership)
2652  return;
2653 
2655  outermostPointerIndex);
2656 
2657  // Any other number of pointers/references does not trigger the rule.
2658  } else return;
2659 
2660  // TODO: mark whether we did this inference?
2661 }
2662 
2663 void Sema::diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
2664  SourceLocation FallbackLoc,
2665  SourceLocation ConstQualLoc,
2666  SourceLocation VolatileQualLoc,
2667  SourceLocation RestrictQualLoc,
2668  SourceLocation AtomicQualLoc,
2669  SourceLocation UnalignedQualLoc) {
2670  if (!Quals)
2671  return;
2672 
2673  struct Qual {
2674  const char *Name;
2675  unsigned Mask;
2676  SourceLocation Loc;
2677  } const QualKinds[5] = {
2678  { "const", DeclSpec::TQ_const, ConstQualLoc },
2679  { "volatile", DeclSpec::TQ_volatile, VolatileQualLoc },
2680  { "restrict", DeclSpec::TQ_restrict, RestrictQualLoc },
2681  { "__unaligned", DeclSpec::TQ_unaligned, UnalignedQualLoc },
2682  { "_Atomic", DeclSpec::TQ_atomic, AtomicQualLoc }
2683  };
2684 
2685  SmallString<32> QualStr;
2686  unsigned NumQuals = 0;
2687  SourceLocation Loc;
2688  FixItHint FixIts[5];
2689 
2690  // Build a string naming the redundant qualifiers.
2691  for (auto &E : QualKinds) {
2692  if (Quals & E.Mask) {
2693  if (!QualStr.empty()) QualStr += ' ';
2694  QualStr += E.Name;
2695 
2696  // If we have a location for the qualifier, offer a fixit.
2697  SourceLocation QualLoc = E.Loc;
2698  if (QualLoc.isValid()) {
2699  FixIts[NumQuals] = FixItHint::CreateRemoval(QualLoc);
2700  if (Loc.isInvalid() ||
2701  getSourceManager().isBeforeInTranslationUnit(QualLoc, Loc))
2702  Loc = QualLoc;
2703  }
2704 
2705  ++NumQuals;
2706  }
2707  }
2708 
2709  Diag(Loc.isInvalid() ? FallbackLoc : Loc, DiagID)
2710  << QualStr << NumQuals << FixIts[0] << FixIts[1] << FixIts[2] << FixIts[3];
2711 }
2712 
2713 // Diagnose pointless type qualifiers on the return type of a function.
2715  Declarator &D,
2716  unsigned FunctionChunkIndex) {
2717  if (D.getTypeObject(FunctionChunkIndex).Fun.hasTrailingReturnType()) {
2718  // FIXME: TypeSourceInfo doesn't preserve location information for
2719  // qualifiers.
2720  S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
2721  RetTy.getLocalCVRQualifiers(),
2722  D.getIdentifierLoc());
2723  return;
2724  }
2725 
2726  for (unsigned OuterChunkIndex = FunctionChunkIndex + 1,
2727  End = D.getNumTypeObjects();
2728  OuterChunkIndex != End; ++OuterChunkIndex) {
2729  DeclaratorChunk &OuterChunk = D.getTypeObject(OuterChunkIndex);
2730  switch (OuterChunk.Kind) {
2732  continue;
2733 
2734  case DeclaratorChunk::Pointer: {
2735  DeclaratorChunk::PointerTypeInfo &PTI = OuterChunk.Ptr;
2737  diag::warn_qual_return_type,
2738  PTI.TypeQuals,
2739  SourceLocation(),
2745  return;
2746  }
2747 
2753  case DeclaratorChunk::Pipe:
2754  // FIXME: We can't currently provide an accurate source location and a
2755  // fix-it hint for these.
2756  unsigned AtomicQual = RetTy->isAtomicType() ? DeclSpec::TQ_atomic : 0;
2757  S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
2758  RetTy.getCVRQualifiers() | AtomicQual,
2759  D.getIdentifierLoc());
2760  return;
2761  }
2762 
2763  llvm_unreachable("unknown declarator chunk kind");
2764  }
2765 
2766  // If the qualifiers come from a conversion function type, don't diagnose
2767  // them -- they're not necessarily redundant, since such a conversion
2768  // operator can be explicitly called as "x.operator const int()".
2770  return;
2771 
2772  // Just parens all the way out to the decl specifiers. Diagnose any qualifiers
2773  // which are present there.
2774  S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
2776  D.getIdentifierLoc(),
2782 }
2783 
2784 static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state,
2785  TypeSourceInfo *&ReturnTypeInfo) {
2786  Sema &SemaRef = state.getSema();
2787  Declarator &D = state.getDeclarator();
2788  QualType T;
2789  ReturnTypeInfo = nullptr;
2790 
2791  // The TagDecl owned by the DeclSpec.
2792  TagDecl *OwnedTagDecl = nullptr;
2793 
2794  switch (D.getName().getKind()) {
2800  T = ConvertDeclSpecToType(state);
2801 
2802  if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) {
2803  OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
2804  // Owned declaration is embedded in declarator.
2805  OwnedTagDecl->setEmbeddedInDeclarator(true);
2806  }
2807  break;
2808 
2812  // Constructors and destructors don't have return types. Use
2813  // "void" instead.
2814  T = SemaRef.Context.VoidTy;
2815  processTypeAttrs(state, T, TAL_DeclSpec,
2817  break;
2818 
2820  // Deduction guides have a trailing return type and no type in their
2821  // decl-specifier sequence. Use a placeholder return type for now.
2822  T = SemaRef.Context.DependentTy;
2823  break;
2824 
2826  // The result type of a conversion function is the type that it
2827  // converts to.
2829  &ReturnTypeInfo);
2830  break;
2831  }
2832 
2833  if (D.getAttributes())
2835 
2836  // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context.
2837  if (DeducedType *Deduced = T->getContainedDeducedType()) {
2838  AutoType *Auto = dyn_cast<AutoType>(Deduced);
2839  int Error = -1;
2840 
2841  // Is this a 'auto' or 'decltype(auto)' type (as opposed to __auto_type or
2842  // class template argument deduction)?
2843  bool IsCXXAutoType =
2844  (Auto && Auto->getKeyword() != AutoTypeKeyword::GNUAutoType);
2845 
2846  switch (D.getContext()) {
2848  // Declared return type of a lambda-declarator is implicit and is always
2849  // 'auto'.
2850  break;
2854  Error = 0;
2855  break;
2857  // In C++14, generic lambdas allow 'auto' in their parameters.
2858  if (!SemaRef.getLangOpts().CPlusPlus14 ||
2859  !Auto || Auto->getKeyword() != AutoTypeKeyword::Auto)
2860  Error = 16;
2861  else {
2862  // If auto is mentioned in a lambda parameter context, convert it to a
2863  // template parameter type.
2864  sema::LambdaScopeInfo *LSI = SemaRef.getCurLambda();
2865  assert(LSI && "No LambdaScopeInfo on the stack!");
2866  const unsigned TemplateParameterDepth = LSI->AutoTemplateParameterDepth;
2867  const unsigned AutoParameterPosition = LSI->AutoTemplateParams.size();
2868  const bool IsParameterPack = D.hasEllipsis();
2869 
2870  // Create the TemplateTypeParmDecl here to retrieve the corresponding
2871  // template parameter type. Template parameters are temporarily added
2872  // to the TU until the associated TemplateDecl is created.
2873  TemplateTypeParmDecl *CorrespondingTemplateParam =
2875  SemaRef.Context, SemaRef.Context.getTranslationUnitDecl(),
2876  /*KeyLoc*/SourceLocation(), /*NameLoc*/D.getLocStart(),
2877  TemplateParameterDepth, AutoParameterPosition,
2878  /*Identifier*/nullptr, false, IsParameterPack);
2879  LSI->AutoTemplateParams.push_back(CorrespondingTemplateParam);
2880  // Replace the 'auto' in the function parameter with this invented
2881  // template type parameter.
2882  // FIXME: Retain some type sugar to indicate that this was written
2883  // as 'auto'.
2884  T = SemaRef.ReplaceAutoType(
2885  T, QualType(CorrespondingTemplateParam->getTypeForDecl(), 0));
2886  }
2887  break;
2891  break;
2892  bool Cxx = SemaRef.getLangOpts().CPlusPlus;
2893  switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) {
2894  case TTK_Enum: llvm_unreachable("unhandled tag kind");
2895  case TTK_Struct: Error = Cxx ? 1 : 2; /* Struct member */ break;
2896  case TTK_Union: Error = Cxx ? 3 : 4; /* Union member */ break;
2897  case TTK_Class: Error = 5; /* Class member */ break;
2898  case TTK_Interface: Error = 6; /* Interface member */ break;
2899  }
2900  if (D.getDeclSpec().isFriendSpecified())
2901  Error = 20; // Friend type
2902  break;
2903  }
2906  Error = 7; // Exception declaration
2907  break;
2909  if (isa<DeducedTemplateSpecializationType>(Deduced))
2910  Error = 19; // Template parameter
2911  else if (!SemaRef.getLangOpts().CPlusPlus17)
2912  Error = 8; // Template parameter (until C++17)
2913  break;
2915  Error = 9; // Block literal
2916  break;
2918  // Within a template argument list, a deduced template specialization
2919  // type will be reinterpreted as a template template argument.
2920  if (isa<DeducedTemplateSpecializationType>(Deduced) &&
2921  !D.getNumTypeObjects() &&
2923  break;
2924  LLVM_FALLTHROUGH;
2926  Error = 10; // Template type argument
2927  break;
2930  Error = 12; // Type alias
2931  break;
2934  if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType)
2935  Error = 13; // Function return type
2936  break;
2938  if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType)
2939  Error = 14; // conversion-type-id
2940  break;
2942  if (isa<DeducedTemplateSpecializationType>(Deduced))
2943  break;
2944  LLVM_FALLTHROUGH;
2946  Error = 15; // Generic
2947  break;
2953  // FIXME: P0091R3 (erroneously) does not permit class template argument
2954  // deduction in conditions, for-init-statements, and other declarations
2955  // that are not simple-declarations.
2956  break;
2958  // FIXME: P0091R3 does not permit class template argument deduction here,
2959  // but we follow GCC and allow it anyway.
2960  if (!IsCXXAutoType && !isa<DeducedTemplateSpecializationType>(Deduced))
2961  Error = 17; // 'new' type
2962  break;
2964  Error = 18; // K&R function parameter
2965  break;
2966  }
2967 
2969  Error = 11;
2970 
2971  // In Objective-C it is an error to use 'auto' on a function declarator
2972  // (and everywhere for '__auto_type').
2973  if (D.isFunctionDeclarator() &&
2974  (!SemaRef.getLangOpts().CPlusPlus11 || !IsCXXAutoType))
2975  Error = 13;
2976 
2977  bool HaveTrailing = false;
2978 
2979  // C++11 [dcl.spec.auto]p2: 'auto' is always fine if the declarator
2980  // contains a trailing return type. That is only legal at the outermost
2981  // level. Check all declarator chunks (outermost first) anyway, to give
2982  // better diagnostics.
2983  // We don't support '__auto_type' with trailing return types.
2984  // FIXME: Should we only do this for 'auto' and not 'decltype(auto)'?
2985  if (SemaRef.getLangOpts().CPlusPlus11 && IsCXXAutoType &&
2986  D.hasTrailingReturnType()) {
2987  HaveTrailing = true;
2988  Error = -1;
2989  }
2990 
2991  SourceRange AutoRange = D.getDeclSpec().getTypeSpecTypeLoc();
2993  AutoRange = D.getName().getSourceRange();
2994 
2995  if (Error != -1) {
2996  unsigned Kind;
2997  if (Auto) {
2998  switch (Auto->getKeyword()) {
2999  case AutoTypeKeyword::Auto: Kind = 0; break;
3000  case AutoTypeKeyword::DecltypeAuto: Kind = 1; break;
3001  case AutoTypeKeyword::GNUAutoType: Kind = 2; break;
3002  }
3003  } else {
3004  assert(isa<DeducedTemplateSpecializationType>(Deduced) &&
3005  "unknown auto type");
3006  Kind = 3;
3007  }
3008 
3009  auto *DTST = dyn_cast<DeducedTemplateSpecializationType>(Deduced);
3010  TemplateName TN = DTST ? DTST->getTemplateName() : TemplateName();
3011 
3012  SemaRef.Diag(AutoRange.getBegin(), diag::err_auto_not_allowed)
3013  << Kind << Error << (int)SemaRef.getTemplateNameKindForDiagnostics(TN)
3014  << QualType(Deduced, 0) << AutoRange;
3015  if (auto *TD = TN.getAsTemplateDecl())
3016  SemaRef.Diag(TD->getLocation(), diag::note_template_decl_here);
3017 
3018  T = SemaRef.Context.IntTy;
3019  D.setInvalidType(true);
3020  } else if (!HaveTrailing &&
3022  // If there was a trailing return type, we already got
3023  // warn_cxx98_compat_trailing_return_type in the parser.
3024  // If this was a lambda, we already warned on that too.
3025  SemaRef.Diag(AutoRange.getBegin(),
3026  diag::warn_cxx98_compat_auto_type_specifier)
3027  << AutoRange;
3028  }
3029  }
3030 
3031  if (SemaRef.getLangOpts().CPlusPlus &&
3032  OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) {
3033  // Check the contexts where C++ forbids the declaration of a new class
3034  // or enumeration in a type-specifier-seq.
3035  unsigned DiagID = 0;
3036  switch (D.getContext()) {
3039  // Class and enumeration definitions are syntactically not allowed in
3040  // trailing return types.
3041  llvm_unreachable("parser should not have allowed this");
3042  break;
3050  // C++11 [dcl.type]p3:
3051  // A type-specifier-seq shall not define a class or enumeration unless
3052  // it appears in the type-id of an alias-declaration (7.1.3) that is not
3053  // the declaration of a template-declaration.
3055  break;
3057  DiagID = diag::err_type_defined_in_alias_template;
3058  break;
3068  DiagID = diag::err_type_defined_in_type_specifier;
3069  break;
3075  // C++ [dcl.fct]p6:
3076  // Types shall not be defined in return or parameter types.
3077  DiagID = diag::err_type_defined_in_param_type;
3078  break;
3080  // C++ 6.4p2:
3081  // The type-specifier-seq shall not contain typedef and shall not declare
3082  // a new class or enumeration.
3083  DiagID = diag::err_type_defined_in_condition;
3084  break;
3085  }
3086 
3087  if (DiagID != 0) {
3088  SemaRef.Diag(OwnedTagDecl->getLocation(), DiagID)
3089  << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
3090  D.setInvalidType(true);
3091  }
3092  }
3093 
3094  assert(!T.isNull() && "This function should not return a null type");
3095  return T;
3096 }
3097 
3098 /// Produce an appropriate diagnostic for an ambiguity between a function
3099 /// declarator and a C++ direct-initializer.
3101  DeclaratorChunk &DeclType, QualType RT) {
3102  const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
3103  assert(FTI.isAmbiguous && "no direct-initializer / function ambiguity");
3104 
3105  // If the return type is void there is no ambiguity.
3106  if (RT->isVoidType())
3107  return;
3108 
3109  // An initializer for a non-class type can have at most one argument.
3110  if (!RT->isRecordType() && FTI.NumParams > 1)
3111  return;
3112 
3113  // An initializer for a reference must have exactly one argument.
3114  if (RT->isReferenceType() && FTI.NumParams != 1)
3115  return;
3116 
3117  // Only warn if this declarator is declaring a function at block scope, and
3118  // doesn't have a storage class (such as 'extern') specified.
3119  if (!D.isFunctionDeclarator() ||
3124  return;
3125 
3126  // Inside a condition, a direct initializer is not permitted. We allow one to
3127  // be parsed in order to give better diagnostics in condition parsing.
3129  return;
3130 
3131  SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc);
3132 
3133  S.Diag(DeclType.Loc,
3134  FTI.NumParams ? diag::warn_parens_disambiguated_as_function_declaration
3135  : diag::warn_empty_parens_are_function_decl)
3136  << ParenRange;
3137 
3138  // If the declaration looks like:
3139  // T var1,
3140  // f();
3141  // and name lookup finds a function named 'f', then the ',' was
3142  // probably intended to be a ';'.
3143  if (!D.isFirstDeclarator() && D.getIdentifier()) {
3146  if (Comma.getFileID() != Name.getFileID() ||
3147  Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) {
3150  if (S.LookupName(Result, S.getCurScope()))
3151  S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call)
3153  << D.getIdentifier();
3154  Result.suppressDiagnostics();
3155  }
3156  }
3157 
3158  if (FTI.NumParams > 0) {
3159  // For a declaration with parameters, eg. "T var(T());", suggest adding
3160  // parens around the first parameter to turn the declaration into a
3161  // variable declaration.
3162  SourceRange Range = FTI.Params[0].Param->getSourceRange();
3163  SourceLocation B = Range.getBegin();
3164  SourceLocation E = S.getLocForEndOfToken(Range.getEnd());
3165  // FIXME: Maybe we should suggest adding braces instead of parens
3166  // in C++11 for classes that don't have an initializer_list constructor.
3167  S.Diag(B, diag::note_additional_parens_for_variable_declaration)
3168  << FixItHint::CreateInsertion(B, "(")
3169  << FixItHint::CreateInsertion(E, ")");
3170  } else {
3171  // For a declaration without parameters, eg. "T var();", suggest replacing
3172  // the parens with an initializer to turn the declaration into a variable
3173  // declaration.
3174  const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
3175 
3176  // Empty parens mean value-initialization, and no parens mean
3177  // default initialization. These are equivalent if the default
3178  // constructor is user-provided or if zero-initialization is a
3179  // no-op.
3180  if (RD && RD->hasDefinition() &&
3181  (RD->isEmpty() || RD->hasUserProvidedDefaultConstructor()))
3182  S.Diag(DeclType.Loc, diag::note_empty_parens_default_ctor)
3183  << FixItHint::CreateRemoval(ParenRange);
3184  else {
3185  std::string Init =
3186  S.getFixItZeroInitializerForType(RT, ParenRange.getBegin());
3187  if (Init.empty() && S.LangOpts.CPlusPlus11)
3188  Init = "{}";
3189  if (!Init.empty())
3190  S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize)
3191  << FixItHint::CreateReplacement(ParenRange, Init);
3192  }
3193  }
3194 }
3195 
3196 /// Produce an appropriate diagnostic for a declarator with top-level
3197 /// parentheses.
3200  assert(Paren.Kind == DeclaratorChunk::Paren &&
3201  "do not have redundant top-level parentheses");
3202 
3203  // This is a syntactic check; we're not interested in cases that arise
3204  // during template instantiation.
3205  if (S.inTemplateInstantiation())
3206  return;
3207 
3208  // Check whether this could be intended to be a construction of a temporary
3209  // object in C++ via a function-style cast.
3210  bool CouldBeTemporaryObject =
3211  S.getLangOpts().CPlusPlus && D.isExpressionContext() &&
3212  !D.isInvalidType() && D.getIdentifier() &&
3214  (T->isRecordType() || T->isDependentType()) &&
3216 
3217  bool StartsWithDeclaratorId = true;
3218  for (auto &C : D.type_objects()) {
3219  switch (C.Kind) {
3221  if (&C == &Paren)
3222  continue;
3223  LLVM_FALLTHROUGH;
3225  StartsWithDeclaratorId = false;
3226  continue;
3227 
3229  if (!C.Arr.NumElts)
3230  CouldBeTemporaryObject = false;
3231  continue;
3232 
3234  // FIXME: Suppress the warning here if there is no initializer; we're
3235  // going to give an error anyway.
3236  // We assume that something like 'T (&x) = y;' is highly likely to not
3237  // be intended to be a temporary object.
3238  CouldBeTemporaryObject = false;
3239  StartsWithDeclaratorId = false;
3240  continue;
3241 
3243  // In a new-type-id, function chunks require parentheses.
3245  return;
3246  // FIXME: "A(f())" deserves a vexing-parse warning, not just a
3247  // redundant-parens warning, but we don't know whether the function
3248  // chunk was syntactically valid as an expression here.
3249  CouldBeTemporaryObject = false;
3250  continue;
3251 
3254  case DeclaratorChunk::Pipe:
3255  // These cannot appear in expressions.
3256  CouldBeTemporaryObject = false;
3257  StartsWithDeclaratorId = false;
3258  continue;
3259  }
3260  }
3261 
3262  // FIXME: If there is an initializer, assume that this is not intended to be
3263  // a construction of a temporary object.
3264 
3265  // Check whether the name has already been declared; if not, this is not a
3266  // function-style cast.
3267  if (CouldBeTemporaryObject) {
3270  if (!S.LookupName(Result, S.getCurScope()))
3271  CouldBeTemporaryObject = false;
3272  Result.suppressDiagnostics();
3273  }
3274 
3275  SourceRange ParenRange(Paren.Loc, Paren.EndLoc);
3276 
3277  if (!CouldBeTemporaryObject) {
3278  // If we have A (::B), the parentheses affect the meaning of the program.
3279  // Suppress the warning in that case. Don't bother looking at the DeclSpec
3280  // here: even (e.g.) "int ::x" is visually ambiguous even though it's
3281  // formally unambiguous.
3282  if (StartsWithDeclaratorId && D.getCXXScopeSpec().isValid()) {
3283  for (NestedNameSpecifier *NNS = D.getCXXScopeSpec().getScopeRep(); NNS;
3284  NNS = NNS->getPrefix()) {
3285  if (NNS->getKind() == NestedNameSpecifier::Global)
3286  return;
3287  }
3288  }
3289 
3290  S.Diag(Paren.Loc, diag::warn_redundant_parens_around_declarator)
3291  << ParenRange << FixItHint::CreateRemoval(Paren.Loc)
3292  << FixItHint::CreateRemoval(Paren.EndLoc);
3293  return;
3294  }
3295 
3296  S.Diag(Paren.Loc, diag::warn_parens_disambiguated_as_variable_declaration)
3297  << ParenRange << D.getIdentifier();
3298  auto *RD = T->getAsCXXRecordDecl();
3299  if (!RD || !RD->hasDefinition() || RD->hasNonTrivialDestructor())
3300  S.Diag(Paren.Loc, diag::note_raii_guard_add_name)
3301  << FixItHint::CreateInsertion(Paren.Loc, " varname") << T
3302  << D.getIdentifier();
3303  // FIXME: A cast to void is probably a better suggestion in cases where it's
3304  // valid (when there is no initializer and we're not in a condition).
3305  S.Diag(D.getLocStart(), diag::note_function_style_cast_add_parentheses)
3308  S.Diag(Paren.Loc, diag::note_remove_parens_for_variable_declaration)
3309  << FixItHint::CreateRemoval(Paren.Loc)
3310  << FixItHint::CreateRemoval(Paren.EndLoc);
3311 }
3312 
3313 /// Helper for figuring out the default CC for a function declarator type. If
3314 /// this is the outermost chunk, then we can determine the CC from the
3315 /// declarator context. If not, then this could be either a member function
3316 /// type or normal function type.
3317 static CallingConv
3320  unsigned ChunkIndex) {
3321  assert(D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function);
3322 
3323  // Check for an explicit CC attribute.
3324  for (auto Attr = FTI.AttrList; Attr; Attr = Attr->getNext()) {
3325  switch (Attr->getKind()) {
3327  // Ignore attributes that don't validate or can't apply to the
3328  // function type. We'll diagnose the failure to apply them in
3329  // handleFunctionTypeAttr.
3330  CallingConv CC;
3331  if (!S.CheckCallingConvAttr(*Attr, CC) &&
3332  (!FTI.isVariadic || supportsVariadicCall(CC))) {
3333  return CC;
3334  }
3335  break;
3336  }
3337 
3338  default:
3339  break;
3340  }
3341  }
3342 
3343  bool IsCXXInstanceMethod = false;
3344 
3345  if (S.getLangOpts().CPlusPlus) {
3346  // Look inwards through parentheses to see if this chunk will form a
3347  // member pointer type or if we're the declarator. Any type attributes
3348  // between here and there will override the CC we choose here.
3349  unsigned I = ChunkIndex;
3350  bool FoundNonParen = false;
3351  while (I && !FoundNonParen) {
3352  --I;
3354  FoundNonParen = true;
3355  }
3356 
3357  if (FoundNonParen) {
3358  // If we're not the declarator, we're a regular function type unless we're
3359  // in a member pointer.
3360  IsCXXInstanceMethod =
3363  // This can only be a call operator for a lambda, which is an instance
3364  // method.
3365  IsCXXInstanceMethod = true;
3366  } else {
3367  // We're the innermost decl chunk, so must be a function declarator.
3368  assert(D.isFunctionDeclarator());
3369 
3370  // If we're inside a record, we're declaring a method, but it could be
3371  // explicitly or implicitly static.
3372  IsCXXInstanceMethod =
3375  !D.isStaticMember();
3376  }
3377  }
3378 
3380  IsCXXInstanceMethod);
3381 
3382  // Attribute AT_OpenCLKernel affects the calling convention for SPIR
3383  // and AMDGPU targets, hence it cannot be treated as a calling
3384  // convention attribute. This is the simplest place to infer
3385  // calling convention for OpenCL kernels.
3386  if (S.getLangOpts().OpenCL) {
3387  for (const AttributeList *Attr = D.getDeclSpec().getAttributes().getList();
3388  Attr; Attr = Attr->getNext()) {
3389  if (Attr->getKind() == AttributeList::AT_OpenCLKernel) {
3390  CC = CC_OpenCLKernel;
3391  break;
3392  }
3393  }
3394  }
3395 
3396  return CC;
3397 }
3398 
3399 namespace {
3400  /// A simple notion of pointer kinds, which matches up with the various
3401  /// pointer declarators.
3402  enum class SimplePointerKind {
3403  Pointer,
3404  BlockPointer,
3405  MemberPointer,
3406  Array,
3407  };
3408 } // end anonymous namespace
3409 
3411  switch (nullability) {
3413  if (!Ident__Nonnull)
3414  Ident__Nonnull = PP.getIdentifierInfo("_Nonnull");
3415  return Ident__Nonnull;
3416 
3418  if (!Ident__Nullable)
3419  Ident__Nullable = PP.getIdentifierInfo("_Nullable");
3420  return Ident__Nullable;
3421 
3423  if (!Ident__Null_unspecified)
3424  Ident__Null_unspecified = PP.getIdentifierInfo("_Null_unspecified");
3425  return Ident__Null_unspecified;
3426  }
3427  llvm_unreachable("Unknown nullability kind.");
3428 }
3429 
3430 /// Retrieve the identifier "NSError".
3432  if (!Ident_NSError)
3433  Ident_NSError = PP.getIdentifierInfo("NSError");
3434 
3435  return Ident_NSError;
3436 }
3437 
3438 /// Check whether there is a nullability attribute of any kind in the given
3439 /// attribute list.
3440 static bool hasNullabilityAttr(const AttributeList *attrs) {
3441  for (const AttributeList *attr = attrs; attr;
3442  attr = attr->getNext()) {
3443  if (attr->getKind() == AttributeList::AT_TypeNonNull ||
3444  attr->getKind() == AttributeList::AT_TypeNullable ||
3445  attr->getKind() == AttributeList::AT_TypeNullUnspecified)
3446  return true;
3447  }
3448 
3449  return false;
3450 }
3451 
3452 namespace {
3453  /// Describes the kind of a pointer a declarator describes.
3455  // Not a pointer.
3456  NonPointer,
3457  // Single-level pointer.
3458  SingleLevelPointer,
3459  // Multi-level pointer (of any pointer kind).
3460  MultiLevelPointer,
3461  // CFFooRef*
3462  MaybePointerToCFRef,
3463  // CFErrorRef*
3464  CFErrorRefPointer,
3465  // NSError**
3466  NSErrorPointerPointer,
3467  };
3468 
3469  /// Describes a declarator chunk wrapping a pointer that marks inference as
3470  /// unexpected.
3471  // These values must be kept in sync with diagnostics.
3473  /// Pointer is top-level.
3474  None = -1,
3475  /// Pointer is an array element.
3476  Array = 0,
3477  /// Pointer is the referent type of a C++ reference.
3478  Reference = 1
3479  };
3480 } // end anonymous namespace
3481 
3482 /// Classify the given declarator, whose type-specified is \c type, based on
3483 /// what kind of pointer it refers to.
3484 ///
3485 /// This is used to determine the default nullability.
3486 static PointerDeclaratorKind
3488  PointerWrappingDeclaratorKind &wrappingKind) {
3489  unsigned numNormalPointers = 0;
3490 
3491  // For any dependent type, we consider it a non-pointer.
3492  if (type->isDependentType())
3493  return PointerDeclaratorKind::NonPointer;
3494 
3495  // Look through the declarator chunks to identify pointers.
3496  for (unsigned i = 0, n = declarator.getNumTypeObjects(); i != n; ++i) {
3497  DeclaratorChunk &chunk = declarator.getTypeObject(i);
3498  switch (chunk.Kind) {
3500  if (numNormalPointers == 0)
3501  wrappingKind = PointerWrappingDeclaratorKind::Array;
3502  break;
3503 
3505  case DeclaratorChunk::Pipe:
3506  break;
3507 
3510  return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3511  : PointerDeclaratorKind::SingleLevelPointer;
3512 
3514  break;
3515 
3517  if (numNormalPointers == 0)
3518  wrappingKind = PointerWrappingDeclaratorKind::Reference;
3519  break;
3520 
3522  ++numNormalPointers;
3523  if (numNormalPointers > 2)
3524  return PointerDeclaratorKind::MultiLevelPointer;
3525  break;
3526  }
3527  }
3528 
3529  // Then, dig into the type specifier itself.
3530  unsigned numTypeSpecifierPointers = 0;
3531  do {
3532  // Decompose normal pointers.
3533  if (auto ptrType = type->getAs<PointerType>()) {
3534  ++numNormalPointers;
3535 
3536  if (numNormalPointers > 2)
3537  return PointerDeclaratorKind::MultiLevelPointer;
3538 
3539  type = ptrType->getPointeeType();
3540  ++numTypeSpecifierPointers;
3541  continue;
3542  }
3543 
3544  // Decompose block pointers.
3545  if (type->getAs<BlockPointerType>()) {
3546  return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3547  : PointerDeclaratorKind::SingleLevelPointer;
3548  }
3549 
3550  // Decompose member pointers.
3551  if (type->getAs<MemberPointerType>()) {
3552  return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3553  : PointerDeclaratorKind::SingleLevelPointer;
3554  }
3555 
3556  // Look at Objective-C object pointers.
3557  if (auto objcObjectPtr = type->getAs<ObjCObjectPointerType>()) {
3558  ++numNormalPointers;
3559  ++numTypeSpecifierPointers;
3560 
3561  // If this is NSError**, report that.
3562  if (auto objcClassDecl = objcObjectPtr->getInterfaceDecl()) {
3563  if (objcClassDecl->getIdentifier() == S.getNSErrorIdent() &&
3564  numNormalPointers == 2 && numTypeSpecifierPointers < 2) {
3565  return PointerDeclaratorKind::NSErrorPointerPointer;
3566  }
3567  }
3568 
3569  break;
3570  }
3571 
3572  // Look at Objective-C class types.
3573  if (auto objcClass = type->getAs<ObjCInterfaceType>()) {
3574  if (objcClass->getInterface()->getIdentifier() == S.getNSErrorIdent()) {
3575  if (numNormalPointers == 2 && numTypeSpecifierPointers < 2)
3576  return PointerDeclaratorKind::NSErrorPointerPointer;
3577  }
3578 
3579  break;
3580  }
3581 
3582  // If at this point we haven't seen a pointer, we won't see one.
3583  if (numNormalPointers == 0)
3584  return PointerDeclaratorKind::NonPointer;
3585 
3586  if (auto recordType = type->getAs<RecordType>()) {
3587  RecordDecl *recordDecl = recordType->getDecl();
3588 
3589  bool isCFError = false;
3590  if (S.CFError) {
3591  // If we already know about CFError, test it directly.
3592  isCFError = (S.CFError == recordDecl);
3593  } else {
3594  // Check whether this is CFError, which we identify based on its bridge
3595  // to NSError. CFErrorRef used to be declared with "objc_bridge" but is
3596  // now declared with "objc_bridge_mutable", so look for either one of
3597  // the two attributes.
3598  if (recordDecl->getTagKind() == TTK_Struct && numNormalPointers > 0) {
3599  IdentifierInfo *bridgedType = nullptr;
3600  if (auto bridgeAttr = recordDecl->getAttr<ObjCBridgeAttr>())
3601  bridgedType = bridgeAttr->getBridgedType();
3602  else if (auto bridgeAttr =
3603  recordDecl->getAttr<ObjCBridgeMutableAttr>())
3604  bridgedType = bridgeAttr->getBridgedType();
3605 
3606  if (bridgedType == S.getNSErrorIdent()) {
3607  S.CFError = recordDecl;
3608  isCFError = true;
3609  }
3610  }
3611  }
3612 
3613  // If this is CFErrorRef*, report it as such.
3614  if (isCFError && numNormalPointers == 2 && numTypeSpecifierPointers < 2) {
3615  return PointerDeclaratorKind::CFErrorRefPointer;
3616  }
3617  break;
3618  }
3619 
3620  break;
3621  } while (true);
3622 
3623  switch (numNormalPointers) {
3624  case 0:
3625  return PointerDeclaratorKind::NonPointer;
3626 
3627  case 1:
3628  return PointerDeclaratorKind::SingleLevelPointer;
3629 
3630  case 2:
3631  return PointerDeclaratorKind::MaybePointerToCFRef;
3632 
3633  default:
3634  return PointerDeclaratorKind::MultiLevelPointer;
3635  }
3636 }
3637 
3639  SourceLocation loc) {
3640  // If we're anywhere in a function, method, or closure context, don't perform
3641  // completeness checks.
3642  for (DeclContext *ctx = S.CurContext; ctx; ctx = ctx->getParent()) {
3643  if (ctx->isFunctionOrMethod())
3644  return FileID();
3645 
3646  if (ctx->isFileContext())
3647  break;
3648  }
3649 
3650  // We only care about the expansion location.
3651  loc = S.SourceMgr.getExpansionLoc(loc);
3652  FileID file = S.SourceMgr.getFileID(loc);
3653  if (file.isInvalid())
3654  return FileID();
3655 
3656  // Retrieve file information.
3657  bool invalid = false;
3658  const SrcMgr::SLocEntry &sloc = S.SourceMgr.getSLocEntry(file, &invalid);
3659  if (invalid || !sloc.isFile())
3660  return FileID();
3661 
3662  // We don't want to perform completeness checks on the main file or in
3663  // system headers.
3664  const SrcMgr::FileInfo &fileInfo = sloc.getFile();
3665  if (fileInfo.getIncludeLoc().isInvalid())
3666  return FileID();
3667  if (fileInfo.getFileCharacteristic() != SrcMgr::C_User &&
3669  return FileID();
3670  }
3671 
3672  return file;
3673 }
3674 
3675 /// Creates a fix-it to insert a C-style nullability keyword at \p pointerLoc,
3676 /// taking into account whitespace before and after.
3678  SourceLocation PointerLoc,
3680  assert(PointerLoc.isValid());
3681  if (PointerLoc.isMacroID())
3682  return;
3683 
3684  SourceLocation FixItLoc = S.getLocForEndOfToken(PointerLoc);
3685  if (!FixItLoc.isValid() || FixItLoc == PointerLoc)
3686  return;
3687 
3688  const char *NextChar = S.SourceMgr.getCharacterData(FixItLoc);
3689  if (!NextChar)
3690  return;
3691 
3692  SmallString<32> InsertionTextBuf{" "};
3693  InsertionTextBuf += getNullabilitySpelling(Nullability);
3694  InsertionTextBuf += " ";
3695  StringRef InsertionText = InsertionTextBuf.str();
3696 
3697  if (isWhitespace(*NextChar)) {
3698  InsertionText = InsertionText.drop_back();
3699  } else if (NextChar[-1] == '[') {
3700  if (NextChar[0] == ']')
3701  InsertionText = InsertionText.drop_back().drop_front();
3702  else
3703  InsertionText = InsertionText.drop_front();
3704  } else if (!isIdentifierBody(NextChar[0], /*allow dollar*/true) &&
3705  !isIdentifierBody(NextChar[-1], /*allow dollar*/true)) {
3706  InsertionText = InsertionText.drop_back().drop_front();
3707  }
3708 
3709  Diag << FixItHint::CreateInsertion(FixItLoc, InsertionText);
3710 }
3711 
3713  SimplePointerKind PointerKind,
3714  SourceLocation PointerLoc,
3715  SourceLocation PointerEndLoc) {
3716  assert(PointerLoc.isValid());
3717 
3718  if (PointerKind == SimplePointerKind::Array) {
3719  S.Diag(PointerLoc, diag::warn_nullability_missing_array);
3720  } else {
3721  S.Diag(PointerLoc, diag::warn_nullability_missing)
3722  << static_cast<unsigned>(PointerKind);
3723  }
3724 
3725  auto FixItLoc = PointerEndLoc.isValid() ? PointerEndLoc : PointerLoc;
3726  if (FixItLoc.isMacroID())
3727  return;
3728 
3729  auto addFixIt = [&](NullabilityKind Nullability) {
3730  auto Diag = S.Diag(FixItLoc, diag::note_nullability_fix_it);
3731  Diag << static_cast<unsigned>(Nullability);
3732  Diag << static_cast<unsigned>(PointerKind);
3733  fixItNullability(S, Diag, FixItLoc, Nullability);
3734  };
3735  addFixIt(NullabilityKind::Nullable);
3736  addFixIt(NullabilityKind::NonNull);
3737 }
3738 
3739 /// Complains about missing nullability if the file containing \p pointerLoc
3740 /// has other uses of nullability (either the keywords or the \c assume_nonnull
3741 /// pragma).
3742 ///
3743 /// If the file has \e not seen other uses of nullability, this particular
3744 /// pointer is saved for possible later diagnosis. See recordNullabilitySeen().
3745 static void
3747  SourceLocation pointerLoc,
3748  SourceLocation pointerEndLoc = SourceLocation()) {
3749  // Determine which file we're performing consistency checking for.
3750  FileID file = getNullabilityCompletenessCheckFileID(S, pointerLoc);
3751  if (file.isInvalid())
3752  return;
3753 
3754  // If we haven't seen any type nullability in this file, we won't warn now
3755  // about anything.
3756  FileNullability &fileNullability = S.NullabilityMap[file];
3757  if (!fileNullability.SawTypeNullability) {
3758  // If this is the first pointer declarator in the file, and the appropriate
3759  // warning is on, record it in case we need to diagnose it retroactively.
3760  diag::kind diagKind;
3761  if (pointerKind == SimplePointerKind::Array)
3762  diagKind = diag::warn_nullability_missing_array;
3763  else
3764  diagKind = diag::warn_nullability_missing;
3765 
3766  if (fileNullability.PointerLoc.isInvalid() &&
3767  !S.Context.getDiagnostics().isIgnored(diagKind, pointerLoc)) {
3768  fileNullability.PointerLoc = pointerLoc;
3769  fileNullability.PointerEndLoc = pointerEndLoc;
3770  fileNullability.PointerKind = static_cast<unsigned>(pointerKind);
3771  }
3772 
3773  return;
3774  }
3775 
3776  // Complain about missing nullability.
3777  emitNullabilityConsistencyWarning(S, pointerKind, pointerLoc, pointerEndLoc);
3778 }
3779 
3780 /// Marks that a nullability feature has been used in the file containing
3781 /// \p loc.
3782 ///
3783 /// If this file already had pointer types in it that were missing nullability,
3784 /// the first such instance is retroactively diagnosed.
3785 ///
3786 /// \sa checkNullabilityConsistency
3789  if (file.isInvalid())
3790  return;
3791 
3792  FileNullability &fileNullability = S.NullabilityMap[file];
3793  if (fileNullability.SawTypeNullability)
3794  return;
3795  fileNullability.SawTypeNullability = true;
3796 
3797  // If we haven't seen any type nullability before, now we have. Retroactively
3798  // diagnose the first unannotated pointer, if there was one.
3799  if (fileNullability.PointerLoc.isInvalid())
3800  return;
3801 
3802  auto kind = static_cast<SimplePointerKind>(fileNullability.PointerKind);
3804  fileNullability.PointerEndLoc);
3805 }
3806 
3807 /// Returns true if any of the declarator chunks before \p endIndex include a
3808 /// level of indirection: array, pointer, reference, or pointer-to-member.
3809 ///
3810 /// Because declarator chunks are stored in outer-to-inner order, testing
3811 /// every chunk before \p endIndex is testing all chunks that embed the current
3812 /// chunk as part of their type.
3813 ///
3814 /// It is legal to pass the result of Declarator::getNumTypeObjects() as the
3815 /// end index, in which case all chunks are tested.
3816 static bool hasOuterPointerLikeChunk(const Declarator &D, unsigned endIndex) {
3817  unsigned i = endIndex;
3818  while (i != 0) {
3819  // Walk outwards along the declarator chunks.
3820  --i;
3821  const DeclaratorChunk &DC = D.getTypeObject(i);
3822  switch (DC.Kind) {
3824  break;
3829  return true;
3832  case DeclaratorChunk::Pipe:
3833  // These are invalid anyway, so just ignore.
3834  break;
3835  }
3836  }
3837  return false;
3838 }
3839 
3840 static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
3841  QualType declSpecType,
3842  TypeSourceInfo *TInfo) {
3843  // The TypeSourceInfo that this function returns will not be a null type.
3844  // If there is an error, this function will fill in a dummy type as fallback.
3845  QualType T = declSpecType;
3846  Declarator &D = state.getDeclarator();
3847  Sema &S = state.getSema();
3848  ASTContext &Context = S.Context;
3849  const LangOptions &LangOpts = S.getLangOpts();
3850 
3851  // The name we're declaring, if any.
3852  DeclarationName Name;
3853  if (D.getIdentifier())
3854  Name = D.getIdentifier();
3855 
3856  // Does this declaration declare a typedef-name?
3857  bool IsTypedefName =
3861 
3862  // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
3863  bool IsQualifiedFunction = T->isFunctionProtoType() &&
3864  (T->castAs<FunctionProtoType>()->getTypeQuals() != 0 ||
3865  T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None);
3866 
3867  // If T is 'decltype(auto)', the only declarators we can have are parens
3868  // and at most one function declarator if this is a function declaration.
3869  // If T is a deduced class template specialization type, we can have no
3870  // declarator chunks at all.
3871  if (auto *DT = T->getAs<DeducedType>()) {
3872  const AutoType *AT = T->getAs<AutoType>();
3873  bool IsClassTemplateDeduction = isa<DeducedTemplateSpecializationType>(DT);
3874  if ((AT && AT->isDecltypeAuto()) || IsClassTemplateDeduction) {
3875  for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
3876  unsigned Index = E - I - 1;
3877  DeclaratorChunk &DeclChunk = D.getTypeObject(Index);
3878  unsigned DiagId = IsClassTemplateDeduction
3879  ? diag::err_deduced_class_template_compound_type
3880  : diag::err_decltype_auto_compound_type;
3881  unsigned DiagKind = 0;
3882  switch (DeclChunk.Kind) {
3884  // FIXME: Rejecting this is a little silly.
3885  if (IsClassTemplateDeduction) {
3886  DiagKind = 4;
3887  break;
3888  }
3889  continue;
3891  if (IsClassTemplateDeduction) {
3892  DiagKind = 3;
3893  break;
3894  }
3895  unsigned FnIndex;
3896  if (D.isFunctionDeclarationContext() &&
3897  D.isFunctionDeclarator(FnIndex) && FnIndex == Index)
3898  continue;
3899  DiagId = diag::err_decltype_auto_function_declarator_not_declaration;
3900  break;
3901  }
3905  DiagKind = 0;
3906  break;
3908  DiagKind = 1;
3909  break;
3911  DiagKind = 2;
3912  break;
3913  case DeclaratorChunk::Pipe:
3914  break;
3915  }
3916 
3917  S.Diag(DeclChunk.Loc, DiagId) << DiagKind;
3918  D.setInvalidType(true);
3919  break;
3920  }
3921  }
3922  }
3923 
3924  // Determine whether we should infer _Nonnull on pointer types.
3925  Optional<NullabilityKind> inferNullability;
3926  bool inferNullabilityCS = false;
3927  bool inferNullabilityInnerOnly = false;
3928  bool inferNullabilityInnerOnlyComplete = false;
3929 
3930  // Are we in an assume-nonnull region?
3931  bool inAssumeNonNullRegion = false;
3932  SourceLocation assumeNonNullLoc = S.PP.getPragmaAssumeNonNullLoc();
3933  if (assumeNonNullLoc.isValid()) {
3934  inAssumeNonNullRegion = true;
3935  recordNullabilitySeen(S, assumeNonNullLoc);
3936  }
3937 
3938  // Whether to complain about missing nullability specifiers or not.
3939  enum {
3940  /// Never complain.
3941  CAMN_No,
3942  /// Complain on the inner pointers (but not the outermost
3943  /// pointer).
3944  CAMN_InnerPointers,
3945  /// Complain about any pointers that don't have nullability
3946  /// specified or inferred.
3947  CAMN_Yes
3948  } complainAboutMissingNullability = CAMN_No;
3949  unsigned NumPointersRemaining = 0;
3950  auto complainAboutInferringWithinChunk = PointerWrappingDeclaratorKind::None;
3951 
3952  if (IsTypedefName) {
3953  // For typedefs, we do not infer any nullability (the default),
3954  // and we only complain about missing nullability specifiers on
3955  // inner pointers.
3956  complainAboutMissingNullability = CAMN_InnerPointers;
3957 
3958  if (T->canHaveNullability(/*ResultIfUnknown*/false) &&
3959  !T->getNullability(S.Context)) {
3960  // Note that we allow but don't require nullability on dependent types.
3961  ++NumPointersRemaining;
3962  }
3963 
3964  for (unsigned i = 0, n = D.getNumTypeObjects(); i != n; ++i) {
3965  DeclaratorChunk &chunk = D.getTypeObject(i);
3966  switch (chunk.Kind) {
3969  case DeclaratorChunk::Pipe:
3970  break;
3971 
3974  ++NumPointersRemaining;
3975  break;
3976 
3979  continue;
3980 
3982  ++NumPointersRemaining;
3983  continue;
3984  }
3985  }
3986  } else {
3987  bool isFunctionOrMethod = false;
3988  switch (auto context = state.getDeclarator().getContext()) {
3994  isFunctionOrMethod = true;
3995  LLVM_FALLTHROUGH;
3996 
3998  if (state.getDeclarator().isObjCIvar() && !isFunctionOrMethod) {
3999  complainAboutMissingNullability = CAMN_No;
4000  break;
4001  }
4002 
4003  // Weak properties are inferred to be nullable.
4004  if (state.getDeclarator().isObjCWeakProperty() && inAssumeNonNullRegion) {
4005  inferNullability = NullabilityKind::Nullable;
4006  break;
4007  }
4008 
4009  LLVM_FALLTHROUGH;
4010 
4013  complainAboutMissingNullability = CAMN_Yes;
4014 
4015  // Nullability inference depends on the type and declarator.
4016  auto wrappingKind = PointerWrappingDeclaratorKind::None;
4017  switch (classifyPointerDeclarator(S, T, D, wrappingKind)) {
4018  case PointerDeclaratorKind::NonPointer:
4019  case PointerDeclaratorKind::MultiLevelPointer:
4020  // Cannot infer nullability.
4021  break;
4022 
4023  case PointerDeclaratorKind::SingleLevelPointer:
4024  // Infer _Nonnull if we are in an assumes-nonnull region.
4025  if (inAssumeNonNullRegion) {
4026  complainAboutInferringWithinChunk = wrappingKind;
4027  inferNullability = NullabilityKind::NonNull;
4028  inferNullabilityCS =
4031  }
4032  break;
4033 
4034  case PointerDeclaratorKind::CFErrorRefPointer:
4035  case PointerDeclaratorKind::NSErrorPointerPointer:
4036  // Within a function or method signature, infer _Nullable at both
4037  // levels.
4038  if (isFunctionOrMethod && inAssumeNonNullRegion)
4039  inferNullability = NullabilityKind::Nullable;
4040  break;
4041 
4042  case PointerDeclaratorKind::MaybePointerToCFRef:
4043  if (isFunctionOrMethod) {
4044  // On pointer-to-pointer parameters marked cf_returns_retained or
4045  // cf_returns_not_retained, if the outer pointer is explicit then
4046  // infer the inner pointer as _Nullable.
4047  auto hasCFReturnsAttr = [](const AttributeList *NextAttr) -> bool {
4048  while (NextAttr) {
4049  if (NextAttr->getKind() == AttributeList::AT_CFReturnsRetained ||
4050  NextAttr->getKind() == AttributeList::AT_CFReturnsNotRetained)
4051  return true;
4052  NextAttr = NextAttr->getNext();
4053  }
4054  return false;
4055  };
4056  if (const auto *InnermostChunk = D.getInnermostNonParenChunk()) {
4057  if (hasCFReturnsAttr(D.getAttributes()) ||
4058  hasCFReturnsAttr(InnermostChunk->getAttrs()) ||
4059  hasCFReturnsAttr(D.getDeclSpec().getAttributes().getList())) {
4060  inferNullability = NullabilityKind::Nullable;
4061  inferNullabilityInnerOnly = true;
4062  }
4063  }
4064  }
4065  break;
4066  }
4067  break;
4068  }
4069 
4071  complainAboutMissingNullability = CAMN_Yes;
4072  break;
4073 
4091  // Don't infer in these contexts.
4092  break;
4093  }
4094  }
4095 
4096  // Local function that returns true if its argument looks like a va_list.
4097  auto isVaList = [&S](QualType T) -> bool {
4098  auto *typedefTy = T->getAs<TypedefType>();
4099  if (!typedefTy)
4100  return false;
4101  TypedefDecl *vaListTypedef = S.Context.getBuiltinVaListDecl();
4102  do {
4103  if (typedefTy->getDecl() == vaListTypedef)
4104  return true;
4105  if (auto *name = typedefTy->getDecl()->getIdentifier())
4106  if (name->isStr("va_list"))
4107  return true;
4108  typedefTy = typedefTy->desugar()->getAs<TypedefType>();
4109  } while (typedefTy);
4110  return false;
4111  };
4112 
4113  // Local function that checks the nullability for a given pointer declarator.
4114  // Returns true if _Nonnull was inferred.
4115  auto inferPointerNullability = [&](SimplePointerKind pointerKind,
4116  SourceLocation pointerLoc,
4117  SourceLocation pointerEndLoc,
4118  AttributeList *&attrs) -> AttributeList * {
4119  // We've seen a pointer.
4120  if (NumPointersRemaining > 0)
4121  --NumPointersRemaining;
4122 
4123  // If a nullability attribute is present, there's nothing to do.
4124  if (hasNullabilityAttr(attrs))
4125  return nullptr;
4126 
4127  // If we're supposed to infer nullability, do so now.
4128  if (inferNullability && !inferNullabilityInnerOnlyComplete) {
4129  AttributeList::Syntax syntax
4130  = inferNullabilityCS ? AttributeList::AS_ContextSensitiveKeyword
4132  AttributeList *nullabilityAttr = state.getDeclarator().getAttributePool()
4133  .create(
4135  *inferNullability),
4136  SourceRange(pointerLoc),
4137  nullptr, SourceLocation(),
4138  nullptr, 0, syntax);
4139 
4140  spliceAttrIntoList(*nullabilityAttr, attrs);
4141 
4142  if (inferNullabilityCS) {
4143  state.getDeclarator().getMutableDeclSpec().getObjCQualifiers()
4144  ->setObjCDeclQualifier(ObjCDeclSpec::DQ_CSNullability);
4145  }
4146 
4147  if (pointerLoc.isValid() &&
4148  complainAboutInferringWithinChunk !=
4150  auto Diag =
4151  S.Diag(pointerLoc, diag::warn_nullability_inferred_on_nested_type);
4152  Diag << static_cast<int>(complainAboutInferringWithinChunk);
4154  }
4155 
4156  if (inferNullabilityInnerOnly)
4157  inferNullabilityInnerOnlyComplete = true;
4158  return nullabilityAttr;
4159  }
4160 
4161  // If we're supposed to complain about missing nullability, do so
4162  // now if it's truly missing.
4163  switch (complainAboutMissingNullability) {
4164  case CAMN_No:
4165  break;
4166 
4167  case CAMN_InnerPointers:
4168  if (NumPointersRemaining == 0)
4169  break;
4170  LLVM_FALLTHROUGH;
4171 
4172  case CAMN_Yes:
4173  checkNullabilityConsistency(S, pointerKind, pointerLoc, pointerEndLoc);
4174  }
4175  return nullptr;
4176  };
4177 
4178  // If the type itself could have nullability but does not, infer pointer
4179  // nullability and perform consistency checking.
4180  if (S.CodeSynthesisContexts.empty()) {
4181  if (T->canHaveNullability(/*ResultIfUnknown*/false) &&
4182  !T->getNullability(S.Context)) {
4183  if (isVaList(T)) {
4184  // Record that we've seen a pointer, but do nothing else.
4185  if (NumPointersRemaining > 0)
4186  --NumPointersRemaining;
4187  } else {
4188  SimplePointerKind pointerKind = SimplePointerKind::Pointer;
4189  if (T->isBlockPointerType())
4190  pointerKind = SimplePointerKind::BlockPointer;
4191  else if (T->isMemberPointerType())
4192  pointerKind = SimplePointerKind::MemberPointer;
4193 
4194  if (auto *attr = inferPointerNullability(
4195  pointerKind, D.getDeclSpec().getTypeSpecTypeLoc(),
4196  D.getDeclSpec().getLocEnd(),
4198  T = Context.getAttributedType(
4199  AttributedType::getNullabilityAttrKind(*inferNullability),T,T);
4200  attr->setUsedAsTypeAttr();
4201  }
4202  }
4203  }
4204 
4205  if (complainAboutMissingNullability == CAMN_Yes &&
4206  T->isArrayType() && !T->getNullability(S.Context) && !isVaList(T) &&
4207  D.isPrototypeContext() &&
4209  checkNullabilityConsistency(S, SimplePointerKind::Array,
4211  }
4212  }
4213 
4214  // Walk the DeclTypeInfo, building the recursive type as we go.
4215  // DeclTypeInfos are ordered from the identifier out, which is
4216  // opposite of what we want :).
4217  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
4218  unsigned chunkIndex = e - i - 1;
4219  state.setCurrentChunkIndex(chunkIndex);
4220  DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
4221  IsQualifiedFunction &= DeclType.Kind == DeclaratorChunk::Paren;
4222  switch (DeclType.Kind) {
4224  if (i == 0)
4225  warnAboutRedundantParens(S, D, T);
4226  T = S.BuildParenType(T);
4227  break;
4229  // If blocks are disabled, emit an error.
4230  if (!LangOpts.Blocks)
4231  S.Diag(DeclType.Loc, diag::err_blocks_disable) << LangOpts.OpenCL;
4232 
4233  // Handle pointer nullability.
4234  inferPointerNullability(SimplePointerKind::BlockPointer, DeclType.Loc,
4235  DeclType.EndLoc, DeclType.getAttrListRef());
4236 
4237  T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name);
4238  if (DeclType.Cls.TypeQuals || LangOpts.OpenCL) {
4239  // OpenCL v2.0, s6.12.5 - Block variable declarations are implicitly
4240  // qualified with const.
4241  if (LangOpts.OpenCL)
4242  DeclType.Cls.TypeQuals |= DeclSpec::TQ_const;
4243  T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals);
4244  }
4245  break;
4247  // Verify that we're not building a pointer to pointer to function with
4248  // exception specification.
4249  if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4250  S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4251  D.setInvalidType(true);
4252  // Build the type anyway.
4253  }
4254 
4255  // Handle pointer nullability
4256  inferPointerNullability(SimplePointerKind::Pointer, DeclType.Loc,
4257  DeclType.EndLoc, DeclType.getAttrListRef());
4258 
4259  if (LangOpts.ObjC1 && T->getAs<ObjCObjectType>()) {
4260  T = Context.getObjCObjectPointerType(T);
4261  if (DeclType.Ptr.TypeQuals)
4262  T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
4263  break;
4264  }
4265 
4266  // OpenCL v2.0 s6.9b - Pointer to image/sampler cannot be used.
4267  // OpenCL v2.0 s6.13.16.1 - Pointer to pipe cannot be used.
4268  // OpenCL v2.0 s6.12.5 - Pointers to Blocks are not allowed.
4269  if (LangOpts.OpenCL) {
4270  if (T->isImageType() || T->isSamplerT() || T->isPipeType() ||
4271  T->isBlockPointerType()) {
4272  S.Diag(D.getIdentifierLoc(), diag::err_opencl_pointer_to_type) << T;
4273  D.setInvalidType(true);
4274  }
4275  }
4276 
4277  T = S.BuildPointerType(T, DeclType.Loc, Name);
4278  if (DeclType.Ptr.TypeQuals)
4279  T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
4280  break;
4282  // Verify that we're not building a reference to pointer to function with
4283  // exception specification.
4284  if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4285  S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4286  D.setInvalidType(true);
4287  // Build the type anyway.
4288  }
4289  T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name);
4290 
4291  if (DeclType.Ref.HasRestrict)
4292  T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict);
4293  break;
4294  }
4295  case DeclaratorChunk::Array: {
4296  // Verify that we're not building an array of pointers to function with
4297  // exception specification.
4298  if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4299  S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4300  D.setInvalidType(true);
4301  // Build the type anyway.
4302  }
4303  DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
4304  Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
4306  if (ATI.isStar)
4307  ASM = ArrayType::Star;
4308  else if (ATI.hasStatic)
4309  ASM = ArrayType::Static;
4310  else
4311  ASM = ArrayType::Normal;
4312  if (ASM == ArrayType::Star && !D.isPrototypeContext()) {
4313  // FIXME: This check isn't quite right: it allows star in prototypes
4314  // for function definitions, and disallows some edge cases detailed
4315  // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
4316  S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
4317  ASM = ArrayType::Normal;
4318  D.setInvalidType(true);
4319  }
4320 
4321  // C99 6.7.5.2p1: The optional type qualifiers and the keyword static
4322  // shall appear only in a declaration of a function parameter with an
4323  // array type, ...
4324  if (ASM == ArrayType::Static || ATI.TypeQuals) {
4325  if (!(D.isPrototypeContext() ||
4327  S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype) <<
4328  (ASM == ArrayType::Static ? "'static'" : "type qualifier");
4329  // Remove the 'static' and the type qualifiers.
4330  if (ASM == ArrayType::Static)
4331  ASM = ArrayType::Normal;
4332  ATI.TypeQuals = 0;
4333  D.setInvalidType(true);
4334  }
4335 
4336  // C99 6.7.5.2p1: ... and then only in the outermost array type
4337  // derivation.
4338  if (hasOuterPointerLikeChunk(D, chunkIndex)) {
4339  S.Diag(DeclType.Loc, diag::err_array_static_not_outermost) <<
4340  (ASM == ArrayType::Static ? "'static'" : "type qualifier");
4341  if (ASM == ArrayType::Static)
4342  ASM = ArrayType::Normal;
4343  ATI.TypeQuals = 0;
4344  D.setInvalidType(true);
4345  }
4346  }
4347  const AutoType *AT = T->getContainedAutoType();
4348  // Allow arrays of auto if we are a generic lambda parameter.
4349  // i.e. [](auto (&array)[5]) { return array[0]; }; OK
4350  if (AT &&
4352  // We've already diagnosed this for decltype(auto).
4353  if (!AT->isDecltypeAuto())
4354  S.Diag(DeclType.Loc, diag::err_illegal_decl_array_of_auto)
4355  << getPrintableNameForEntity(Name) << T;
4356  T = QualType();
4357  break;
4358  }
4359 
4360  // Array parameters can be marked nullable as well, although it's not
4361  // necessary if they're marked 'static'.
4362  if (complainAboutMissingNullability == CAMN_Yes &&
4363  !hasNullabilityAttr(DeclType.getAttrs()) &&
4364  ASM != ArrayType::Static &&
4365  D.isPrototypeContext() &&
4366  !hasOuterPointerLikeChunk(D, chunkIndex)) {
4367  checkNullabilityConsistency(S, SimplePointerKind::Array, DeclType.Loc);
4368  }
4369 
4370  T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals,
4371  SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
4372  break;
4373  }
4375  // If the function declarator has a prototype (i.e. it is not () and
4376  // does not have a K&R-style identifier list), then the arguments are part
4377  // of the type, otherwise the argument list is ().
4378  const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
4379  IsQualifiedFunction = FTI.TypeQuals || FTI.hasRefQualifier();
4380 
4381  // Check for auto functions and trailing return type and adjust the
4382  // return type accordingly.
4383  if (!D.isInvalidType()) {
4384  // trailing-return-type is only required if we're declaring a function,
4385  // and not, for instance, a pointer to a function.
4386  if (D.getDeclSpec().hasAutoTypeSpec() &&
4387  !FTI.hasTrailingReturnType() && chunkIndex == 0 &&
4388  !S.getLangOpts().CPlusPlus14) {
4391  ? diag::err_auto_missing_trailing_return
4392  : diag::err_deduced_return_type);
4393  T = Context.IntTy;
4394  D.setInvalidType(true);
4395  } else if (FTI.hasTrailingReturnType()) {
4396  // T must be exactly 'auto' at this point. See CWG issue 681.
4397  if (isa<ParenType>(T)) {
4398  S.Diag(D.getLocStart(),
4399  diag::err_trailing_return_in_parens)
4400  << T << D.getSourceRange();
4401  D.setInvalidType(true);
4402  } else if (D.getName().getKind() ==
4404  if (T != Context.DependentTy) {
4405  S.Diag(D.getDeclSpec().getLocStart(),
4406  diag::err_deduction_guide_with_complex_decl)
4407  << D.getSourceRange();
4408  D.setInvalidType(true);
4409  }
4411  (T.hasQualifiers() || !isa<AutoType>(T) ||
4412  cast<AutoType>(T)->getKeyword() !=
4415  diag::err_trailing_return_without_auto)
4416  << T << D.getDeclSpec().getSourceRange();
4417  D.setInvalidType(true);
4418  }
4419  T = S.GetTypeFromParser(FTI.getTrailingReturnType(), &TInfo);
4420  if (T.isNull()) {
4421  // An error occurred parsing the trailing return type.
4422  T = Context.IntTy;
4423  D.setInvalidType(true);
4424  }
4425  }
4426  }
4427 
4428  // C99 6.7.5.3p1: The return type may not be a function or array type.
4429  // For conversion functions, we'll diagnose this particular error later.
4430  if (!D.isInvalidType() && (T->isArrayType() || T->isFunctionType()) &&
4431  (D.getName().getKind() !=
4433  unsigned diagID = diag::err_func_returning_array_function;
4434  // Last processing chunk in block context means this function chunk
4435  // represents the block.
4436  if (chunkIndex == 0 &&
4438  diagID = diag::err_block_returning_array_function;
4439  S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T;
4440  T = Context.IntTy;
4441  D.setInvalidType(true);
4442  }
4443 
4444  // Do not allow returning half FP value.
4445  // FIXME: This really should be in BuildFunctionType.
4446  if (T->isHalfType()) {
4447  if (S.getLangOpts().OpenCL) {
4448  if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16")) {
4449  S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return)
4450  << T << 0 /*pointer hint*/;
4451  D.setInvalidType(true);
4452  }
4453  } else if (!S.getLangOpts().HalfArgsAndReturns) {
4454  S.Diag(D.getIdentifierLoc(),
4455  diag::err_parameters_retval_cannot_have_fp16_type) << 1;
4456  D.setInvalidType(true);
4457  }
4458  }
4459 
4460  if (LangOpts.OpenCL) {
4461  // OpenCL v2.0 s6.12.5 - A block cannot be the return value of a
4462  // function.
4463  if (T->isBlockPointerType() || T->isImageType() || T->isSamplerT() ||
4464  T->isPipeType()) {
4465  S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return)
4466  << T << 1 /*hint off*/;
4467  D.setInvalidType(true);
4468  }
4469  // OpenCL doesn't support variadic functions and blocks
4470  // (s6.9.e and s6.12.5 OpenCL v2.0) except for printf.
4471  // We also allow here any toolchain reserved identifiers.
4472  if (FTI.isVariadic &&
4473  !(D.getIdentifier() &&
4474  ((D.getIdentifier()->getName() == "printf" &&
4475  LangOpts.OpenCLVersion >= 120) ||
4476  D.getIdentifier()->getName().startswith("__")))) {
4477  S.Diag(D.getIdentifierLoc(), diag::err_opencl_variadic_function);
4478  D.setInvalidType(true);
4479  }
4480  }
4481 
4482  // Methods cannot return interface types. All ObjC objects are
4483  // passed by reference.
4484  if (T->isObjCObjectType()) {
4485  SourceLocation DiagLoc, FixitLoc;
4486  if (TInfo) {
4487  DiagLoc = TInfo->getTypeLoc().getLocStart();
4488  FixitLoc = S.getLocForEndOfToken(TInfo->getTypeLoc().getLocEnd());
4489  } else {
4490  DiagLoc = D.getDeclSpec().getTypeSpecTypeLoc();
4491  FixitLoc = S.getLocForEndOfToken(D.getDeclSpec().getLocEnd());
4492  }
4493  S.Diag(DiagLoc, diag::err_object_cannot_be_passed_returned_by_value)
4494  << 0 << T
4495  << FixItHint::CreateInsertion(FixitLoc, "*");
4496 
4497  T = Context.getObjCObjectPointerType(T);
4498  if (TInfo) {
4499  TypeLocBuilder TLB;
4500  TLB.pushFullCopy(TInfo->getTypeLoc());
4502  TLoc.setStarLoc(FixitLoc);
4503  TInfo = TLB.getTypeSourceInfo(Context, T);
4504  }
4505 
4506  D.setInvalidType(true);
4507  }
4508 
4509  // cv-qualifiers on return types are pointless except when the type is a
4510  // class type in C++.
4511  if ((T.getCVRQualifiers() || T->isAtomicType()) &&
4512  !(S.getLangOpts().CPlusPlus &&
4513  (T->isDependentType() || T->isRecordType()))) {
4514  if (T->isVoidType() && !S.getLangOpts().CPlusPlus &&
4516  // [6.9.1/3] qualified void return is invalid on a C
4517  // function definition. Apparently ok on declarations and
4518  // in C++ though (!)
4519  S.Diag(DeclType.Loc, diag::err_func_returning_qualified_void) << T;
4520  } else
4521  diagnoseRedundantReturnTypeQualifiers(S, T, D, chunkIndex);
4522  }
4523 
4524  // Objective-C ARC ownership qualifiers are ignored on the function
4525  // return type (by type canonicalization). Complain if this attribute
4526  // was written here.
4527  if (T.getQualifiers().hasObjCLifetime()) {
4528  SourceLocation AttrLoc;
4529  if (chunkIndex + 1 < D.getNumTypeObjects()) {
4530  DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1);
4531  for (const AttributeList *Attr = ReturnTypeChunk.getAttrs();
4532  Attr; Attr = Attr->getNext()) {
4533  if (Attr->getKind() == AttributeList::AT_ObjCOwnership) {
4534  AttrLoc = Attr->getLoc();
4535  break;
4536  }
4537  }
4538  }
4539  if (AttrLoc.isInvalid()) {
4540  for (const AttributeList *Attr
4541  = D.getDeclSpec().getAttributes().getList();
4542  Attr; Attr = Attr->getNext()) {
4543  if (Attr->getKind() == AttributeList::AT_ObjCOwnership) {
4544  AttrLoc = Attr->getLoc();
4545  break;
4546  }
4547  }
4548  }
4549 
4550  if (AttrLoc.isValid()) {
4551  // The ownership attributes are almost always written via
4552  // the predefined
4553  // __strong/__weak/__autoreleasing/__unsafe_unretained.
4554  if (AttrLoc.isMacroID())
4555  AttrLoc =
4557 
4558  S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type)
4559  << T.getQualifiers().getObjCLifetime();
4560  }
4561  }
4562 
4563  if (LangOpts.CPlusPlus && D.getDeclSpec().hasTagDefinition()) {
4564  // C++ [dcl.fct]p6:
4565  // Types shall not be defined in return or parameter types.
4566  TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
4567  S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
4568  << Context.getTypeDeclType(Tag);
4569  }
4570 
4571  // Exception specs are not allowed in typedefs. Complain, but add it
4572  // anyway.
4573  if (IsTypedefName && FTI.getExceptionSpecType() && !LangOpts.CPlusPlus17)
4574  S.Diag(FTI.getExceptionSpecLocBeg(),
4575  diag::err_exception_spec_in_typedef)
4578 
4579  // If we see "T var();" or "T var(T());" at block scope, it is probably
4580  // an attempt to initialize a variable, not a function declaration.
4581  if (FTI.isAmbiguous)
4582  warnAboutAmbiguousFunction(S, D, DeclType, T);
4583 
4584  FunctionType::ExtInfo EI(getCCForDeclaratorChunk(S, D, FTI, chunkIndex));
4585 
4586  if (!FTI.NumParams && !FTI.isVariadic && !LangOpts.CPlusPlus
4587  && !LangOpts.OpenCL) {
4588  // Simple void foo(), where the incoming T is the result type.
4589  T = Context.getFunctionNoProtoType(T, EI);
4590  } else {
4591  // We allow a zero-parameter variadic function in C if the
4592  // function is marked with the "overloadable" attribute. Scan
4593  // for this attribute now.
4594  if (!FTI.NumParams && FTI.isVariadic && !LangOpts.CPlusPlus) {
4595  bool Overloadable = false;
4596  for (const AttributeList *Attrs = D.getAttributes();
4597  Attrs; Attrs = Attrs->getNext()) {
4598  if (Attrs->getKind() == AttributeList::AT_Overloadable) {
4599  Overloadable = true;
4600  break;
4601  }
4602  }
4603 
4604  if (!Overloadable)
4605  S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_param);
4606  }
4607 
4608  if (FTI.NumParams && FTI.Params[0].Param == nullptr) {
4609  // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function
4610  // definition.
4611  S.Diag(FTI.Params[0].IdentLoc,
4612  diag::err_ident_list_in_fn_declaration);
4613  D.setInvalidType(true);
4614  // Recover by creating a K&R-style function type.
4615  T = Context.getFunctionNoProtoType(T, EI);
4616  break;
4617  }
4618 
4620  EPI.ExtInfo = EI;
4621  EPI.Variadic = FTI.isVariadic;
4623  EPI.TypeQuals = FTI.TypeQuals;
4624  EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None
4626  : RQ_RValue;
4627 
4628  // Otherwise, we have a function with a parameter list that is
4629  // potentially variadic.
4630  SmallVector<QualType, 16> ParamTys;
4631  ParamTys.reserve(FTI.NumParams);
4632 
4634  ExtParameterInfos(FTI.NumParams);
4635  bool HasAnyInterestingExtParameterInfos = false;
4636 
4637  for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
4638  ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
4639  QualType ParamTy = Param->getType();
4640  assert(!ParamTy.isNull() && "Couldn't parse type?");
4641 
4642  // Look for 'void'. void is allowed only as a single parameter to a
4643  // function with no other parameters (C99 6.7.5.3p10). We record
4644  // int(void) as a FunctionProtoType with an empty parameter list.
4645  if (ParamTy->isVoidType()) {
4646  // If this is something like 'float(int, void)', reject it. 'void'
4647  // is an incomplete type (C99 6.2.5p19) and function decls cannot
4648  // have parameters of incomplete type.
4649  if (FTI.NumParams != 1 || FTI.isVariadic) {
4650  S.Diag(DeclType.Loc, diag::err_void_only_param);
4651  ParamTy = Context.IntTy;
4652  Param->setType(ParamTy);
4653  } else if (FTI.Params[i].Ident) {
4654  // Reject, but continue to parse 'int(void abc)'.
4655  S.Diag(FTI.Params[i].IdentLoc, diag::err_param_with_void_type);
4656  ParamTy = Context.IntTy;
4657  Param->setType(ParamTy);
4658  } else {
4659  // Reject, but continue to parse 'float(const void)'.
4660  if (ParamTy.hasQualifiers())
4661  S.Diag(DeclType.Loc, diag::err_void_param_qualified);
4662 
4663  // Do not add 'void' to the list.
4664  break;
4665  }
4666  } else if (ParamTy->isHalfType()) {
4667  // Disallow half FP parameters.
4668  // FIXME: This really should be in BuildFunctionType.
4669  if (S.getLangOpts().OpenCL) {
4670  if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16")) {
4671  S.Diag(Param->getLocation(),
4672  diag::err_opencl_half_param) << ParamTy;
4673  D.setInvalidType();
4674  Param->setInvalidDecl();
4675  }
4676  } else if (!S.getLangOpts().HalfArgsAndReturns) {
4677  S.Diag(Param->getLocation(),
4678  diag::err_parameters_retval_cannot_have_fp16_type) << 0;
4679  D.setInvalidType();
4680  }
4681  } else if (!FTI.hasPrototype) {
4682  if (ParamTy->isPromotableIntegerType()) {
4683  ParamTy = Context.getPromotedIntegerType(ParamTy);
4684  Param->setKNRPromoted(true);
4685  } else if (const BuiltinType* BTy = ParamTy->getAs<BuiltinType>()) {
4686  if (BTy->getKind() == BuiltinType::Float) {
4687  ParamTy = Context.DoubleTy;
4688  Param->setKNRPromoted(true);
4689  }
4690  }
4691  }
4692 
4693  if (LangOpts.ObjCAutoRefCount && Param->hasAttr<NSConsumedAttr>()) {
4694  ExtParameterInfos[i] = ExtParameterInfos[i].withIsConsumed(true);
4695  HasAnyInterestingExtParameterInfos = true;
4696  }
4697 
4698  if (auto attr = Param->getAttr<ParameterABIAttr>()) {
4699  ExtParameterInfos[i] =
4700  ExtParameterInfos[i].withABI(attr->getABI());
4701  HasAnyInterestingExtParameterInfos = true;
4702  }
4703 
4704  if (Param->hasAttr<PassObjectSizeAttr>()) {
4705  ExtParameterInfos[i] = ExtParameterInfos[i].withHasPassObjectSize();
4706  HasAnyInterestingExtParameterInfos = true;
4707  }
4708 
4709  if (Param->hasAttr<NoEscapeAttr>()) {
4710  ExtParameterInfos[i] = ExtParameterInfos[i].withIsNoEscape(true);
4711  HasAnyInterestingExtParameterInfos = true;
4712  }
4713 
4714  ParamTys.push_back(ParamTy);
4715  }
4716 
4717  if (HasAnyInterestingExtParameterInfos) {
4718  EPI.ExtParameterInfos = ExtParameterInfos.data();
4719  checkExtParameterInfos(S, ParamTys, EPI,
4720  [&](unsigned i) { return FTI.Params[i].Param->getLocation(); });
4721  }
4722 
4723  SmallVector<QualType, 4> Exceptions;
4724  SmallVector<ParsedType, 2> DynamicExceptions;
4725  SmallVector<SourceRange, 2> DynamicExceptionRanges;
4726  Expr *NoexceptExpr = nullptr;
4727 
4728  if (FTI.getExceptionSpecType() == EST_Dynamic) {
4729  // FIXME: It's rather inefficient to have to split into two vectors
4730  // here.
4731  unsigned N = FTI.getNumExceptions();
4732  DynamicExceptions.reserve(N);
4733  DynamicExceptionRanges.reserve(N);
4734  for (unsigned I = 0; I != N; ++I) {
4735  DynamicExceptions.push_back(FTI.Exceptions[I].Ty);
4736  DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range);
4737  }
4738  } else if (isComputedNoexcept(FTI.getExceptionSpecType())) {
4739  NoexceptExpr = FTI.NoexceptExpr;
4740  }
4741 
4743  FTI.getExceptionSpecType(),
4744  DynamicExceptions,
4745  DynamicExceptionRanges,
4746  NoexceptExpr,
4747  Exceptions,
4748  EPI.ExceptionSpec);
4749 
4750  T = Context.getFunctionType(T, ParamTys, EPI);
4751  }
4752  break;
4753  }
4755  // The scope spec must refer to a class, or be dependent.
4756  CXXScopeSpec &SS = DeclType.Mem.Scope();
4757  QualType ClsType;
4758 
4759  // Handle pointer nullability.
4760  inferPointerNullability(SimplePointerKind::MemberPointer, DeclType.Loc,
4761  DeclType.EndLoc, DeclType.getAttrListRef());
4762 
4763  if (SS.isInvalid()) {
4764  // Avoid emitting extra errors if we already errored on the scope.
4765  D.setInvalidType(true);
4766  } else if (S.isDependentScopeSpecifier(SS) ||
4767  dyn_cast_or_null<CXXRecordDecl>(S.computeDeclContext(SS))) {
4768  NestedNameSpecifier *NNS = SS.getScopeRep();
4769  NestedNameSpecifier *NNSPrefix = NNS->getPrefix();
4770  switch (NNS->getKind()) {
4772  ClsType = Context.getDependentNameType(ETK_None, NNSPrefix,
4773  NNS->getAsIdentifier());
4774  break;
4775 
4780  llvm_unreachable("Nested-name-specifier must name a type");
4781 
4784  ClsType = QualType(NNS->getAsType(), 0);
4785  // Note: if the NNS has a prefix and ClsType is a nondependent
4786  // TemplateSpecializationType, then the NNS prefix is NOT included
4787  // in ClsType; hence we wrap ClsType into an ElaboratedType.
4788  // NOTE: in particular, no wrap occurs if ClsType already is an
4789  // Elaborated, DependentName, or DependentTemplateSpecialization.
4790  if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType()))
4791  ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType);
4792  break;
4793  }
4794  } else {
4795  S.Diag(DeclType.Mem.Scope().getBeginLoc(),
4796  diag::err_illegal_decl_mempointer_in_nonclass)
4797  << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
4798  << DeclType.Mem.Scope().getRange();
4799  D.setInvalidType(true);
4800  }
4801 
4802  if (!ClsType.isNull())
4803  T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc,
4804  D.getIdentifier());
4805  if (T.isNull()) {
4806  T = Context.IntTy;
4807  D.setInvalidType(true);
4808  } else if (DeclType.Mem.TypeQuals) {
4809  T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals);
4810  }
4811  break;
4812  }
4813 
4814  case DeclaratorChunk::Pipe: {
4815  T = S.BuildReadPipeType(T, DeclType.Loc);
4816  processTypeAttrs(state, T, TAL_DeclSpec,
4818  break;
4819  }
4820  }
4821 
4822  if (T.isNull()) {
4823  D.setInvalidType(true);
4824  T = Context.IntTy;
4825  }
4826 
4827  // See if there are any attributes on this declarator chunk.
4828  processTypeAttrs(state, T, TAL_DeclChunk,
4829  const_cast<AttributeList *>(DeclType.getAttrs()));
4830  }
4831 
4832  // GNU warning -Wstrict-prototypes
4833  // Warn if a function declaration is without a prototype.
4834  // This warning is issued for all kinds of unprototyped function
4835  // declarations (i.e. function type typedef, function pointer etc.)
4836  // C99 6.7.5.3p14:
4837  // The empty list in a function declarator that is not part of a definition
4838  // of that function specifies that no information about the number or types
4839  // of the parameters is supplied.
4840  if (!LangOpts.CPlusPlus && D.getFunctionDefinitionKind() == FDK_Declaration) {
4841  bool IsBlock = false;
4842  for (const DeclaratorChunk &DeclType : D.type_objects()) {
4843  switch (DeclType.Kind) {
4845  IsBlock = true;
4846  break;
4848  const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
4849  if (FTI.NumParams == 0 && !FTI.isVariadic)
4850  S.Diag(DeclType.Loc, diag::warn_strict_prototypes)
4851  << IsBlock
4852  << FixItHint::CreateInsertion(FTI.getRParenLoc(), "void");
4853  IsBlock = false;
4854  break;
4855  }
4856  default:
4857  break;
4858  }
4859  }
4860  }
4861 
4862  assert(!T.isNull() && "T must not be null after this point");
4863 
4864  if (LangOpts.CPlusPlus && T->isFunctionType()) {
4865  const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
4866  assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
4867 
4868  // C++ 8.3.5p4:
4869  // A cv-qualifier-seq shall only be part of the function type
4870  // for a nonstatic member function, the function type to which a pointer
4871  // to member refers, or the top-level function type of a function typedef
4872  // declaration.
4873  //
4874  // Core issue 547 also allows cv-qualifiers on function types that are
4875  // top-level template type arguments.
4876  enum { NonMember, Member, DeductionGuide } Kind = NonMember;
4878  Kind = DeductionGuide;
4879  else if (!D.getCXXScopeSpec().isSet()) {
4883  Kind = Member;
4884  } else {
4886  if (!DC || DC->isRecord())
4887  Kind = Member;
4888  }
4889 
4890  // C++11 [dcl.fct]p6 (w/DR1417):
4891  // An attempt to specify a function type with a cv-qualifier-seq or a
4892  // ref-qualifier (including by typedef-name) is ill-formed unless it is:
4893  // - the function type for a non-static member function,
4894  // - the function type to which a pointer to member refers,
4895  // - the top-level function type of a function typedef declaration or
4896  // alias-declaration,
4897  // - the type-id in the default argument of a type-parameter, or
4898  // - the type-id of a template-argument for a type-parameter
4899  //
4900  // FIXME: Checking this here is insufficient. We accept-invalid on:
4901  //
4902  // template<typename T> struct S { void f(T); };
4903  // S<int() const> s;
4904  //
4905  // ... for instance.
4906  if (IsQualifiedFunction &&
4907  !(Kind == Member &&
4909  !IsTypedefName &&
4912  SourceLocation Loc = D.getLocStart();
4913  SourceRange RemovalRange;
4914  unsigned I;
4915  if (D.isFunctionDeclarator(I)) {
4916  SmallVector<SourceLocation, 4> RemovalLocs;
4917  const DeclaratorChunk &Chunk = D.getTypeObject(I);
4918  assert(Chunk.Kind == DeclaratorChunk::Function);
4919  if (Chunk.Fun.hasRefQualifier())
4920  RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc());
4921  if (Chunk.Fun.TypeQuals & Qualifiers::Const)
4922  RemovalLocs.push_back(Chunk.Fun.getConstQualifierLoc());
4923  if (Chunk.Fun.TypeQuals & Qualifiers::Volatile)
4924  RemovalLocs.push_back(Chunk.Fun.getVolatileQualifierLoc());
4925  if (Chunk.Fun.TypeQuals & Qualifiers::Restrict)
4926  RemovalLocs.push_back(Chunk.Fun.getRestrictQualifierLoc());
4927  if (!RemovalLocs.empty()) {
4928  llvm::sort(RemovalLocs.begin(), RemovalLocs.end(),
4930  RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back());
4931  Loc = RemovalLocs.front();
4932  }
4933  }
4934 
4935  S.Diag(Loc, diag::err_invalid_qualified_function_type)
4936  << Kind << D.isFunctionDeclarator() << T
4938  << FixItHint::CreateRemoval(RemovalRange);
4939 
4940  // Strip the cv-qualifiers and ref-qualifiers from the type.
4942  EPI.TypeQuals = 0;
4943  EPI.RefQualifier = RQ_None;
4944 
4945  T = Context.getFunctionType(FnTy->getReturnType(), FnTy->getParamTypes(),
4946  EPI);
4947  // Rebuild any parens around the identifier in the function type.
4948  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
4950  break;
4951  T = S.BuildParenType(T);
4952  }
4953  }
4954  }
4955 
4956  // Apply any undistributed attributes from the declarator.
4958 
4959  // Diagnose any ignored type attributes.
4960  state.diagnoseIgnoredTypeAttrs(T);
4961 
4962  // C++0x [dcl.constexpr]p9:
4963  // A constexpr specifier used in an object declaration declares the object
4964  // as const.
4965  if (D.getDeclSpec().isConstexprSpecified() && T->isObjectType()) {
4966  T.addConst();
4967  }
4968 
4969  // If there was an ellipsis in the declarator, the declaration declares a
4970  // parameter pack whose type may be a pack expansion type.
4971  if (D.hasEllipsis()) {
4972  // C++0x [dcl.fct]p13:
4973  // A declarator-id or abstract-declarator containing an ellipsis shall
4974  // only be used in a parameter-declaration. Such a parameter-declaration
4975  // is a parameter pack (14.5.3). [...]
4976  switch (D.getContext()) {
4979  // C++0x [dcl.fct]p13:
4980  // [...] When it is part of a parameter-declaration-clause, the
4981  // parameter pack is a function parameter pack (14.5.3). The type T
4982  // of the declarator-id of the function parameter pack shall contain
4983  // a template parameter pack; each template parameter pack in T is
4984  // expanded by the function parameter pack.
4985  //
4986  // We represent function parameter packs as function parameters whose
4987  // type is a pack expansion.
4988  if (!T->containsUnexpandedParameterPack()) {
4989  S.Diag(D.getEllipsisLoc(),
4990  diag::err_function_parameter_pack_without_parameter_packs)
4991  << T << D.getSourceRange();
4993  } else {
4994  T = Context.getPackExpansionType(T, None);
4995  }
4996  break;
4998  // C++0x [temp.param]p15:
4999  // If a template-parameter is a [...] is a parameter-declaration that
5000  // declares a parameter pack (8.3.5), then the template-parameter is a
5001  // template parameter pack (14.5.3).
5002  //
5003  // Note: core issue 778 clarifies that, if there are any unexpanded
5004  // parameter packs in the type of the non-type template parameter, then
5005  // it expands those parameter packs.
5007  T = Context.getPackExpansionType(T, None);
5008  else
5009  S.Diag(D.getEllipsisLoc(),
5010  LangOpts.CPlusPlus11
5011  ? diag::warn_cxx98_compat_variadic_templates
5012  : diag::ext_variadic_templates);
5013  break;
5014 
5017  case DeclaratorContext::ObjCParameterContext: // FIXME: special diagnostic
5018  // here?
5019  case DeclaratorContext::ObjCResultContext: // FIXME: special diagnostic
5020  // here?
5040  // FIXME: We may want to allow parameter packs in block-literal contexts
5041  // in the future.
5042  S.Diag(D.getEllipsisLoc(),
5043  diag::err_ellipsis_in_declarator_not_parameter);
5045  break;
5046  }
5047  }
5048 
5049  assert(!T.isNull() && "T must not be null at the end of this function");
5050  if (D.isInvalidType())
5051  return Context.getTrivialTypeSourceInfo(T);
5052 
5053  return S.GetTypeSourceInfoForDeclarator(D, T, TInfo);
5054 }
5055 
5056 /// GetTypeForDeclarator - Convert the type for the specified
5057 /// declarator to Type instances.
5058 ///
5059 /// The result of this call will never be null, but the associated
5060 /// type may be a null type if there's an unrecoverable error.
5062  // Determine the type of the declarator. Not all forms of declarator
5063  // have a type.
5064 
5065  TypeProcessingState state(*this, D);
5066 
5067  TypeSourceInfo *ReturnTypeInfo = nullptr;
5068  QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
5069  if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount)
5070  inferARCWriteback(state, T);
5071 
5072  return GetFullTypeForDeclarator(state, T, ReturnTypeInfo);
5073 }
5074 
5076  QualType &declSpecTy,
5077  Qualifiers::ObjCLifetime ownership) {
5078  if (declSpecTy->isObjCRetainableType() &&
5079  declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) {
5080  Qualifiers qs;
5081  qs.addObjCLifetime(ownership);
5082  declSpecTy = S.Context.getQualifiedType(declSpecTy, qs);
5083  }
5084 }
5085 
5086 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
5087  Qualifiers::ObjCLifetime ownership,
5088  unsigned chunkIndex) {
5089  Sema &S = state.getSema();
5090  Declarator &D = state.getDeclarator();
5091 
5092  // Look for an explicit lifetime attribute.
5093  DeclaratorChunk &chunk = D.getTypeObject(chunkIndex);
5094  for (const AttributeList *attr = chunk.getAttrs(); attr;
5095  attr = attr->getNext())
5096  if (attr->getKind() == AttributeList::AT_ObjCOwnership)
5097  return;
5098 
5099  const char *attrStr = nullptr;
5100  switch (ownership) {
5101  case Qualifiers::OCL_None: llvm_unreachable("no ownership!");
5102  case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break;
5103  case Qualifiers::OCL_Strong: attrStr = "strong"; break;
5104  case Qualifiers::OCL_Weak: attrStr = "weak"; break;
5105  case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break;
5106  }
5107 
5108  IdentifierLoc *Arg = new (S.Context) IdentifierLoc;
5109  Arg->Ident = &S.Context.Idents.get(attrStr);
5110  Arg->Loc = SourceLocation();
5111 
5112  ArgsUnion Args(Arg);
5113 
5114  // If there wasn't one, add one (with an invalid source location
5115  // so that we don't make an AttributedType for it).
5116  AttributeList *attr = D.getAttributePool()
5117  .create(&S.Context.Idents.get("objc_ownership"), SourceLocation(),
5118  /*scope*/ nullptr, SourceLocation(),
5119  /*args*/ &Args, 1, AttributeList::AS_GNU);
5120  spliceAttrIntoList(*attr, chunk.getAttrListRef());
5121 
5122  // TODO: mark whether we did this inference?
5123 }
5124 
5125 /// Used for transferring ownership in casts resulting in l-values.
5126 static void transferARCOwnership(TypeProcessingState &state,
5127  QualType &declSpecTy,
5128  Qualifiers::ObjCLifetime ownership) {
5129  Sema &S = state.getSema();
5130  Declarator &D = state.getDeclarator();
5131 
5132  int inner = -1;
5133  bool hasIndirection = false;
5134  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
5135  DeclaratorChunk &chunk = D.getTypeObject(i);
5136  switch (chunk.Kind) {
5138  // Ignore parens.
5139  break;
5140 
5144  if (inner != -1)
5145  hasIndirection = true;
5146  inner = i;
5147  break;
5148 
5150  if (inner != -1)
5151  transferARCOwnershipToDeclaratorChunk(state, ownership, i);
5152  return;
5153 
5156  case DeclaratorChunk::Pipe:
5157  return;
5158  }
5159  }
5160 
5161  if (inner == -1)
5162  return;
5163 
5164  DeclaratorChunk &chunk = D.getTypeObject(inner);
5165  if (chunk.Kind == DeclaratorChunk::Pointer) {
5166  if (declSpecTy->isObjCRetainableType())
5167  return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
5168  if (declSpecTy->isObjCObjectType() && hasIndirection)
5169  return transferARCOwnershipToDeclaratorChunk(state, ownership, inner);
5170  } else {
5171  assert(chunk.Kind == DeclaratorChunk::Array ||
5172  chunk.Kind == DeclaratorChunk::Reference);
5173  return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
5174  }
5175 }
5176 
5178  TypeProcessingState state(*this, D);
5179 
5180  TypeSourceInfo *ReturnTypeInfo = nullptr;
5181  QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
5182 
5183  if (getLangOpts().ObjC1) {
5184  Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy);
5185  if (ownership != Qualifiers::OCL_None)
5186  transferARCOwnership(state, declSpecTy, ownership);
5187  }
5188 
5189  return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo);
5190 }
5191 
5192 /// Map an AttributedType::Kind to an AttributeList::Kind.
5194  switch (kind) {
5196  return AttributeList::AT_AddressSpace;
5198  return AttributeList::AT_Regparm;
5200  return AttributeList::AT_VectorSize;
5202  return AttributeList::AT_NeonVectorType;
5204  return AttributeList::AT_NeonPolyVectorType;
5206  return AttributeList::AT_ObjCGC;
5209  return AttributeList::AT_ObjCOwnership;
5211  return AttributeList::AT_NoReturn;
5213  return AttributeList::AT_AnyX86NoCfCheck;
5215  return AttributeList::AT_CDecl;
5217  return AttributeList::AT_FastCall;
5219  return AttributeList::AT_StdCall;
5221  return AttributeList::AT_ThisCall;
5223  return AttributeList::AT_RegCall;
5225  return AttributeList::AT_Pascal;
5227  return AttributeList::AT_SwiftCall;
5229  return AttributeList::AT_VectorCall;
5232  return AttributeList::AT_Pcs;
5234  return AttributeList::AT_IntelOclBicc;
5236  return AttributeList::AT_MSABI;
5238  return AttributeList::AT_SysVABI;
5240  return AttributeList::AT_PreserveMost;
5242  return AttributeList::AT_PreserveAll;
5244  return AttributeList::AT_Ptr32;
5246  return AttributeList::AT_Ptr64;
5248  return AttributeList::AT_SPtr;
5250  return AttributeList::AT_UPtr;
5252  return AttributeList::AT_TypeNonNull;
5254  return AttributeList::AT_TypeNullable;
5256  return AttributeList::AT_TypeNullUnspecified;
5258  return AttributeList::AT_ObjCKindOf;
5260  return AttributeList::AT_NSReturnsRetained;
5261  }
5262  llvm_unreachable("unexpected attribute kind!");
5263 }
5264 
5266  const AttributeList *attrs,
5267  const AttributeList *DeclAttrs = nullptr) {
5268  // DeclAttrs and attrs cannot be both empty.
5269  assert((attrs || DeclAttrs) &&
5270  "no type attributes in the expected location!");
5271 
5272  AttributeList::Kind parsedKind = getAttrListKind(TL.getAttrKind());
5273  // Try to search for an attribute of matching kind in attrs list.
5274  while (attrs && attrs->getKind() != parsedKind)
5275  attrs = attrs->getNext();
5276  if (!attrs) {
5277  // No matching type attribute in attrs list found.
5278  // Try searching through C++11 attributes in the declarator attribute list.
5279  while (DeclAttrs && (!DeclAttrs->isCXX11Attribute() ||
5280  DeclAttrs->getKind() != parsedKind))
5281  DeclAttrs = DeclAttrs->getNext();
5282  attrs = DeclAttrs;
5283  }
5284 
5285  assert(attrs && "no matching type attribute in expected location!");
5286 
5287  TL.setAttrNameLoc(attrs->getLoc());
5288  if (TL.hasAttrExprOperand()) {
5289  assert(attrs->isArgExpr(0) && "mismatched attribute operand kind");
5290  TL.setAttrExprOperand(attrs->getArgAsExpr(0));
5291  } else if (TL.hasAttrEnumOperand()) {
5292  assert((attrs->isArgIdent(0) || attrs->isArgExpr(0)) &&
5293  "unexpected attribute operand kind");
5294  if (attrs->isArgIdent(0))
5295  TL.setAttrEnumOperandLoc(attrs->getArgAsIdent(0)->Loc);
5296  else
5298  }
5299 
5300  // FIXME: preserve this information to here.
5301  if (TL.hasAttrOperand())
5303 }
5304 
5305 namespace {
5306  class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
5307  ASTContext &Context;
5308  const DeclSpec &DS;
5309 
5310  public:
5311  TypeSpecLocFiller(ASTContext &Context, const DeclSpec &DS)
5312  : Context(Context), DS(DS) {}
5313 
5314  void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5316  Visit(TL.getModifiedLoc());
5317  }
5318  void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5319  Visit(TL.getUnqualifiedLoc());
5320  }
5321  void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5322  TL.setNameLoc(DS.getTypeSpecTypeLoc());
5323  }
5324  void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5325  TL.setNameLoc(DS.getTypeSpecTypeLoc());
5326  // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires
5327  // addition field. What we have is good enough for dispay of location
5328  // of 'fixit' on interface name.
5329  TL.setNameEndLoc(DS.getLocEnd());
5330  }
5331  void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5332  TypeSourceInfo *RepTInfo = nullptr;
5333  Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
5334  TL.copy(RepTInfo->getTypeLoc());
5335  }
5336  void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5337  TypeSourceInfo *RepTInfo = nullptr;
5338  Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
5339  TL.copy(RepTInfo->getTypeLoc());
5340  }
5341  void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
5342  TypeSourceInfo *TInfo = nullptr;
5343  Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5344 
5345  // If we got no declarator info from previous Sema routines,
5346  // just fill with the typespec loc.
5347  if (!TInfo) {
5348  TL.initialize(Context, DS.getTypeSpecTypeNameLoc());
5349  return;
5350  }
5351 
5352  TypeLoc OldTL = TInfo->getTypeLoc();
5353  if (TInfo->getType()->getAs<ElaboratedType>()) {
5354  ElaboratedTypeLoc ElabTL = OldTL.castAs<ElaboratedTypeLoc>();
5357  TL.copy(NamedTL);
5358  } else {
5359  TL.copy(OldTL.