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