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