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