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