blob: 1f4be4405b557502fac694350c244b8ed65d3772 [file] [log] [blame]
Chris Lattner2c6fcf52008-06-26 18:38:35 +00001//===--- SemaDeclAttr.cpp - Declaration Attribute Handling ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements decl-related attribute processing.
11//
12//===----------------------------------------------------------------------===//
13
David Majnemer929025d2016-01-26 19:30:26 +000014#include "clang/AST/ASTConsumer.h"
Chris Lattner2c6fcf52008-06-26 18:38:35 +000015#include "clang/AST/ASTContext.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000016#include "clang/AST/ASTMutationListener.h"
DeLesley Hutchins5ff430c2012-05-04 16:28:38 +000017#include "clang/AST/CXXInheritance.h"
John McCall28a0cf72010-08-25 07:42:41 +000018#include "clang/AST/DeclCXX.h"
Daniel Dunbar56fdb6a2008-08-11 06:23:49 +000019#include "clang/AST/DeclObjC.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/AST/DeclTemplate.h"
Daniel Dunbar56fdb6a2008-08-11 06:23:49 +000021#include "clang/AST/Expr.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000022#include "clang/AST/ExprCXX.h"
Rafael Espindoladb77c4a2013-02-26 19:13:56 +000023#include "clang/AST/Mangle.h"
Erik Pilkington5cd57172016-08-16 17:44:11 +000024#include "clang/AST/RecursiveASTVisitor.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000025#include "clang/Basic/CharInfo.h"
John McCall31168b02011-06-15 23:02:42 +000026#include "clang/Basic/SourceManager.h"
Chris Lattneracbc2d22008-06-27 22:18:37 +000027#include "clang/Basic/TargetInfo.h"
Benjamin Kramer6ee15622013-09-13 15:35:43 +000028#include "clang/Lex/Preprocessor.h"
John McCall8b0666c2010-08-20 18:27:03 +000029#include "clang/Sema/DeclSpec.h"
John McCallb45a1e72010-08-26 02:13:20 +000030#include "clang/Sema/DelayedDiagnostic.h"
Artem Belevichbcec9da2016-06-06 22:54:57 +000031#include "clang/Sema/Initialization.h"
John McCallf1e8b342011-09-29 07:17:38 +000032#include "clang/Sema/Lookup.h"
Richard Smithe233fbf2013-01-28 22:42:45 +000033#include "clang/Sema/Scope.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000034#include "clang/Sema/SemaInternal.h"
George Burgess IV177399e2017-01-09 04:12:14 +000035#include "llvm/ADT/STLExtras.h"
Chris Lattner30ba6742009-08-10 19:03:04 +000036#include "llvm/ADT/StringExtras.h"
Hal Finkelee90a222014-09-26 05:04:30 +000037#include "llvm/Support/MathExtras.h"
Eugene Zelenko1ced5092016-02-12 22:53:10 +000038
Chris Lattner2c6fcf52008-06-26 18:38:35 +000039using namespace clang;
John McCallb45a1e72010-08-26 02:13:20 +000040using namespace sema;
Chris Lattner2c6fcf52008-06-26 18:38:35 +000041
Aaron Ballmandf8fe4c2013-11-24 21:35:16 +000042namespace AttributeLangSupport {
NAKAMURA Takumi01d27f92013-11-25 00:52:29 +000043 enum LANG {
Aaron Ballmandf8fe4c2013-11-24 21:35:16 +000044 C,
45 Cpp,
46 ObjC
47 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +000048} // end namespace AttributeLangSupport
Aaron Ballmandf8fe4c2013-11-24 21:35:16 +000049
Chris Lattner58418ff2008-06-29 00:16:31 +000050//===----------------------------------------------------------------------===//
51// Helper functions
52//===----------------------------------------------------------------------===//
53
Ted Kremenek527042b2009-08-14 20:49:40 +000054/// isFunctionOrMethod - Return true if the given decl has function
Daniel Dunbar70e3eba2008-10-19 02:04:16 +000055/// type (function or function-typed variable) or an Objective-C
56/// method.
Chandler Carruthff4c4f02011-07-01 23:49:12 +000057static bool isFunctionOrMethod(const Decl *D) {
Craig Topperc3ec1492014-05-26 06:22:03 +000058 return (D->getFunctionType() != nullptr) || isa<ObjCMethodDecl>(D);
Fariborz Jahanian4447e172009-05-15 23:15:03 +000059}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000060
David Majnemer06864812015-04-07 06:01:53 +000061/// \brief Return true if the given decl has function type (function or
62/// function-typed variable) or an Objective-C method or a block.
63static bool isFunctionOrMethodOrBlock(const Decl *D) {
64 return isFunctionOrMethod(D) || isa<BlockDecl>(D);
65}
Fariborz Jahanian4447e172009-05-15 23:15:03 +000066
John McCall3882ace2011-01-05 12:14:39 +000067/// Return true if the given decl has a declarator that should have
68/// been processed by Sema::GetTypeForDeclarator.
Chandler Carruthff4c4f02011-07-01 23:49:12 +000069static bool hasDeclarator(const Decl *D) {
John McCall31168b02011-06-15 23:02:42 +000070 // In some sense, TypedefDecl really *ought* to be a DeclaratorDecl.
Chandler Carruthff4c4f02011-07-01 23:49:12 +000071 return isa<DeclaratorDecl>(D) || isa<BlockDecl>(D) || isa<TypedefNameDecl>(D) ||
72 isa<ObjCPropertyDecl>(D);
John McCall3882ace2011-01-05 12:14:39 +000073}
74
Daniel Dunbar70e3eba2008-10-19 02:04:16 +000075/// hasFunctionProto - Return true if the given decl has a argument
76/// information. This decl should have already passed
Fariborz Jahanian4447e172009-05-15 23:15:03 +000077/// isFunctionOrMethod or isFunctionOrMethodOrBlock.
Chandler Carruthff4c4f02011-07-01 23:49:12 +000078static bool hasFunctionProto(const Decl *D) {
Aaron Ballman12b9f652014-01-16 13:55:42 +000079 if (const FunctionType *FnTy = D->getFunctionType())
Douglas Gregordeaad8c2009-02-26 23:50:07 +000080 return isa<FunctionProtoType>(FnTy);
Aaron Ballman12b9f652014-01-16 13:55:42 +000081 return isa<ObjCMethodDecl>(D) || isa<BlockDecl>(D);
Daniel Dunbar70e3eba2008-10-19 02:04:16 +000082}
83
Alp Toker601b22c2014-01-21 23:35:24 +000084/// getFunctionOrMethodNumParams - Return number of function or method
85/// parameters. It is an error to call this on a K&R function (use
Daniel Dunbar70e3eba2008-10-19 02:04:16 +000086/// hasFunctionProto first).
Alp Toker601b22c2014-01-21 23:35:24 +000087static unsigned getFunctionOrMethodNumParams(const Decl *D) {
Aaron Ballman12b9f652014-01-16 13:55:42 +000088 if (const FunctionType *FnTy = D->getFunctionType())
Alp Toker9cacbab2014-01-20 20:26:09 +000089 return cast<FunctionProtoType>(FnTy)->getNumParams();
Chandler Carruthff4c4f02011-07-01 23:49:12 +000090 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
Fariborz Jahanian960910a2009-05-19 17:08:59 +000091 return BD->getNumParams();
Chandler Carruthff4c4f02011-07-01 23:49:12 +000092 return cast<ObjCMethodDecl>(D)->param_size();
Daniel Dunbarc136e0c2008-09-26 04:12:28 +000093}
94
Alp Toker601b22c2014-01-21 23:35:24 +000095static QualType getFunctionOrMethodParamType(const Decl *D, unsigned Idx) {
Aaron Ballman12b9f652014-01-16 13:55:42 +000096 if (const FunctionType *FnTy = D->getFunctionType())
Alp Toker9cacbab2014-01-20 20:26:09 +000097 return cast<FunctionProtoType>(FnTy)->getParamType(Idx);
Chandler Carruthff4c4f02011-07-01 23:49:12 +000098 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
Fariborz Jahanian960910a2009-05-19 17:08:59 +000099 return BD->getParamDecl(Idx)->getType();
Mike Stumpd3bb5572009-07-24 19:02:52 +0000100
Alp Toker03376dc2014-07-07 09:02:20 +0000101 return cast<ObjCMethodDecl>(D)->parameters()[Idx]->getType();
Daniel Dunbarc136e0c2008-09-26 04:12:28 +0000102}
103
Aaron Ballman4bfa0de2014-08-01 12:58:11 +0000104static SourceRange getFunctionOrMethodParamRange(const Decl *D, unsigned Idx) {
105 if (const auto *FD = dyn_cast<FunctionDecl>(D))
106 return FD->getParamDecl(Idx)->getSourceRange();
Aaron Ballmane13d0092014-08-01 17:02:34 +0000107 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
Aaron Ballman4bfa0de2014-08-01 12:58:11 +0000108 return MD->parameters()[Idx]->getSourceRange();
Aaron Ballmane13d0092014-08-01 17:02:34 +0000109 if (const auto *BD = dyn_cast<BlockDecl>(D))
Aaron Ballman4bfa0de2014-08-01 12:58:11 +0000110 return BD->getParamDecl(Idx)->getSourceRange();
111 return SourceRange();
112}
113
Chandler Carruthff4c4f02011-07-01 23:49:12 +0000114static QualType getFunctionOrMethodResultType(const Decl *D) {
Aaron Ballman12b9f652014-01-16 13:55:42 +0000115 if (const FunctionType *FnTy = D->getFunctionType())
Aaron Ballman6288d062014-07-11 16:31:29 +0000116 return cast<FunctionType>(FnTy)->getReturnType();
Alp Toker314cc812014-01-25 16:55:45 +0000117 return cast<ObjCMethodDecl>(D)->getReturnType();
Fariborz Jahanianf1c25022009-05-20 17:41:43 +0000118}
119
Aaron Ballman4bfa0de2014-08-01 12:58:11 +0000120static SourceRange getFunctionOrMethodResultSourceRange(const Decl *D) {
121 if (const auto *FD = dyn_cast<FunctionDecl>(D))
122 return FD->getReturnTypeSourceRange();
Aaron Ballmane13d0092014-08-01 17:02:34 +0000123 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
Aaron Ballman4bfa0de2014-08-01 12:58:11 +0000124 return MD->getReturnTypeSourceRange();
125 return SourceRange();
126}
127
Chandler Carruthff4c4f02011-07-01 23:49:12 +0000128static bool isFunctionOrMethodVariadic(const Decl *D) {
Aaron Ballman12b9f652014-01-16 13:55:42 +0000129 if (const FunctionType *FnTy = D->getFunctionType()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000130 const FunctionProtoType *proto = cast<FunctionProtoType>(FnTy);
Daniel Dunbarc136e0c2008-09-26 04:12:28 +0000131 return proto->isVariadic();
Daniel Dunbarc136e0c2008-09-26 04:12:28 +0000132 }
Aaron Ballmane13d0092014-08-01 17:02:34 +0000133 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
134 return BD->isVariadic();
135
136 return cast<ObjCMethodDecl>(D)->isVariadic();
Daniel Dunbarc136e0c2008-09-26 04:12:28 +0000137}
138
Chandler Carruthff4c4f02011-07-01 23:49:12 +0000139static bool isInstanceMethod(const Decl *D) {
140 if (const CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D))
Chandler Carruth743682b2010-11-16 08:35:43 +0000141 return MethodDecl->isInstance();
142 return false;
143}
144
Chris Lattner2c6fcf52008-06-26 18:38:35 +0000145static inline bool isNSStringType(QualType T, ASTContext &Ctx) {
John McCall9dd450b2009-09-21 23:43:11 +0000146 const ObjCObjectPointerType *PT = T->getAs<ObjCObjectPointerType>();
Chris Lattner574dee62008-07-26 22:17:49 +0000147 if (!PT)
Chris Lattner2c6fcf52008-06-26 18:38:35 +0000148 return false;
Mike Stumpd3bb5572009-07-24 19:02:52 +0000149
John McCall96fa4842010-05-17 21:00:27 +0000150 ObjCInterfaceDecl *Cls = PT->getObjectType()->getInterface();
151 if (!Cls)
Chris Lattner2c6fcf52008-06-26 18:38:35 +0000152 return false;
Mike Stumpd3bb5572009-07-24 19:02:52 +0000153
John McCall96fa4842010-05-17 21:00:27 +0000154 IdentifierInfo* ClsName = Cls->getIdentifier();
Mike Stumpd3bb5572009-07-24 19:02:52 +0000155
Chris Lattner2c6fcf52008-06-26 18:38:35 +0000156 // FIXME: Should we walk the chain of classes?
157 return ClsName == &Ctx.Idents.get("NSString") ||
158 ClsName == &Ctx.Idents.get("NSMutableString");
159}
160
Daniel Dunbar980c6692008-09-26 03:32:58 +0000161static inline bool isCFStringType(QualType T, ASTContext &Ctx) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000162 const PointerType *PT = T->getAs<PointerType>();
Daniel Dunbar980c6692008-09-26 03:32:58 +0000163 if (!PT)
164 return false;
165
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000166 const RecordType *RT = PT->getPointeeType()->getAs<RecordType>();
Daniel Dunbar980c6692008-09-26 03:32:58 +0000167 if (!RT)
168 return false;
Mike Stumpd3bb5572009-07-24 19:02:52 +0000169
Daniel Dunbar980c6692008-09-26 03:32:58 +0000170 const RecordDecl *RD = RT->getDecl();
Abramo Bagnara6150c882010-05-11 21:36:43 +0000171 if (RD->getTagKind() != TTK_Struct)
Daniel Dunbar980c6692008-09-26 03:32:58 +0000172 return false;
173
174 return RD->getIdentifier() == &Ctx.Idents.get("__CFString");
175}
176
Richard Smithb87c4652013-10-31 21:23:20 +0000177static unsigned getNumAttributeArgs(const AttributeList &Attr) {
178 // FIXME: Include the type in the argument list.
179 return Attr.getNumArgs() + Attr.hasParsedType();
180}
181
Aaron Ballman8ed8dbd2014-07-31 16:37:04 +0000182template <typename Compare>
183static bool checkAttributeNumArgsImpl(Sema &S, const AttributeList &Attr,
184 unsigned Num, unsigned Diag,
185 Compare Comp) {
186 if (Comp(getNumAttributeArgs(Attr), Num)) {
187 S.Diag(Attr.getLoc(), Diag) << Attr.getName() << Num;
Chandler Carruthfcc48d92011-07-11 23:30:35 +0000188 return false;
189 }
190
191 return true;
192}
193
Aaron Ballman8ed8dbd2014-07-31 16:37:04 +0000194/// \brief Check if the attribute has exactly as many args as Num. May
195/// output an error.
196static bool checkAttributeNumArgs(Sema &S, const AttributeList &Attr,
197 unsigned Num) {
198 return checkAttributeNumArgsImpl(S, Attr, Num,
199 diag::err_attribute_wrong_number_arguments,
200 std::not_equal_to<unsigned>());
201}
202
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000203/// \brief Check if the attribute has at least as many args as Num. May
204/// output an error.
205static bool checkAttributeAtLeastNumArgs(Sema &S, const AttributeList &Attr,
Richard Smithb87c4652013-10-31 21:23:20 +0000206 unsigned Num) {
Aaron Ballman8ed8dbd2014-07-31 16:37:04 +0000207 return checkAttributeNumArgsImpl(S, Attr, Num,
208 diag::err_attribute_too_few_arguments,
209 std::less<unsigned>());
210}
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000211
Aaron Ballman8ed8dbd2014-07-31 16:37:04 +0000212/// \brief Check if the attribute has at most as many args as Num. May
213/// output an error.
214static bool checkAttributeAtMostNumArgs(Sema &S, const AttributeList &Attr,
215 unsigned Num) {
216 return checkAttributeNumArgsImpl(S, Attr, Num,
217 diag::err_attribute_too_many_arguments,
218 std::greater<unsigned>());
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000219}
220
Erich Keane623efd82017-03-30 21:48:55 +0000221/// \brief A helper function to provide Attribute Location for the Attr types
222/// AND the AttributeList.
223template <typename AttrInfo>
224static typename std::enable_if<std::is_base_of<clang::Attr, AttrInfo>::value,
225 SourceLocation>::type
226getAttrLoc(const AttrInfo &Attr) {
227 return Attr.getLocation();
228}
229static SourceLocation getAttrLoc(const clang::AttributeList &Attr) {
230 return Attr.getLoc();
231}
232
233/// \brief A helper function to provide Attribute Name for the Attr types
234/// AND the AttributeList.
235template <typename AttrInfo>
236static typename std::enable_if<std::is_base_of<clang::Attr, AttrInfo>::value,
237 const AttrInfo *>::type
238getAttrName(const AttrInfo &Attr) {
239 return &Attr;
240}
Benjamin Kramer674d5792017-05-26 20:08:24 +0000241static const IdentifierInfo *getAttrName(const clang::AttributeList &Attr) {
Erich Keane623efd82017-03-30 21:48:55 +0000242 return Attr.getName();
243}
244
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +0000245/// \brief If Expr is a valid integer constant, get the value of the integer
246/// expression and return success or failure. May output an error.
Erich Keane623efd82017-03-30 21:48:55 +0000247template<typename AttrInfo>
248static bool checkUInt32Argument(Sema &S, const AttrInfo& Attr, const Expr *Expr,
249 uint32_t &Val, unsigned Idx = UINT_MAX) {
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +0000250 llvm::APSInt I(32);
251 if (Expr->isTypeDependent() || Expr->isValueDependent() ||
252 !Expr->isIntegerConstantExpr(I, S.Context)) {
253 if (Idx != UINT_MAX)
Erich Keane623efd82017-03-30 21:48:55 +0000254 S.Diag(getAttrLoc(Attr), diag::err_attribute_argument_n_type)
255 << getAttrName(Attr) << Idx << AANT_ArgumentIntegerConstant
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +0000256 << Expr->getSourceRange();
257 else
Erich Keane623efd82017-03-30 21:48:55 +0000258 S.Diag(getAttrLoc(Attr), diag::err_attribute_argument_type)
259 << getAttrName(Attr) << AANT_ArgumentIntegerConstant
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +0000260 << Expr->getSourceRange();
261 return false;
262 }
Aaron Ballmanadfdde52014-07-22 14:09:34 +0000263
264 if (!I.isIntN(32)) {
Aaron Ballman31f42312014-07-24 14:51:23 +0000265 S.Diag(Expr->getExprLoc(), diag::err_ice_too_large)
266 << I.toString(10, false) << 32 << /* Unsigned */ 1;
Aaron Ballmanadfdde52014-07-22 14:09:34 +0000267 return false;
268 }
269
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +0000270 Val = (uint32_t)I.getZExtValue();
271 return true;
272}
273
George Burgess IVe3763372016-12-22 02:50:20 +0000274/// \brief Wrapper around checkUInt32Argument, with an extra check to be sure
275/// that the result will fit into a regular (signed) int. All args have the same
276/// purpose as they do in checkUInt32Argument.
Erich Keane623efd82017-03-30 21:48:55 +0000277template<typename AttrInfo>
278static bool checkPositiveIntArgument(Sema &S, const AttrInfo& Attr, const Expr *Expr,
279 int &Val, unsigned Idx = UINT_MAX) {
George Burgess IVe3763372016-12-22 02:50:20 +0000280 uint32_t UVal;
281 if (!checkUInt32Argument(S, Attr, Expr, UVal, Idx))
282 return false;
283
George Burgess IVa8049572016-12-22 19:00:31 +0000284 if (UVal > (uint32_t)std::numeric_limits<int>::max()) {
George Burgess IVe3763372016-12-22 02:50:20 +0000285 llvm::APSInt I(32); // for toString
286 I = UVal;
287 S.Diag(Expr->getExprLoc(), diag::err_ice_too_large)
288 << I.toString(10, false) << 32 << /* Unsigned */ 0;
289 return false;
290 }
291
292 Val = UVal;
293 return true;
294}
295
Aaron Ballmanfb763042013-12-02 18:05:46 +0000296/// \brief Diagnose mutually exclusive attributes when present on a given
297/// declaration. Returns true if diagnosed.
298template <typename AttrTy>
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +0000299static bool checkAttrMutualExclusion(Sema &S, Decl *D, SourceRange Range,
300 IdentifierInfo *Ident) {
Aaron Ballman2cfbc002014-01-03 16:23:46 +0000301 if (AttrTy *A = D->getAttr<AttrTy>()) {
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +0000302 S.Diag(Range.getBegin(), diag::err_attributes_are_not_compatible) << Ident
303 << A;
304 S.Diag(A->getLocation(), diag::note_conflicting_attribute);
Aaron Ballmanfb763042013-12-02 18:05:46 +0000305 return true;
306 }
307 return false;
308}
309
Alp Toker601b22c2014-01-21 23:35:24 +0000310/// \brief Check if IdxExpr is a valid parameter index for a function or
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000311/// instance method D. May output an error.
312///
313/// \returns true if IdxExpr is a valid index.
Erich Keane623efd82017-03-30 21:48:55 +0000314template <typename AttrInfo>
315static bool checkFunctionOrMethodParameterIndex(
Dean Michael Berris7456a282017-06-16 03:22:09 +0000316 Sema &S, const Decl *D, const AttrInfo &Attr, unsigned AttrArgNum,
317 const Expr *IdxExpr, uint64_t &Idx, bool AllowImplicitThis = false) {
David Majnemer06864812015-04-07 06:01:53 +0000318 assert(isFunctionOrMethodOrBlock(D));
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000319
320 // In C++ the implicit 'this' function parameter also counts.
321 // Parameters are counted from one.
Aaron Ballmanbe50eb82013-07-30 00:48:57 +0000322 bool HP = hasFunctionProto(D);
323 bool HasImplicitThisParam = isInstanceMethod(D);
324 bool IV = HP && isFunctionOrMethodVariadic(D);
Alp Toker601b22c2014-01-21 23:35:24 +0000325 unsigned NumParams =
326 (HP ? getFunctionOrMethodNumParams(D) : 0) + HasImplicitThisParam;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000327
328 llvm::APSInt IdxInt;
329 if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent() ||
330 !IdxExpr->isIntegerConstantExpr(IdxInt, S.Context)) {
Erich Keane623efd82017-03-30 21:48:55 +0000331 S.Diag(getAttrLoc(Attr), diag::err_attribute_argument_n_type)
332 << getAttrName(Attr) << AttrArgNum << AANT_ArgumentIntegerConstant
Aaron Ballmanfaed0fa2013-12-26 16:30:30 +0000333 << IdxExpr->getSourceRange();
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000334 return false;
335 }
336
337 Idx = IdxInt.getLimitedValue();
Alp Toker601b22c2014-01-21 23:35:24 +0000338 if (Idx < 1 || (!IV && Idx > NumParams)) {
Erich Keane623efd82017-03-30 21:48:55 +0000339 S.Diag(getAttrLoc(Attr), diag::err_attribute_argument_out_of_bounds)
340 << getAttrName(Attr) << AttrArgNum << IdxExpr->getSourceRange();
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000341 return false;
342 }
343 Idx--; // Convert to zero-based.
Dean Michael Berris7456a282017-06-16 03:22:09 +0000344 if (HasImplicitThisParam && !AllowImplicitThis) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000345 if (Idx == 0) {
Erich Keane623efd82017-03-30 21:48:55 +0000346 S.Diag(getAttrLoc(Attr),
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000347 diag::err_attribute_invalid_implicit_this_argument)
Erich Keane623efd82017-03-30 21:48:55 +0000348 << getAttrName(Attr) << IdxExpr->getSourceRange();
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000349 return false;
350 }
351 --Idx;
352 }
353
354 return true;
355}
356
Aaron Ballman3b1dde62013-09-13 19:35:18 +0000357/// \brief Check if the argument \p ArgNum of \p Attr is a ASCII string literal.
358/// If not emit an error and return false. If the argument is an identifier it
359/// will emit an error with a fixit hint and treat it as if it was a string
360/// literal.
Tim Northover6a6b63b2013-10-01 14:34:18 +0000361bool Sema::checkStringLiteralArgumentAttr(const AttributeList &Attr,
362 unsigned ArgNum, StringRef &Str,
Tim Northovera484bc02013-10-01 14:34:25 +0000363 SourceLocation *ArgLocation) {
Aaron Ballman3b1dde62013-09-13 19:35:18 +0000364 // Look for identifiers. If we have one emit a hint to fix it to a literal.
365 if (Attr.isArgIdent(ArgNum)) {
366 IdentifierLoc *Loc = Attr.getArgAsIdent(ArgNum);
Tim Northover6a6b63b2013-10-01 14:34:18 +0000367 Diag(Loc->Loc, diag::err_attribute_argument_type)
Aaron Ballman3b1dde62013-09-13 19:35:18 +0000368 << Attr.getName() << AANT_ArgumentString
369 << FixItHint::CreateInsertion(Loc->Loc, "\"")
Craig Topper07fa1762015-11-15 02:31:46 +0000370 << FixItHint::CreateInsertion(getLocForEndOfToken(Loc->Loc), "\"");
Aaron Ballman3b1dde62013-09-13 19:35:18 +0000371 Str = Loc->Ident->getName();
372 if (ArgLocation)
373 *ArgLocation = Loc->Loc;
374 return true;
375 }
376
377 // Now check for an actual string literal.
378 Expr *ArgExpr = Attr.getArgAsExpr(ArgNum);
379 StringLiteral *Literal = dyn_cast<StringLiteral>(ArgExpr->IgnoreParenCasts());
380 if (ArgLocation)
381 *ArgLocation = ArgExpr->getLocStart();
382
383 if (!Literal || !Literal->isAscii()) {
Tim Northover6a6b63b2013-10-01 14:34:18 +0000384 Diag(ArgExpr->getLocStart(), diag::err_attribute_argument_type)
Aaron Ballman3b1dde62013-09-13 19:35:18 +0000385 << Attr.getName() << AANT_ArgumentString;
386 return false;
387 }
388
389 Str = Literal->getString();
390 return true;
391}
392
Aaron Ballman6f9165a2013-11-27 15:24:06 +0000393/// \brief Applies the given attribute to the Decl without performing any
394/// additional semantic checking.
395template <typename AttrType>
396static void handleSimpleAttribute(Sema &S, Decl *D,
397 const AttributeList &Attr) {
398 D->addAttr(::new (S.Context) AttrType(Attr.getRange(), S.Context,
399 Attr.getAttributeSpellingListIndex()));
400}
401
Justin Lebar3eaaf862016-01-13 01:07:35 +0000402template <typename AttrType>
403static void handleSimpleAttributeWithExclusions(Sema &S, Decl *D,
404 const AttributeList &Attr) {
405 handleSimpleAttribute<AttrType>(S, D, Attr);
406}
407
408/// \brief Applies the given attribute to the Decl so long as the Decl doesn't
409/// already have one of the given incompatible attributes.
410template <typename AttrType, typename IncompatibleAttrType,
411 typename... IncompatibleAttrTypes>
412static void handleSimpleAttributeWithExclusions(Sema &S, Decl *D,
413 const AttributeList &Attr) {
414 if (checkAttrMutualExclusion<IncompatibleAttrType>(S, D, Attr.getRange(),
415 Attr.getName()))
416 return;
417 handleSimpleAttributeWithExclusions<AttrType, IncompatibleAttrTypes...>(S, D,
418 Attr);
419}
420
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000421/// \brief Check if the passed-in expression is of type int or bool.
422static bool isIntOrBool(Expr *Exp) {
423 QualType QT = Exp->getType();
424 return QT->isBooleanType() || QT->isIntegerType();
425}
426
DeLesley Hutchinse09be232012-04-23 18:39:55 +0000427
428// Check to see if the type is a smart pointer of some kind. We assume
429// it's a smart pointer if it defines both operator-> and operator*.
DeLesley Hutchins90ff4682012-05-02 22:18:42 +0000430static bool threadSafetyCheckIsSmartPointer(Sema &S, const RecordType* RT) {
Richard Smithcf4bdde2015-02-21 02:45:19 +0000431 DeclContextLookupResult Res1 = RT->getDecl()->lookup(
432 S.Context.DeclarationNames.getCXXOperatorName(OO_Star));
David Blaikieff7d47a2012-12-19 00:45:41 +0000433 if (Res1.empty())
DeLesley Hutchins90ff4682012-05-02 22:18:42 +0000434 return false;
DeLesley Hutchinse09be232012-04-23 18:39:55 +0000435
Richard Smithcf4bdde2015-02-21 02:45:19 +0000436 DeclContextLookupResult Res2 = RT->getDecl()->lookup(
437 S.Context.DeclarationNames.getCXXOperatorName(OO_Arrow));
David Blaikieff7d47a2012-12-19 00:45:41 +0000438 if (Res2.empty())
DeLesley Hutchins90ff4682012-05-02 22:18:42 +0000439 return false;
440
441 return true;
DeLesley Hutchinse09be232012-04-23 18:39:55 +0000442}
443
Caitlin Sadowskiaac4d212011-07-28 17:21:07 +0000444/// \brief Check if passed in Decl is a pointer type.
445/// Note that this function may produce an error message.
446/// \return true if the Decl is a pointer type; false otherwise
DeLesley Hutchins8d11c792012-04-19 16:10:44 +0000447static bool threadSafetyCheckIsPointer(Sema &S, const Decl *D,
448 const AttributeList &Attr) {
Aaron Ballman553e6812013-12-26 14:54:11 +0000449 const ValueDecl *vd = cast<ValueDecl>(D);
450 QualType QT = vd->getType();
451 if (QT->isAnyPointerType())
452 return true;
453
454 if (const RecordType *RT = QT->getAs<RecordType>()) {
455 // If it's an incomplete type, it could be a smart pointer; skip it.
456 // (We don't want to force template instantiation if we can avoid it,
457 // since that would alter the order in which templates are instantiated.)
458 if (RT->isIncompleteType())
Caitlin Sadowskiaac4d212011-07-28 17:21:07 +0000459 return true;
DeLesley Hutchinse09be232012-04-23 18:39:55 +0000460
Aaron Ballman553e6812013-12-26 14:54:11 +0000461 if (threadSafetyCheckIsSmartPointer(S, RT))
462 return true;
Caitlin Sadowskiaac4d212011-07-28 17:21:07 +0000463 }
Aaron Ballman553e6812013-12-26 14:54:11 +0000464
465 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_decl_not_pointer)
Aaron Ballman68289452013-12-26 15:06:01 +0000466 << Attr.getName() << QT;
Caitlin Sadowskiaac4d212011-07-28 17:21:07 +0000467 return false;
468}
469
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000470/// \brief Checks that the passed in QualType either is of RecordType or points
471/// to RecordType. Returns the relevant RecordType, null if it does not exit.
Benjamin Kramer56b675f2011-08-19 04:18:11 +0000472static const RecordType *getRecordType(QualType QT) {
473 if (const RecordType *RT = QT->getAs<RecordType>())
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000474 return RT;
Benjamin Kramer56b675f2011-08-19 04:18:11 +0000475
476 // Now check if we point to record type.
477 if (const PointerType *PT = QT->getAs<PointerType>())
478 return PT->getPointeeType()->getAs<RecordType>();
479
Craig Topperc3ec1492014-05-26 06:22:03 +0000480 return nullptr;
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000481}
482
Josh Gao55afa752017-08-11 07:54:35 +0000483static bool checkRecordTypeForCapability(Sema &S, QualType Ty) {
DeLesley Hutchins481d5ab2012-04-06 20:02:30 +0000484 const RecordType *RT = getRecordType(Ty);
Michael Hana9171bc2012-08-03 17:40:43 +0000485
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000486 if (!RT)
487 return false;
DeLesley Hutchins90ff4682012-05-02 22:18:42 +0000488
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000489 // Don't check for the capability if the class hasn't been defined yet.
DeLesley Hutchins3509f292012-02-16 17:15:51 +0000490 if (RT->isIncompleteType())
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000491 return true;
DeLesley Hutchins90ff4682012-05-02 22:18:42 +0000492
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000493 // Allow smart pointers to be used as capability objects.
DeLesley Hutchins90ff4682012-05-02 22:18:42 +0000494 // FIXME -- Check the type that the smart pointer points to.
495 if (threadSafetyCheckIsSmartPointer(S, RT))
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000496 return true;
DeLesley Hutchins90ff4682012-05-02 22:18:42 +0000497
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000498 // Check if the record itself has a capability.
DeLesley Hutchins5ff430c2012-05-04 16:28:38 +0000499 RecordDecl *RD = RT->getDecl();
Josh Gao55afa752017-08-11 07:54:35 +0000500 if (RD->hasAttr<CapabilityAttr>())
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000501 return true;
DeLesley Hutchins5ff430c2012-05-04 16:28:38 +0000502
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000503 // Else check if any base classes have a capability.
DeLesley Hutchins5ff430c2012-05-04 16:28:38 +0000504 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
505 CXXBasePaths BPaths(false, false);
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +0000506 if (CRD->lookupInBases([](const CXXBaseSpecifier *BS, CXXBasePath &) {
507 const auto *Type = BS->getType()->getAs<RecordType>();
Josh Gao55afa752017-08-11 07:54:35 +0000508 return Type->getDecl()->hasAttr<CapabilityAttr>();
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +0000509 }, BPaths))
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000510 return true;
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000511 }
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000512 return false;
513}
514
Josh Gao55afa752017-08-11 07:54:35 +0000515static bool checkTypedefTypeForCapability(QualType Ty) {
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000516 const auto *TD = Ty->getAs<TypedefType>();
517 if (!TD)
518 return false;
519
520 TypedefNameDecl *TN = TD->getDecl();
521 if (!TN)
522 return false;
523
Josh Gao55afa752017-08-11 07:54:35 +0000524 return TN->hasAttr<CapabilityAttr>();
Aaron Ballman76050722014-04-04 15:13:57 +0000525}
526
Josh Gaob40c1772017-08-08 19:44:35 +0000527static bool typeHasCapability(Sema &S, QualType Ty) {
Josh Gao55afa752017-08-11 07:54:35 +0000528 if (checkTypedefTypeForCapability(Ty))
529 return true;
Josh Gaob40c1772017-08-08 19:44:35 +0000530
Josh Gao55afa752017-08-11 07:54:35 +0000531 if (checkRecordTypeForCapability(S, Ty))
532 return true;
533
534 return false;
Josh Gaob40c1772017-08-08 19:44:35 +0000535}
536
Aaron Ballman76050722014-04-04 15:13:57 +0000537static bool isCapabilityExpr(Sema &S, const Expr *Ex) {
538 // Capability expressions are simple expressions involving the boolean logic
539 // operators &&, || or !, a simple DeclRefExpr, CastExpr or a ParenExpr. Once
540 // a DeclRefExpr is found, its type should be checked to determine whether it
541 // is a capability or not.
542
543 if (const auto *E = dyn_cast<DeclRefExpr>(Ex))
544 return typeHasCapability(S, E->getType());
545 else if (const auto *E = dyn_cast<CastExpr>(Ex))
546 return isCapabilityExpr(S, E->getSubExpr());
547 else if (const auto *E = dyn_cast<ParenExpr>(Ex))
548 return isCapabilityExpr(S, E->getSubExpr());
549 else if (const auto *E = dyn_cast<UnaryOperator>(Ex)) {
550 if (E->getOpcode() == UO_LNot)
551 return isCapabilityExpr(S, E->getSubExpr());
552 return false;
553 } else if (const auto *E = dyn_cast<BinaryOperator>(Ex)) {
554 if (E->getOpcode() == BO_LAnd || E->getOpcode() == BO_LOr)
555 return isCapabilityExpr(S, E->getLHS()) &&
556 isCapabilityExpr(S, E->getRHS());
557 return false;
558 }
559
560 return false;
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000561}
562
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000563/// \brief Checks that all attribute arguments, starting from Sidx, resolve to
564/// a capability object.
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000565/// \param Sidx The attribute argument index to start checking with.
566/// \param ParamIdxOk Whether an argument can be indexing into a function
567/// parameter list.
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000568static void checkAttrArgsAreCapabilityObjs(Sema &S, Decl *D,
569 const AttributeList &Attr,
570 SmallVectorImpl<Expr *> &Args,
571 int Sidx = 0,
572 bool ParamIdxOk = false) {
573 for (unsigned Idx = Sidx; Idx < Attr.getNumArgs(); ++Idx) {
Aaron Ballman00e99962013-08-31 01:11:41 +0000574 Expr *ArgExp = Attr.getArgAsExpr(Idx);
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000575
Caitlin Sadowski990d5712011-09-08 17:42:31 +0000576 if (ArgExp->isTypeDependent()) {
DeLesley Hutchins8d11c792012-04-19 16:10:44 +0000577 // FIXME -- need to check this again on template instantiation
Caitlin Sadowski990d5712011-09-08 17:42:31 +0000578 Args.push_back(ArgExp);
579 continue;
580 }
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000581
DeLesley Hutchins70b5e8e2012-04-23 16:45:01 +0000582 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(ArgExp)) {
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000583 if (StrLit->getLength() == 0 ||
Benjamin Kramerca9fe142013-09-13 16:30:12 +0000584 (StrLit->isAscii() && StrLit->getString() == StringRef("*"))) {
DeLesley Hutchins3c3d57b2012-08-31 21:57:32 +0000585 // Pass empty strings to the analyzer without warnings.
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000586 // Treat "*" as the universal lock.
DeLesley Hutchins3c3d57b2012-08-31 21:57:32 +0000587 Args.push_back(ArgExp);
DeLesley Hutchins70b5e8e2012-04-23 16:45:01 +0000588 continue;
DeLesley Hutchins3c3d57b2012-08-31 21:57:32 +0000589 }
DeLesley Hutchins70b5e8e2012-04-23 16:45:01 +0000590
DeLesley Hutchins8d11c792012-04-19 16:10:44 +0000591 // We allow constant strings to be used as a placeholder for expressions
592 // that are not valid C++ syntax, but warn that they are ignored.
593 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_ignored) <<
594 Attr.getName();
DeLesley Hutchins3c3d57b2012-08-31 21:57:32 +0000595 Args.push_back(ArgExp);
DeLesley Hutchins8d11c792012-04-19 16:10:44 +0000596 continue;
597 }
598
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000599 QualType ArgTy = ArgExp->getType();
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000600
DeLesley Hutchins70b5e8e2012-04-23 16:45:01 +0000601 // A pointer to member expression of the form &MyClass::mu is treated
602 // specially -- we need to look at the type of the member.
603 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(ArgExp))
604 if (UOp->getOpcode() == UO_AddrOf)
605 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(UOp->getSubExpr()))
606 if (DRE->getDecl()->isCXXInstanceMember())
607 ArgTy = DRE->getDecl()->getType();
608
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000609 // First see if we can just cast to record type, or pointer to record type.
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000610 const RecordType *RT = getRecordType(ArgTy);
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000611
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000612 // Now check if we index into a record type function param.
Josh Gao55afa752017-08-11 07:54:35 +0000613 if(!RT && ParamIdxOk) {
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000614 FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000615 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(ArgExp);
Josh Gao55afa752017-08-11 07:54:35 +0000616 if(FD && IL) {
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000617 unsigned int NumParams = FD->getNumParams();
618 llvm::APInt ArgValue = IL->getValue();
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000619 uint64_t ParamIdxFromOne = ArgValue.getZExtValue();
620 uint64_t ParamIdxFromZero = ParamIdxFromOne - 1;
Josh Gao55afa752017-08-11 07:54:35 +0000621 if(!ArgValue.isStrictlyPositive() || ParamIdxFromOne > NumParams) {
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000622 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_range)
623 << Attr.getName() << Idx + 1 << NumParams;
DeLesley Hutchins8d11c792012-04-19 16:10:44 +0000624 continue;
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000625 }
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000626 ArgTy = FD->getParamDecl(ParamIdxFromZero)->getType();
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000627 }
628 }
629
Aaron Ballman76050722014-04-04 15:13:57 +0000630 // If the type does not have a capability, see if the components of the
631 // expression have capabilities. This allows for writing C code where the
632 // capability may be on the type, and the expression is a capability
633 // boolean logic expression. Eg) requires_capability(A || B && !C)
634 if (!typeHasCapability(S, ArgTy) && !isCapabilityExpr(S, ArgExp))
635 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_argument_not_lockable)
636 << Attr.getName() << ArgTy;
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000637
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000638 Args.push_back(ArgExp);
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000639 }
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000640}
641
Chris Lattner58418ff2008-06-29 00:16:31 +0000642//===----------------------------------------------------------------------===//
Chris Lattner58418ff2008-06-29 00:16:31 +0000643// Attribute Implementations
644//===----------------------------------------------------------------------===//
645
Michael Hana9171bc2012-08-03 17:40:43 +0000646static void handlePtGuardedVarAttr(Sema &S, Decl *D,
Michael Han99315932013-01-24 16:46:58 +0000647 const AttributeList &Attr) {
Michael Han3be3b442012-07-23 18:48:41 +0000648 if (!threadSafetyCheckIsPointer(S, D, Attr))
649 return;
650
Michael Han99315932013-01-24 16:46:58 +0000651 D->addAttr(::new (S.Context)
652 PtGuardedVarAttr(Attr.getRange(), S.Context,
653 Attr.getAttributeSpellingListIndex()));
Michael Han3be3b442012-07-23 18:48:41 +0000654}
655
Michael Hana9171bc2012-08-03 17:40:43 +0000656static bool checkGuardedByAttrCommon(Sema &S, Decl *D,
657 const AttributeList &Attr,
Michael Han3be3b442012-07-23 18:48:41 +0000658 Expr* &Arg) {
DeLesley Hutchins8d11c792012-04-19 16:10:44 +0000659 SmallVector<Expr*, 1> Args;
660 // check that all arguments are lockable objects
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000661 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
DeLesley Hutchins8d11c792012-04-19 16:10:44 +0000662 unsigned Size = Args.size();
663 if (Size != 1)
Michael Han3be3b442012-07-23 18:48:41 +0000664 return false;
Michael Hana9171bc2012-08-03 17:40:43 +0000665
Michael Han3be3b442012-07-23 18:48:41 +0000666 Arg = Args[0];
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000667
Michael Han3be3b442012-07-23 18:48:41 +0000668 return true;
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000669}
670
Michael Han3be3b442012-07-23 18:48:41 +0000671static void handleGuardedByAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000672 Expr *Arg = nullptr;
Michael Han3be3b442012-07-23 18:48:41 +0000673 if (!checkGuardedByAttrCommon(S, D, Attr, Arg))
674 return;
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000675
Aaron Ballman36a53502014-01-16 13:03:14 +0000676 D->addAttr(::new (S.Context) GuardedByAttr(Attr.getRange(), S.Context, Arg,
677 Attr.getAttributeSpellingListIndex()));
Michael Han3be3b442012-07-23 18:48:41 +0000678}
679
Michael Hana9171bc2012-08-03 17:40:43 +0000680static void handlePtGuardedByAttr(Sema &S, Decl *D,
Michael Han3be3b442012-07-23 18:48:41 +0000681 const AttributeList &Attr) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000682 Expr *Arg = nullptr;
Michael Han3be3b442012-07-23 18:48:41 +0000683 if (!checkGuardedByAttrCommon(S, D, Attr, Arg))
684 return;
685
686 if (!threadSafetyCheckIsPointer(S, D, Attr))
687 return;
688
689 D->addAttr(::new (S.Context) PtGuardedByAttr(Attr.getRange(),
Aaron Ballman36a53502014-01-16 13:03:14 +0000690 S.Context, Arg,
691 Attr.getAttributeSpellingListIndex()));
Michael Han3be3b442012-07-23 18:48:41 +0000692}
693
Michael Hana9171bc2012-08-03 17:40:43 +0000694static bool checkAcquireOrderAttrCommon(Sema &S, Decl *D,
695 const AttributeList &Attr,
Craig Topper5603df42013-07-05 19:34:19 +0000696 SmallVectorImpl<Expr *> &Args) {
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000697 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
Michael Han3be3b442012-07-23 18:48:41 +0000698 return false;
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000699
DeLesley Hutchins8d11c792012-04-19 16:10:44 +0000700 // Check that this attribute only applies to lockable types.
Aaron Ballmane61b8b82013-12-02 15:02:49 +0000701 QualType QT = cast<ValueDecl>(D)->getType();
DeLesley Hutchins2b504dc2015-09-29 16:24:18 +0000702 if (!QT->isDependentType() && !typeHasCapability(S, QT)) {
703 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_decl_not_lockable)
704 << Attr.getName();
705 return false;
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000706 }
707
DeLesley Hutchins8d11c792012-04-19 16:10:44 +0000708 // Check that all arguments are lockable objects.
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000709 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000710 if (Args.empty())
Michael Han3be3b442012-07-23 18:48:41 +0000711 return false;
Michael Hana9171bc2012-08-03 17:40:43 +0000712
Michael Han3be3b442012-07-23 18:48:41 +0000713 return true;
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000714}
715
Michael Hana9171bc2012-08-03 17:40:43 +0000716static void handleAcquiredAfterAttr(Sema &S, Decl *D,
Michael Han3be3b442012-07-23 18:48:41 +0000717 const AttributeList &Attr) {
718 SmallVector<Expr*, 1> Args;
719 if (!checkAcquireOrderAttrCommon(S, D, Attr, Args))
720 return;
721
722 Expr **StartArg = &Args[0];
Michael Han99315932013-01-24 16:46:58 +0000723 D->addAttr(::new (S.Context)
724 AcquiredAfterAttr(Attr.getRange(), S.Context,
725 StartArg, Args.size(),
726 Attr.getAttributeSpellingListIndex()));
Michael Han3be3b442012-07-23 18:48:41 +0000727}
728
Michael Hana9171bc2012-08-03 17:40:43 +0000729static void handleAcquiredBeforeAttr(Sema &S, Decl *D,
Michael Han3be3b442012-07-23 18:48:41 +0000730 const AttributeList &Attr) {
731 SmallVector<Expr*, 1> Args;
732 if (!checkAcquireOrderAttrCommon(S, D, Attr, Args))
733 return;
734
735 Expr **StartArg = &Args[0];
Michael Han99315932013-01-24 16:46:58 +0000736 D->addAttr(::new (S.Context)
737 AcquiredBeforeAttr(Attr.getRange(), S.Context,
738 StartArg, Args.size(),
739 Attr.getAttributeSpellingListIndex()));
Michael Han3be3b442012-07-23 18:48:41 +0000740}
741
Michael Hana9171bc2012-08-03 17:40:43 +0000742static bool checkLockFunAttrCommon(Sema &S, Decl *D,
743 const AttributeList &Attr,
Craig Topper5603df42013-07-05 19:34:19 +0000744 SmallVectorImpl<Expr *> &Args) {
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000745 // zero or more arguments ok
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000746 // check that all arguments are lockable objects
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000747 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 0, /*ParamIdxOk=*/true);
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000748
Michael Han3be3b442012-07-23 18:48:41 +0000749 return true;
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000750}
751
DeLesley Hutchinsb6824312013-05-17 23:02:59 +0000752static void handleAssertSharedLockAttr(Sema &S, Decl *D,
753 const AttributeList &Attr) {
754 SmallVector<Expr*, 1> Args;
755 if (!checkLockFunAttrCommon(S, D, Attr, Args))
756 return;
757
758 unsigned Size = Args.size();
Craig Topperc3ec1492014-05-26 06:22:03 +0000759 Expr **StartArg = Size == 0 ? nullptr : &Args[0];
DeLesley Hutchinsb6824312013-05-17 23:02:59 +0000760 D->addAttr(::new (S.Context)
761 AssertSharedLockAttr(Attr.getRange(), S.Context, StartArg, Size,
762 Attr.getAttributeSpellingListIndex()));
763}
764
765static void handleAssertExclusiveLockAttr(Sema &S, Decl *D,
766 const AttributeList &Attr) {
767 SmallVector<Expr*, 1> Args;
768 if (!checkLockFunAttrCommon(S, D, Attr, Args))
769 return;
770
771 unsigned Size = Args.size();
Craig Topperc3ec1492014-05-26 06:22:03 +0000772 Expr **StartArg = Size == 0 ? nullptr : &Args[0];
DeLesley Hutchinsb6824312013-05-17 23:02:59 +0000773 D->addAttr(::new (S.Context)
774 AssertExclusiveLockAttr(Attr.getRange(), S.Context,
775 StartArg, Size,
776 Attr.getAttributeSpellingListIndex()));
777}
778
Erich Keane623efd82017-03-30 21:48:55 +0000779/// \brief Checks to be sure that the given parameter number is in bounds, and is
780/// an integral type. Will emit appropriate diagnostics if this returns
George Burgess IVe3763372016-12-22 02:50:20 +0000781/// false.
782///
783/// FuncParamNo is expected to be from the user, so is base-1. AttrArgNo is used
784/// to actually retrieve the argument, so it's base-0.
Erich Keane623efd82017-03-30 21:48:55 +0000785template <typename AttrInfo>
786static bool checkParamIsIntegerType(Sema &S, const FunctionDecl *FD,
787 const AttrInfo &Attr, Expr *AttrArg,
788 unsigned FuncParamNo, unsigned AttrArgNo,
789 bool AllowDependentType = false) {
790 uint64_t Idx;
791 if (!checkFunctionOrMethodParameterIndex(S, FD, Attr, FuncParamNo, AttrArg,
792 Idx))
793 return false;
794
795 const ParmVarDecl *Param = FD->getParamDecl(Idx);
796 if (AllowDependentType && Param->getType()->isDependentType())
797 return true;
798 if (!Param->getType()->isIntegerType() && !Param->getType()->isCharType()) {
799 SourceLocation SrcLoc = AttrArg->getLocStart();
800 S.Diag(SrcLoc, diag::err_attribute_integers_only)
801 << getAttrName(Attr) << Param->getSourceRange();
802 return false;
803 }
804 return true;
805}
806
807/// \brief Checks to be sure that the given parameter number is in bounds, and is
808/// an integral type. Will emit appropriate diagnostics if this returns false.
809///
810/// FuncParamNo is expected to be from the user, so is base-1. AttrArgNo is used
811/// to actually retrieve the argument, so it's base-0.
George Burgess IVe3763372016-12-22 02:50:20 +0000812static bool checkParamIsIntegerType(Sema &S, const FunctionDecl *FD,
813 const AttributeList &Attr,
Erich Keane623efd82017-03-30 21:48:55 +0000814 unsigned FuncParamNo, unsigned AttrArgNo,
815 bool AllowDependentType = false) {
George Burgess IVe3763372016-12-22 02:50:20 +0000816 assert(Attr.isArgExpr(AttrArgNo) && "Expected expression argument");
Erich Keane623efd82017-03-30 21:48:55 +0000817 return checkParamIsIntegerType(S, FD, Attr, Attr.getArgAsExpr(AttrArgNo),
818 FuncParamNo, AttrArgNo, AllowDependentType);
George Burgess IVe3763372016-12-22 02:50:20 +0000819}
820
821static void handleAllocSizeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
822 if (!checkAttributeAtLeastNumArgs(S, Attr, 1) ||
823 !checkAttributeAtMostNumArgs(S, Attr, 2))
824 return;
825
826 const auto *FD = cast<FunctionDecl>(D);
827 if (!FD->getReturnType()->isPointerType()) {
828 S.Diag(Attr.getLoc(), diag::warn_attribute_return_pointers_only)
829 << Attr.getName();
830 return;
831 }
832
833 const Expr *SizeExpr = Attr.getArgAsExpr(0);
834 int SizeArgNo;
Simon Pilgrim27cc0542017-02-15 15:12:06 +0000835 // Parameter indices are 1-indexed, hence Index=1
George Burgess IVe3763372016-12-22 02:50:20 +0000836 if (!checkPositiveIntArgument(S, Attr, SizeExpr, SizeArgNo, /*Index=*/1))
837 return;
838
839 if (!checkParamIsIntegerType(S, FD, Attr, SizeArgNo, /*AttrArgNo=*/0))
840 return;
841
842 // Args are 1-indexed, so 0 implies that the arg was not present
843 int NumberArgNo = 0;
844 if (Attr.getNumArgs() == 2) {
845 const Expr *NumberExpr = Attr.getArgAsExpr(1);
Simon Pilgrim27cc0542017-02-15 15:12:06 +0000846 // Parameter indices are 1-based, hence Index=2
George Burgess IVe3763372016-12-22 02:50:20 +0000847 if (!checkPositiveIntArgument(S, Attr, NumberExpr, NumberArgNo,
848 /*Index=*/2))
849 return;
850
851 if (!checkParamIsIntegerType(S, FD, Attr, NumberArgNo, /*AttrArgNo=*/1))
852 return;
853 }
854
855 D->addAttr(::new (S.Context) AllocSizeAttr(
856 Attr.getRange(), S.Context, SizeArgNo, NumberArgNo,
857 Attr.getAttributeSpellingListIndex()));
858}
DeLesley Hutchinsb6824312013-05-17 23:02:59 +0000859
Michael Hana9171bc2012-08-03 17:40:43 +0000860static bool checkTryLockFunAttrCommon(Sema &S, Decl *D,
861 const AttributeList &Attr,
Craig Topper5603df42013-07-05 19:34:19 +0000862 SmallVectorImpl<Expr *> &Args) {
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000863 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
Michael Han3be3b442012-07-23 18:48:41 +0000864 return false;
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000865
Aaron Ballman00e99962013-08-31 01:11:41 +0000866 if (!isIntOrBool(Attr.getArgAsExpr(0))) {
Aaron Ballman29982272013-07-23 14:03:57 +0000867 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
Aaron Ballman3bf758c2013-07-30 01:31:03 +0000868 << Attr.getName() << 1 << AANT_ArgumentIntOrBool;
Michael Han3be3b442012-07-23 18:48:41 +0000869 return false;
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000870 }
871
872 // check that all arguments are lockable objects
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000873 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 1);
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000874
Michael Han3be3b442012-07-23 18:48:41 +0000875 return true;
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000876}
877
Michael Hana9171bc2012-08-03 17:40:43 +0000878static void handleSharedTrylockFunctionAttr(Sema &S, Decl *D,
Michael Han3be3b442012-07-23 18:48:41 +0000879 const AttributeList &Attr) {
880 SmallVector<Expr*, 2> Args;
881 if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
882 return;
883
Michael Han99315932013-01-24 16:46:58 +0000884 D->addAttr(::new (S.Context)
885 SharedTrylockFunctionAttr(Attr.getRange(), S.Context,
Aaron Ballman00e99962013-08-31 01:11:41 +0000886 Attr.getArgAsExpr(0),
887 Args.data(), Args.size(),
Michael Han99315932013-01-24 16:46:58 +0000888 Attr.getAttributeSpellingListIndex()));
Michael Han3be3b442012-07-23 18:48:41 +0000889}
890
Michael Hana9171bc2012-08-03 17:40:43 +0000891static void handleExclusiveTrylockFunctionAttr(Sema &S, Decl *D,
Michael Han3be3b442012-07-23 18:48:41 +0000892 const AttributeList &Attr) {
893 SmallVector<Expr*, 2> Args;
894 if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
895 return;
896
Nico Weber462fd1e2015-01-07 23:50:05 +0000897 D->addAttr(::new (S.Context) ExclusiveTrylockFunctionAttr(
898 Attr.getRange(), S.Context, Attr.getArgAsExpr(0), Args.data(),
899 Args.size(), Attr.getAttributeSpellingListIndex()));
Michael Han3be3b442012-07-23 18:48:41 +0000900}
901
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000902static void handleLockReturnedAttr(Sema &S, Decl *D,
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000903 const AttributeList &Attr) {
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000904 // check that the argument is lockable object
DeLesley Hutchinsd96b46a2012-05-02 17:38:37 +0000905 SmallVector<Expr*, 1> Args;
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000906 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
DeLesley Hutchinsd96b46a2012-05-02 17:38:37 +0000907 unsigned Size = Args.size();
908 if (Size == 0)
909 return;
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000910
Michael Han99315932013-01-24 16:46:58 +0000911 D->addAttr(::new (S.Context)
912 LockReturnedAttr(Attr.getRange(), S.Context, Args[0],
913 Attr.getAttributeSpellingListIndex()));
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000914}
915
916static void handleLocksExcludedAttr(Sema &S, Decl *D,
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000917 const AttributeList &Attr) {
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000918 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000919 return;
920
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000921 // check that all arguments are lockable objects
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000922 SmallVector<Expr*, 1> Args;
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000923 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000924 unsigned Size = Args.size();
DeLesley Hutchins8d11c792012-04-19 16:10:44 +0000925 if (Size == 0)
926 return;
927 Expr **StartArg = &Args[0];
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000928
Michael Han99315932013-01-24 16:46:58 +0000929 D->addAttr(::new (S.Context)
930 LocksExcludedAttr(Attr.getRange(), S.Context, StartArg, Size,
931 Attr.getAttributeSpellingListIndex()));
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000932}
933
George Burgess IV177399e2017-01-09 04:12:14 +0000934static bool checkFunctionConditionAttr(Sema &S, Decl *D,
935 const AttributeList &Attr,
936 Expr *&Cond, StringRef &Msg) {
937 Cond = Attr.getArgAsExpr(0);
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000938 if (!Cond->isTypeDependent()) {
939 ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
940 if (Converted.isInvalid())
George Burgess IV177399e2017-01-09 04:12:14 +0000941 return false;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000942 Cond = Converted.get();
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000943 }
944
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000945 if (!S.checkStringLiteralArgumentAttr(Attr, 1, Msg))
George Burgess IV177399e2017-01-09 04:12:14 +0000946 return false;
947
948 if (Msg.empty())
949 Msg = "<no message provided>";
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000950
951 SmallVector<PartialDiagnosticAt, 8> Diags;
Argyrios Kyrtzidisa7233bd2017-05-24 00:46:27 +0000952 if (isa<FunctionDecl>(D) && !Cond->isValueDependent() &&
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000953 !Expr::isPotentialConstantExprUnevaluated(Cond, cast<FunctionDecl>(D),
954 Diags)) {
George Burgess IV177399e2017-01-09 04:12:14 +0000955 S.Diag(Attr.getLoc(), diag::err_attr_cond_never_constant_expr)
956 << Attr.getName();
George Burgess IV0d546532016-11-10 21:47:12 +0000957 for (const PartialDiagnosticAt &PDiag : Diags)
958 S.Diag(PDiag.first, PDiag.second);
George Burgess IV177399e2017-01-09 04:12:14 +0000959 return false;
960 }
961 return true;
962}
963
964static void handleEnableIfAttr(Sema &S, Decl *D, const AttributeList &Attr) {
965 S.Diag(Attr.getLoc(), diag::ext_clang_enable_if);
966
967 Expr *Cond;
968 StringRef Msg;
969 if (checkFunctionConditionAttr(S, D, Attr, Cond, Msg))
970 D->addAttr(::new (S.Context)
971 EnableIfAttr(Attr.getRange(), S.Context, Cond, Msg,
972 Attr.getAttributeSpellingListIndex()));
973}
974
975namespace {
976/// Determines if a given Expr references any of the given function's
977/// ParmVarDecls, or the function's implicit `this` parameter (if applicable).
978class ArgumentDependenceChecker
979 : public RecursiveASTVisitor<ArgumentDependenceChecker> {
980#ifndef NDEBUG
981 const CXXRecordDecl *ClassType;
982#endif
983 llvm::SmallPtrSet<const ParmVarDecl *, 16> Parms;
984 bool Result;
985
986public:
987 ArgumentDependenceChecker(const FunctionDecl *FD) {
988#ifndef NDEBUG
989 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
990 ClassType = MD->getParent();
991 else
992 ClassType = nullptr;
993#endif
994 Parms.insert(FD->param_begin(), FD->param_end());
995 }
996
997 bool referencesArgs(Expr *E) {
998 Result = false;
999 TraverseStmt(E);
1000 return Result;
1001 }
1002
1003 bool VisitCXXThisExpr(CXXThisExpr *E) {
1004 assert(E->getType()->getPointeeCXXRecordDecl() == ClassType &&
1005 "`this` doesn't refer to the enclosing class?");
1006 Result = true;
1007 return false;
1008 }
1009
1010 bool VisitDeclRefExpr(DeclRefExpr *DRE) {
1011 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
1012 if (Parms.count(PVD)) {
1013 Result = true;
1014 return false;
1015 }
1016 return true;
1017 }
1018};
1019}
1020
1021static void handleDiagnoseIfAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1022 S.Diag(Attr.getLoc(), diag::ext_clang_diagnose_if);
1023
1024 Expr *Cond;
1025 StringRef Msg;
1026 if (!checkFunctionConditionAttr(S, D, Attr, Cond, Msg))
1027 return;
1028
1029 StringRef DiagTypeStr;
1030 if (!S.checkStringLiteralArgumentAttr(Attr, 2, DiagTypeStr))
1031 return;
1032
1033 DiagnoseIfAttr::DiagnosticType DiagType;
1034 if (!DiagnoseIfAttr::ConvertStrToDiagnosticType(DiagTypeStr, DiagType)) {
1035 S.Diag(Attr.getArgAsExpr(2)->getLocStart(),
1036 diag::err_diagnose_if_invalid_diagnostic_type);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001037 return;
1038 }
1039
Argyrios Kyrtzidisa7233bd2017-05-24 00:46:27 +00001040 bool ArgDependent = false;
Argyrios Kyrtzidis5f0c0aa2017-05-24 18:35:01 +00001041 if (const auto *FD = dyn_cast<FunctionDecl>(D))
Argyrios Kyrtzidisa7233bd2017-05-24 00:46:27 +00001042 ArgDependent = ArgumentDependenceChecker(FD).referencesArgs(Cond);
George Burgess IV177399e2017-01-09 04:12:14 +00001043 D->addAttr(::new (S.Context) DiagnoseIfAttr(
Argyrios Kyrtzidisa7233bd2017-05-24 00:46:27 +00001044 Attr.getRange(), S.Context, Cond, Msg, DiagType, ArgDependent, cast<NamedDecl>(D),
George Burgess IV177399e2017-01-09 04:12:14 +00001045 Attr.getAttributeSpellingListIndex()));
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001046}
1047
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001048static void handlePassObjectSizeAttr(Sema &S, Decl *D,
1049 const AttributeList &Attr) {
1050 if (D->hasAttr<PassObjectSizeAttr>()) {
1051 S.Diag(D->getLocStart(), diag::err_attribute_only_once_per_parameter)
1052 << Attr.getName();
1053 return;
1054 }
1055
1056 Expr *E = Attr.getArgAsExpr(0);
1057 uint32_t Type;
1058 if (!checkUInt32Argument(S, Attr, E, Type, /*Idx=*/1))
1059 return;
1060
1061 // pass_object_size's argument is passed in as the second argument of
1062 // __builtin_object_size. So, it has the same constraints as that second
1063 // argument; namely, it must be in the range [0, 3].
1064 if (Type > 3) {
1065 S.Diag(E->getLocStart(), diag::err_attribute_argument_outof_range)
1066 << Attr.getName() << 0 << 3 << E->getSourceRange();
1067 return;
1068 }
1069
1070 // pass_object_size is only supported on constant pointer parameters; as a
1071 // kindness to users, we allow the parameter to be non-const for declarations.
1072 // At this point, we have no clue if `D` belongs to a function declaration or
1073 // definition, so we defer the constness check until later.
1074 if (!cast<ParmVarDecl>(D)->getType()->isPointerType()) {
1075 S.Diag(D->getLocStart(), diag::err_attribute_pointers_only)
1076 << Attr.getName() << 1;
1077 return;
1078 }
1079
1080 D->addAttr(::new (S.Context)
1081 PassObjectSizeAttr(Attr.getRange(), S.Context, (int)Type,
1082 Attr.getAttributeSpellingListIndex()));
1083}
1084
DeLesley Hutchins5a715c42013-08-30 22:56:34 +00001085static void handleConsumableAttr(Sema &S, Decl *D, const AttributeList &Attr) {
David Blaikie16f76d22013-09-06 01:28:43 +00001086 ConsumableAttr::ConsumedState DefaultState;
1087
1088 if (Attr.isArgIdent(0)) {
Aaron Ballman682ee422013-09-11 19:47:58 +00001089 IdentifierLoc *IL = Attr.getArgAsIdent(0);
1090 if (!ConsumableAttr::ConvertStrToConsumedState(IL->Ident->getName(),
1091 DefaultState)) {
1092 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported)
1093 << Attr.getName() << IL->Ident;
David Blaikie16f76d22013-09-06 01:28:43 +00001094 return;
1095 }
David Blaikie16f76d22013-09-06 01:28:43 +00001096 } else {
1097 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
1098 << Attr.getName() << AANT_ArgumentIdentifier;
1099 return;
1100 }
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001101
1102 D->addAttr(::new (S.Context)
David Blaikie16f76d22013-09-06 01:28:43 +00001103 ConsumableAttr(Attr.getRange(), S.Context, DefaultState,
DeLesley Hutchins5a715c42013-08-30 22:56:34 +00001104 Attr.getAttributeSpellingListIndex()));
1105}
1106
1107static bool checkForConsumableClass(Sema &S, const CXXMethodDecl *MD,
1108 const AttributeList &Attr) {
1109 ASTContext &CurrContext = S.getASTContext();
1110 QualType ThisType = MD->getThisType(CurrContext)->getPointeeType();
1111
1112 if (const CXXRecordDecl *RD = ThisType->getAsCXXRecordDecl()) {
1113 if (!RD->hasAttr<ConsumableAttr>()) {
1114 S.Diag(Attr.getLoc(), diag::warn_attr_on_unconsumable_class) <<
1115 RD->getNameAsString();
1116
1117 return false;
1118 }
1119 }
1120
1121 return true;
1122}
1123
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001124static void handleCallableWhenAttr(Sema &S, Decl *D,
1125 const AttributeList &Attr) {
Aaron Ballmandbd586f2013-10-14 23:26:04 +00001126 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
1127 return;
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001128
DeLesley Hutchins5a715c42013-08-30 22:56:34 +00001129 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr))
1130 return;
1131
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001132 SmallVector<CallableWhenAttr::ConsumedState, 3> States;
1133 for (unsigned ArgIndex = 0; ArgIndex < Attr.getNumArgs(); ++ArgIndex) {
1134 CallableWhenAttr::ConsumedState CallableState;
1135
Aaron Ballman4c9b7dc2013-10-05 22:45:34 +00001136 StringRef StateString;
1137 SourceLocation Loc;
Aaron Ballman55ef1512014-12-19 16:42:04 +00001138 if (Attr.isArgIdent(ArgIndex)) {
1139 IdentifierLoc *Ident = Attr.getArgAsIdent(ArgIndex);
1140 StateString = Ident->Ident->getName();
1141 Loc = Ident->Loc;
1142 } else {
1143 if (!S.checkStringLiteralArgumentAttr(Attr, ArgIndex, StateString, &Loc))
1144 return;
1145 }
Aaron Ballman4c9b7dc2013-10-05 22:45:34 +00001146
1147 if (!CallableWhenAttr::ConvertStrToConsumedState(StateString,
DeLesley Hutchins69391772013-10-17 23:23:53 +00001148 CallableState)) {
Aaron Ballman4c9b7dc2013-10-05 22:45:34 +00001149 S.Diag(Loc, diag::warn_attribute_type_not_supported)
1150 << Attr.getName() << StateString;
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001151 return;
1152 }
Aaron Ballman4c9b7dc2013-10-05 22:45:34 +00001153
1154 States.push_back(CallableState);
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001155 }
1156
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001157 D->addAttr(::new (S.Context)
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001158 CallableWhenAttr(Attr.getRange(), S.Context, States.data(),
1159 States.size(), Attr.getAttributeSpellingListIndex()));
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001160}
1161
DeLesley Hutchins69391772013-10-17 23:23:53 +00001162static void handleParamTypestateAttr(Sema &S, Decl *D,
1163 const AttributeList &Attr) {
DeLesley Hutchins69391772013-10-17 23:23:53 +00001164 ParamTypestateAttr::ConsumedState ParamState;
1165
1166 if (Attr.isArgIdent(0)) {
1167 IdentifierLoc *Ident = Attr.getArgAsIdent(0);
1168 StringRef StateString = Ident->Ident->getName();
1169
1170 if (!ParamTypestateAttr::ConvertStrToConsumedState(StateString,
1171 ParamState)) {
1172 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
1173 << Attr.getName() << StateString;
1174 return;
1175 }
1176 } else {
1177 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
1178 Attr.getName() << AANT_ArgumentIdentifier;
1179 return;
1180 }
1181
1182 // FIXME: This check is currently being done in the analysis. It can be
1183 // enabled here only after the parser propagates attributes at
1184 // template specialization definition, not declaration.
1185 //QualType ReturnType = cast<ParmVarDecl>(D)->getType();
1186 //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
1187 //
1188 //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
1189 // S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
1190 // ReturnType.getAsString();
1191 // return;
1192 //}
1193
1194 D->addAttr(::new (S.Context)
1195 ParamTypestateAttr(Attr.getRange(), S.Context, ParamState,
1196 Attr.getAttributeSpellingListIndex()));
1197}
1198
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001199static void handleReturnTypestateAttr(Sema &S, Decl *D,
1200 const AttributeList &Attr) {
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001201 ReturnTypestateAttr::ConsumedState ReturnState;
1202
1203 if (Attr.isArgIdent(0)) {
Aaron Ballman682ee422013-09-11 19:47:58 +00001204 IdentifierLoc *IL = Attr.getArgAsIdent(0);
1205 if (!ReturnTypestateAttr::ConvertStrToConsumedState(IL->Ident->getName(),
1206 ReturnState)) {
1207 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported)
1208 << Attr.getName() << IL->Ident;
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001209 return;
1210 }
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001211 } else {
1212 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
1213 Attr.getName() << AANT_ArgumentIdentifier;
1214 return;
1215 }
1216
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001217 // FIXME: This check is currently being done in the analysis. It can be
1218 // enabled here only after the parser propagates attributes at
1219 // template specialization definition, not declaration.
1220 //QualType ReturnType;
1221 //
DeLesley Hutchins36ea1dd2013-10-17 22:53:04 +00001222 //if (const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D)) {
1223 // ReturnType = Param->getType();
1224 //
1225 //} else if (const CXXConstructorDecl *Constructor =
1226 // dyn_cast<CXXConstructorDecl>(D)) {
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001227 // ReturnType = Constructor->getThisType(S.getASTContext())->getPointeeType();
1228 //
1229 //} else {
1230 //
1231 // ReturnType = cast<FunctionDecl>(D)->getCallResultType();
1232 //}
1233 //
1234 //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
1235 //
1236 //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
1237 // S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
1238 // ReturnType.getAsString();
1239 // return;
1240 //}
1241
1242 D->addAttr(::new (S.Context)
1243 ReturnTypestateAttr(Attr.getRange(), S.Context, ReturnState,
1244 Attr.getAttributeSpellingListIndex()));
1245}
1246
DeLesley Hutchins33a29342013-10-11 23:03:26 +00001247static void handleSetTypestateAttr(Sema &S, Decl *D, const AttributeList &Attr) {
DeLesley Hutchins33a29342013-10-11 23:03:26 +00001248 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr))
1249 return;
1250
1251 SetTypestateAttr::ConsumedState NewState;
DeLesley Hutchins33a29342013-10-11 23:03:26 +00001252 if (Attr.isArgIdent(0)) {
Aaron Ballman91c98e12013-10-14 23:22:37 +00001253 IdentifierLoc *Ident = Attr.getArgAsIdent(0);
1254 StringRef Param = Ident->Ident->getName();
1255 if (!SetTypestateAttr::ConvertStrToConsumedState(Param, NewState)) {
1256 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
1257 << Attr.getName() << Param;
DeLesley Hutchins33a29342013-10-11 23:03:26 +00001258 return;
1259 }
DeLesley Hutchins33a29342013-10-11 23:03:26 +00001260 } else {
1261 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
1262 Attr.getName() << AANT_ArgumentIdentifier;
1263 return;
1264 }
1265
1266 D->addAttr(::new (S.Context)
1267 SetTypestateAttr(Attr.getRange(), S.Context, NewState,
1268 Attr.getAttributeSpellingListIndex()));
1269}
1270
Chris Wailes9385f9f2013-10-29 20:28:41 +00001271static void handleTestTypestateAttr(Sema &S, Decl *D,
1272 const AttributeList &Attr) {
DeLesley Hutchins33a29342013-10-11 23:03:26 +00001273 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr))
1274 return;
1275
Chris Wailes9385f9f2013-10-29 20:28:41 +00001276 TestTypestateAttr::ConsumedState TestState;
DeLesley Hutchins33a29342013-10-11 23:03:26 +00001277 if (Attr.isArgIdent(0)) {
Aaron Ballman91c98e12013-10-14 23:22:37 +00001278 IdentifierLoc *Ident = Attr.getArgAsIdent(0);
1279 StringRef Param = Ident->Ident->getName();
Chris Wailes9385f9f2013-10-29 20:28:41 +00001280 if (!TestTypestateAttr::ConvertStrToConsumedState(Param, TestState)) {
Aaron Ballman91c98e12013-10-14 23:22:37 +00001281 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
1282 << Attr.getName() << Param;
DeLesley Hutchins33a29342013-10-11 23:03:26 +00001283 return;
1284 }
DeLesley Hutchins33a29342013-10-11 23:03:26 +00001285 } else {
1286 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
1287 Attr.getName() << AANT_ArgumentIdentifier;
1288 return;
1289 }
1290
1291 D->addAttr(::new (S.Context)
Chris Wailes9385f9f2013-10-29 20:28:41 +00001292 TestTypestateAttr(Attr.getRange(), S.Context, TestState,
DeLesley Hutchins33a29342013-10-11 23:03:26 +00001293 Attr.getAttributeSpellingListIndex()));
1294}
1295
Chandler Carruthedc2c642011-07-02 00:01:44 +00001296static void handleExtVectorTypeAttr(Sema &S, Scope *scope, Decl *D,
1297 const AttributeList &Attr) {
Richard Smith1f5a4322013-01-13 02:11:23 +00001298 // Remember this typedef decl, we will need it later for diagnostics.
Aaron Ballman74eeeae2013-11-27 13:27:02 +00001299 S.ExtVectorDecls.push_back(cast<TypedefNameDecl>(D));
Chris Lattner2c6fcf52008-06-26 18:38:35 +00001300}
1301
Chandler Carruthedc2c642011-07-02 00:01:44 +00001302static void handlePackedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00001303 if (TagDecl *TD = dyn_cast<TagDecl>(D))
Aaron Ballman36a53502014-01-16 13:03:14 +00001304 TD->addAttr(::new (S.Context) PackedAttr(Attr.getRange(), S.Context,
1305 Attr.getAttributeSpellingListIndex()));
Chandler Carruthff4c4f02011-07-01 23:49:12 +00001306 else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Aaron Ballmanb6fd7262017-08-08 18:07:17 +00001307 bool BitfieldByteAligned = (!FD->getType()->isDependentType() &&
1308 !FD->getType()->isIncompleteType() &&
1309 FD->isBitField() &&
1310 S.Context.getTypeAlign(FD->getType()) <= 8);
Alexey Bataev830dfcc2015-12-03 09:34:49 +00001311
Aaron Ballmanb6fd7262017-08-08 18:07:17 +00001312 if (S.getASTContext().getTargetInfo().getTriple().isPS4()) {
1313 if (BitfieldByteAligned)
1314 // The PS4 target needs to maintain ABI backwards compatibility.
1315 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored_for_field_of_type)
1316 << Attr.getName() << FD->getType();
1317 else
1318 FD->addAttr(::new (S.Context) PackedAttr(
1319 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
1320 } else {
1321 // Report warning about changed offset in the newer compiler versions.
1322 if (BitfieldByteAligned)
1323 S.Diag(Attr.getLoc(), diag::warn_attribute_packed_for_bitfield);
1324
1325 FD->addAttr(::new (S.Context) PackedAttr(
1326 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
1327 }
1328
Chris Lattner2c6fcf52008-06-26 18:38:35 +00001329 } else
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001330 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
Chris Lattner2c6fcf52008-06-26 18:38:35 +00001331}
1332
Ted Kremenek7fd17232011-09-29 07:02:25 +00001333static bool checkIBOutletCommon(Sema &S, Decl *D, const AttributeList &Attr) {
1334 // The IBOutlet/IBOutletCollection attributes only apply to instance
1335 // variables or properties of Objective-C classes. The outlet must also
1336 // have an object reference type.
1337 if (const ObjCIvarDecl *VD = dyn_cast<ObjCIvarDecl>(D)) {
1338 if (!VD->getType()->getAs<ObjCObjectPointerType>()) {
Ted Kremenek5d6044e2011-11-01 18:08:35 +00001339 S.Diag(Attr.getLoc(), diag::warn_iboutlet_object_type)
Ted Kremenek7fd17232011-09-29 07:02:25 +00001340 << Attr.getName() << VD->getType() << 0;
1341 return false;
1342 }
1343 }
1344 else if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) {
1345 if (!PD->getType()->getAs<ObjCObjectPointerType>()) {
Douglas Gregor5c3cc422012-03-14 16:55:17 +00001346 S.Diag(Attr.getLoc(), diag::warn_iboutlet_object_type)
Ted Kremenek7fd17232011-09-29 07:02:25 +00001347 << Attr.getName() << PD->getType() << 1;
1348 return false;
1349 }
1350 }
1351 else {
1352 S.Diag(Attr.getLoc(), diag::warn_attribute_iboutlet) << Attr.getName();
1353 return false;
1354 }
Douglas Gregor5c3cc422012-03-14 16:55:17 +00001355
Ted Kremenek7fd17232011-09-29 07:02:25 +00001356 return true;
1357}
1358
Chandler Carruthedc2c642011-07-02 00:01:44 +00001359static void handleIBOutlet(Sema &S, Decl *D, const AttributeList &Attr) {
Ted Kremenek7fd17232011-09-29 07:02:25 +00001360 if (!checkIBOutletCommon(S, D, Attr))
Ted Kremenek1f672822010-02-18 03:08:58 +00001361 return;
Ted Kremenek1f672822010-02-18 03:08:58 +00001362
Michael Han99315932013-01-24 16:46:58 +00001363 D->addAttr(::new (S.Context)
1364 IBOutletAttr(Attr.getRange(), S.Context,
1365 Attr.getAttributeSpellingListIndex()));
Ted Kremenek8e3704d2008-07-15 22:26:48 +00001366}
1367
Chandler Carruthedc2c642011-07-02 00:01:44 +00001368static void handleIBOutletCollection(Sema &S, Decl *D,
1369 const AttributeList &Attr) {
Ted Kremenek26bde772010-05-19 17:38:06 +00001370
1371 // The iboutletcollection attribute can have zero or one arguments.
Aaron Ballman00e99962013-08-31 01:11:41 +00001372 if (Attr.getNumArgs() > 1) {
Aaron Ballmanb7243382013-07-23 19:30:11 +00001373 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
1374 << Attr.getName() << 1;
Ted Kremenek26bde772010-05-19 17:38:06 +00001375 return;
1376 }
1377
Ted Kremenek7fd17232011-09-29 07:02:25 +00001378 if (!checkIBOutletCommon(S, D, Attr))
Ted Kremenek26bde772010-05-19 17:38:06 +00001379 return;
Ted Kremenek7fd17232011-09-29 07:02:25 +00001380
Richard Smithb1f9a282013-10-31 01:56:18 +00001381 ParsedType PT;
1382
1383 if (Attr.hasParsedType())
1384 PT = Attr.getTypeArg();
1385 else {
1386 PT = S.getTypeName(S.Context.Idents.get("NSObject"), Attr.getLoc(),
1387 S.getScopeForContext(D->getDeclContext()->getParent()));
1388 if (!PT) {
1389 S.Diag(Attr.getLoc(), diag::err_iboutletcollection_type) << "NSObject";
1390 return;
1391 }
Aaron Ballman00e99962013-08-31 01:11:41 +00001392 }
Richard Smithb1f9a282013-10-31 01:56:18 +00001393
Craig Topperc3ec1492014-05-26 06:22:03 +00001394 TypeSourceInfo *QTLoc = nullptr;
Richard Smithb87c4652013-10-31 21:23:20 +00001395 QualType QT = S.GetTypeFromParser(PT, &QTLoc);
1396 if (!QTLoc)
1397 QTLoc = S.Context.getTrivialTypeSourceInfo(QT, Attr.getLoc());
Richard Smithb1f9a282013-10-31 01:56:18 +00001398
Fariborz Jahanianb5d59b62010-08-17 20:23:12 +00001399 // Diagnose use of non-object type in iboutletcollection attribute.
1400 // FIXME. Gnu attribute extension ignores use of builtin types in
1401 // attributes. So, __attribute__((iboutletcollection(char))) will be
1402 // treated as __attribute__((iboutletcollection())).
Fariborz Jahanian2f31b332011-10-18 19:54:31 +00001403 if (!QT->isObjCIdType() && !QT->isObjCObjectType()) {
Richard Smithb1f9a282013-10-31 01:56:18 +00001404 S.Diag(Attr.getLoc(),
1405 QT->isBuiltinType() ? diag::err_iboutletcollection_builtintype
1406 : diag::err_iboutletcollection_type) << QT;
Fariborz Jahanianb5d59b62010-08-17 20:23:12 +00001407 return;
1408 }
Richard Smithb1f9a282013-10-31 01:56:18 +00001409
Michael Han99315932013-01-24 16:46:58 +00001410 D->addAttr(::new (S.Context)
Richard Smithb87c4652013-10-31 21:23:20 +00001411 IBOutletCollectionAttr(Attr.getRange(), S.Context, QTLoc,
Michael Han99315932013-01-24 16:46:58 +00001412 Attr.getAttributeSpellingListIndex()));
Ted Kremenek26bde772010-05-19 17:38:06 +00001413}
1414
Hal Finkelee90a222014-09-26 05:04:30 +00001415bool Sema::isValidPointerAttrType(QualType T, bool RefOkay) {
1416 if (RefOkay) {
1417 if (T->isReferenceType())
1418 return true;
1419 } else {
1420 T = T.getNonReferenceType();
1421 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001422
Hal Finkelee90a222014-09-26 05:04:30 +00001423 // The nonnull attribute, and other similar attributes, can be applied to a
1424 // transparent union that contains a pointer type.
Richard Smith588bd9b2014-08-27 04:59:42 +00001425 if (const RecordType *UT = T->getAsUnionType()) {
Fariborz Jahanianf4aa2792011-06-27 21:12:03 +00001426 if (UT && UT->getDecl()->hasAttr<TransparentUnionAttr>()) {
1427 RecordDecl *UD = UT->getDecl();
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001428 for (const auto *I : UD->fields()) {
1429 QualType QT = I->getType();
Richard Smith588bd9b2014-08-27 04:59:42 +00001430 if (QT->isAnyPointerType() || QT->isBlockPointerType())
1431 return true;
Fariborz Jahanianf4aa2792011-06-27 21:12:03 +00001432 }
1433 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001434 }
1435
1436 return T->isAnyPointerType() || T->isBlockPointerType();
Fariborz Jahanianf4aa2792011-06-27 21:12:03 +00001437}
1438
Ted Kremenek9aedc152014-01-17 06:24:56 +00001439static bool attrNonNullArgCheck(Sema &S, QualType T, const AttributeList &Attr,
Aaron Ballman4bfa0de2014-08-01 12:58:11 +00001440 SourceRange AttrParmRange,
Hal Finkelee90a222014-09-26 05:04:30 +00001441 SourceRange TypeRange,
Aaron Ballman4bfa0de2014-08-01 12:58:11 +00001442 bool isReturnValue = false) {
Hal Finkelee90a222014-09-26 05:04:30 +00001443 if (!S.isValidPointerAttrType(T)) {
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001444 if (isReturnValue)
1445 S.Diag(Attr.getLoc(), diag::warn_attribute_return_pointers_only)
1446 << Attr.getName() << AttrParmRange << TypeRange;
1447 else
1448 S.Diag(Attr.getLoc(), diag::warn_attribute_pointers_only)
1449 << Attr.getName() << AttrParmRange << TypeRange << 0;
Ted Kremenek9aedc152014-01-17 06:24:56 +00001450 return false;
1451 }
1452 return true;
1453}
1454
Chandler Carruthedc2c642011-07-02 00:01:44 +00001455static void handleNonNullAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballmanbe50eb82013-07-30 00:48:57 +00001456 SmallVector<unsigned, 8> NonNullArgs;
Richard Smith588bd9b2014-08-27 04:59:42 +00001457 for (unsigned I = 0; I < Attr.getNumArgs(); ++I) {
1458 Expr *Ex = Attr.getArgAsExpr(I);
Aaron Ballmanbe50eb82013-07-30 00:48:57 +00001459 uint64_t Idx;
Richard Smith588bd9b2014-08-27 04:59:42 +00001460 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, I + 1, Ex, Idx))
Ted Kremenek2d63bc12008-07-21 21:53:04 +00001461 return;
Ted Kremenek2d63bc12008-07-21 21:53:04 +00001462
1463 // Is the function argument a pointer type?
Richard Smith588bd9b2014-08-27 04:59:42 +00001464 if (Idx < getFunctionOrMethodNumParams(D) &&
1465 !attrNonNullArgCheck(S, getFunctionOrMethodParamType(D, Idx), Attr,
Aaron Ballman4bfa0de2014-08-01 12:58:11 +00001466 Ex->getSourceRange(),
1467 getFunctionOrMethodParamRange(D, Idx)))
Ted Kremenekc4f6d902008-09-01 19:57:52 +00001468 continue;
Mike Stumpd3bb5572009-07-24 19:02:52 +00001469
Aaron Ballmanbe50eb82013-07-30 00:48:57 +00001470 NonNullArgs.push_back(Idx);
Ted Kremenek2d63bc12008-07-21 21:53:04 +00001471 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00001472
1473 // If no arguments were specified to __attribute__((nonnull)) then all pointer
Richard Smith588bd9b2014-08-27 04:59:42 +00001474 // arguments have a nonnull attribute; warn if there aren't any. Skip this
1475 // check if the attribute came from a macro expansion or a template
1476 // instantiation.
1477 if (NonNullArgs.empty() && Attr.getLoc().isFileID() &&
Richard Smith51ec0cf2017-02-21 01:17:38 +00001478 !S.inTemplateInstantiation()) {
Richard Smith588bd9b2014-08-27 04:59:42 +00001479 bool AnyPointers = isFunctionOrMethodVariadic(D);
1480 for (unsigned I = 0, E = getFunctionOrMethodNumParams(D);
1481 I != E && !AnyPointers; ++I) {
1482 QualType T = getFunctionOrMethodParamType(D, I);
Hal Finkelee90a222014-09-26 05:04:30 +00001483 if (T->isDependentType() || S.isValidPointerAttrType(T))
Richard Smith588bd9b2014-08-27 04:59:42 +00001484 AnyPointers = true;
Ted Kremenek5fa50522008-11-18 06:52:58 +00001485 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00001486
Richard Smith588bd9b2014-08-27 04:59:42 +00001487 if (!AnyPointers)
1488 S.Diag(Attr.getLoc(), diag::warn_attribute_nonnull_no_pointers);
Ted Kremenek2d63bc12008-07-21 21:53:04 +00001489 }
Ted Kremenekc4f6d902008-09-01 19:57:52 +00001490
Richard Smith588bd9b2014-08-27 04:59:42 +00001491 unsigned *Start = NonNullArgs.data();
1492 unsigned Size = NonNullArgs.size();
1493 llvm::array_pod_sort(Start, Start + Size);
Michael Han99315932013-01-24 16:46:58 +00001494 D->addAttr(::new (S.Context)
Richard Smith588bd9b2014-08-27 04:59:42 +00001495 NonNullAttr(Attr.getRange(), S.Context, Start, Size,
Michael Han99315932013-01-24 16:46:58 +00001496 Attr.getAttributeSpellingListIndex()));
Ted Kremenek2d63bc12008-07-21 21:53:04 +00001497}
1498
Jordan Rosec9399072014-02-11 17:27:59 +00001499static void handleNonNullAttrParameter(Sema &S, ParmVarDecl *D,
1500 const AttributeList &Attr) {
1501 if (Attr.getNumArgs() > 0) {
1502 if (D->getFunctionType()) {
1503 handleNonNullAttr(S, D, Attr);
1504 } else {
1505 S.Diag(Attr.getLoc(), diag::warn_attribute_nonnull_parm_no_args)
1506 << D->getSourceRange();
1507 }
1508 return;
1509 }
1510
1511 // Is the argument a pointer type?
Aaron Ballman4bfa0de2014-08-01 12:58:11 +00001512 if (!attrNonNullArgCheck(S, D->getType(), Attr, SourceRange(),
1513 D->getSourceRange()))
Jordan Rosec9399072014-02-11 17:27:59 +00001514 return;
1515
1516 D->addAttr(::new (S.Context)
Craig Topperc3ec1492014-05-26 06:22:03 +00001517 NonNullAttr(Attr.getRange(), S.Context, nullptr, 0,
Jordan Rosec9399072014-02-11 17:27:59 +00001518 Attr.getAttributeSpellingListIndex()));
1519}
1520
Ted Kremenekdbf62e32014-01-20 05:50:47 +00001521static void handleReturnsNonNullAttr(Sema &S, Decl *D,
1522 const AttributeList &Attr) {
Aaron Ballmanfc1951c2014-01-20 14:19:44 +00001523 QualType ResultType = getFunctionOrMethodResultType(D);
Aaron Ballman4bfa0de2014-08-01 12:58:11 +00001524 SourceRange SR = getFunctionOrMethodResultSourceRange(D);
1525 if (!attrNonNullArgCheck(S, ResultType, Attr, SourceRange(), SR,
Ted Kremenekdbf62e32014-01-20 05:50:47 +00001526 /* isReturnValue */ true))
1527 return;
1528
1529 D->addAttr(::new (S.Context)
1530 ReturnsNonNullAttr(Attr.getRange(), S.Context,
1531 Attr.getAttributeSpellingListIndex()));
1532}
1533
Akira Hatanaka98a49332017-09-22 00:41:05 +00001534static void handleNoEscapeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1535 if (D->isInvalidDecl())
1536 return;
1537
1538 // noescape only applies to pointer types.
1539 QualType T = cast<ParmVarDecl>(D)->getType();
1540 if (!S.isValidPointerAttrType(T, /* RefOkay */ true)) {
1541 S.Diag(Attr.getLoc(), diag::warn_attribute_pointers_only)
1542 << Attr.getName() << Attr.getRange() << 0;
1543 return;
1544 }
1545
1546 D->addAttr(::new (S.Context) NoEscapeAttr(
1547 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
1548}
1549
Hal Finkelee90a222014-09-26 05:04:30 +00001550static void handleAssumeAlignedAttr(Sema &S, Decl *D,
1551 const AttributeList &Attr) {
1552 Expr *E = Attr.getArgAsExpr(0),
1553 *OE = Attr.getNumArgs() > 1 ? Attr.getArgAsExpr(1) : nullptr;
1554 S.AddAssumeAlignedAttr(Attr.getRange(), D, E, OE,
1555 Attr.getAttributeSpellingListIndex());
1556}
1557
Erich Keane623efd82017-03-30 21:48:55 +00001558static void handleAllocAlignAttr(Sema &S, Decl *D,
1559 const AttributeList &Attr) {
1560 S.AddAllocAlignAttr(Attr.getRange(), D, Attr.getArgAsExpr(0),
1561 Attr.getAttributeSpellingListIndex());
1562}
1563
Hal Finkelee90a222014-09-26 05:04:30 +00001564void Sema::AddAssumeAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
1565 Expr *OE, unsigned SpellingListIndex) {
1566 QualType ResultType = getFunctionOrMethodResultType(D);
1567 SourceRange SR = getFunctionOrMethodResultSourceRange(D);
1568
1569 AssumeAlignedAttr TmpAttr(AttrRange, Context, E, OE, SpellingListIndex);
1570 SourceLocation AttrLoc = AttrRange.getBegin();
1571
1572 if (!isValidPointerAttrType(ResultType, /* RefOkay */ true)) {
1573 Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only)
1574 << &TmpAttr << AttrRange << SR;
1575 return;
1576 }
1577
1578 if (!E->isValueDependent()) {
1579 llvm::APSInt I(64);
1580 if (!E->isIntegerConstantExpr(I, Context)) {
1581 if (OE)
1582 Diag(AttrLoc, diag::err_attribute_argument_n_type)
1583 << &TmpAttr << 1 << AANT_ArgumentIntegerConstant
1584 << E->getSourceRange();
1585 else
1586 Diag(AttrLoc, diag::err_attribute_argument_type)
1587 << &TmpAttr << AANT_ArgumentIntegerConstant
1588 << E->getSourceRange();
1589 return;
1590 }
1591
1592 if (!I.isPowerOf2()) {
1593 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
1594 << E->getSourceRange();
1595 return;
1596 }
1597 }
1598
1599 if (OE) {
1600 if (!OE->isValueDependent()) {
1601 llvm::APSInt I(64);
1602 if (!OE->isIntegerConstantExpr(I, Context)) {
1603 Diag(AttrLoc, diag::err_attribute_argument_n_type)
1604 << &TmpAttr << 2 << AANT_ArgumentIntegerConstant
1605 << OE->getSourceRange();
1606 return;
1607 }
1608 }
1609 }
1610
1611 D->addAttr(::new (Context)
1612 AssumeAlignedAttr(AttrRange, Context, E, OE, SpellingListIndex));
1613}
1614
Erich Keane623efd82017-03-30 21:48:55 +00001615void Sema::AddAllocAlignAttr(SourceRange AttrRange, Decl *D, Expr *ParamExpr,
1616 unsigned SpellingListIndex) {
1617 QualType ResultType = getFunctionOrMethodResultType(D);
1618
1619 AllocAlignAttr TmpAttr(AttrRange, Context, 0, SpellingListIndex);
1620 SourceLocation AttrLoc = AttrRange.getBegin();
1621
1622 if (!ResultType->isDependentType() &&
1623 !isValidPointerAttrType(ResultType, /* RefOkay */ true)) {
1624 Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only)
1625 << &TmpAttr << AttrRange << getFunctionOrMethodResultSourceRange(D);
1626 return;
1627 }
1628
1629 uint64_t IndexVal;
1630 const auto *FuncDecl = cast<FunctionDecl>(D);
1631 if (!checkFunctionOrMethodParameterIndex(*this, FuncDecl, TmpAttr,
1632 /*AttrArgNo=*/1, ParamExpr,
1633 IndexVal))
1634 return;
1635
1636 QualType Ty = getFunctionOrMethodParamType(D, IndexVal);
1637 if (!Ty->isDependentType() && !Ty->isIntegralType(Context)) {
1638 Diag(ParamExpr->getLocStart(), diag::err_attribute_integers_only)
1639 << &TmpAttr << FuncDecl->getParamDecl(IndexVal)->getSourceRange();
1640 return;
1641 }
1642
1643 // We cannot use the Idx returned from checkFunctionOrMethodParameterIndex
1644 // because that has corrected for the implicit this parameter, and is zero-
1645 // based. The attribute expects what the user wrote explicitly.
1646 llvm::APSInt Val;
1647 ParamExpr->EvaluateAsInt(Val, Context);
1648
1649 D->addAttr(::new (Context) AllocAlignAttr(
1650 AttrRange, Context, Val.getZExtValue(), SpellingListIndex));
1651}
1652
Aaron Ballman8b5e7ba2015-10-08 19:24:08 +00001653/// Normalize the attribute, __foo__ becomes foo.
1654/// Returns true if normalization was applied.
1655static bool normalizeName(StringRef &AttrName) {
Aaron Ballman62692362015-10-09 13:53:24 +00001656 if (AttrName.size() > 4 && AttrName.startswith("__") &&
1657 AttrName.endswith("__")) {
Aaron Ballman8b5e7ba2015-10-08 19:24:08 +00001658 AttrName = AttrName.drop_front(2).drop_back(2);
1659 return true;
1660 }
1661 return false;
1662}
1663
Chandler Carruthedc2c642011-07-02 00:01:44 +00001664static void handleOwnershipAttr(Sema &S, Decl *D, const AttributeList &AL) {
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001665 // This attribute must be applied to a function declaration. The first
1666 // argument to the attribute must be an identifier, the name of the resource,
1667 // for example: malloc. The following arguments must be argument indexes, the
1668 // arguments must be of integer type for Returns, otherwise of pointer type.
Ted Kremenekd21139a2010-07-31 01:52:11 +00001669 // The difference between Holds and Takes is that a pointer may still be used
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001670 // after being held. free() should be __attribute((ownership_takes)), whereas
Jordy Rose5af0e3c2010-08-12 08:54:03 +00001671 // a list append function may well be __attribute((ownership_holds)).
Ted Kremenekd21139a2010-07-31 01:52:11 +00001672
Aaron Ballman00e99962013-08-31 01:11:41 +00001673 if (!AL.isArgIdent(0)) {
Aaron Ballman29982272013-07-23 14:03:57 +00001674 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001675 << AL.getName() << 1 << AANT_ArgumentIdentifier;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001676 return;
1677 }
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001678
Richard Smith852e9ce2013-11-27 01:46:48 +00001679 // Figure out our Kind.
1680 OwnershipAttr::OwnershipKind K =
Craig Topperc3ec1492014-05-26 06:22:03 +00001681 OwnershipAttr(AL.getLoc(), S.Context, nullptr, nullptr, 0,
Richard Smith852e9ce2013-11-27 01:46:48 +00001682 AL.getAttributeSpellingListIndex()).getOwnKind();
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001683
Richard Smith852e9ce2013-11-27 01:46:48 +00001684 // Check arguments.
1685 switch (K) {
1686 case OwnershipAttr::Takes:
1687 case OwnershipAttr::Holds:
1688 if (AL.getNumArgs() < 2) {
Aaron Ballman05e420a2014-01-02 21:26:14 +00001689 S.Diag(AL.getLoc(), diag::err_attribute_too_few_arguments)
1690 << AL.getName() << 2;
Richard Smith852e9ce2013-11-27 01:46:48 +00001691 return;
1692 }
1693 break;
1694 case OwnershipAttr::Returns:
Aaron Ballman00e99962013-08-31 01:11:41 +00001695 if (AL.getNumArgs() > 2) {
Aaron Ballman05e420a2014-01-02 21:26:14 +00001696 S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments)
1697 << AL.getName() << 1;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001698 return;
1699 }
Jordy Rose5af0e3c2010-08-12 08:54:03 +00001700 break;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001701 }
1702
Richard Smith852e9ce2013-11-27 01:46:48 +00001703 IdentifierInfo *Module = AL.getArgAsIdent(0)->Ident;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001704
Richard Smith852e9ce2013-11-27 01:46:48 +00001705 StringRef ModuleName = Module->getName();
Aaron Ballman8b5e7ba2015-10-08 19:24:08 +00001706 if (normalizeName(ModuleName)) {
Richard Smith852e9ce2013-11-27 01:46:48 +00001707 Module = &S.PP.getIdentifierTable().get(ModuleName);
1708 }
Ted Kremenekd21139a2010-07-31 01:52:11 +00001709
Aaron Ballmanbe50eb82013-07-30 00:48:57 +00001710 SmallVector<unsigned, 8> OwnershipArgs;
Aaron Ballman00e99962013-08-31 01:11:41 +00001711 for (unsigned i = 1; i < AL.getNumArgs(); ++i) {
1712 Expr *Ex = AL.getArgAsExpr(i);
Aaron Ballmanbe50eb82013-07-30 00:48:57 +00001713 uint64_t Idx;
Alp Toker601b22c2014-01-21 23:35:24 +00001714 if (!checkFunctionOrMethodParameterIndex(S, D, AL, i, Ex, Idx))
Aaron Ballmanbe50eb82013-07-30 00:48:57 +00001715 return;
Chandler Carruth743682b2010-11-16 08:35:43 +00001716
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001717 // Is the function argument a pointer type?
Alp Toker601b22c2014-01-21 23:35:24 +00001718 QualType T = getFunctionOrMethodParamType(D, Idx);
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001719 int Err = -1; // No error
Ted Kremenekd21139a2010-07-31 01:52:11 +00001720 switch (K) {
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001721 case OwnershipAttr::Takes:
1722 case OwnershipAttr::Holds:
1723 if (!T->isAnyPointerType() && !T->isBlockPointerType())
1724 Err = 0;
1725 break;
1726 case OwnershipAttr::Returns:
1727 if (!T->isIntegerType())
1728 Err = 1;
1729 break;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001730 }
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001731 if (-1 != Err) {
Fariborz Jahanian8a5e9472013-09-19 16:37:20 +00001732 S.Diag(AL.getLoc(), diag::err_ownership_type) << AL.getName() << Err
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001733 << Ex->getSourceRange();
1734 return;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001735 }
Ted Kremenekd21139a2010-07-31 01:52:11 +00001736
1737 // Check we don't have a conflict with another ownership attribute.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001738 for (const auto *I : D->specific_attrs<OwnershipAttr>()) {
Aaron Ballmanef7aef82014-07-31 20:44:26 +00001739 // Cannot have two ownership attributes of different kinds for the same
1740 // index.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001741 if (I->getOwnKind() != K && I->args_end() !=
1742 std::find(I->args_begin(), I->args_end(), Idx)) {
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001743 S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001744 << AL.getName() << I;
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001745 return;
Aaron Ballmanef7aef82014-07-31 20:44:26 +00001746 } else if (K == OwnershipAttr::Returns &&
1747 I->getOwnKind() == OwnershipAttr::Returns) {
1748 // A returns attribute conflicts with any other returns attribute using
1749 // a different index. Note, diagnostic reporting is 1-based, but stored
1750 // argument indexes are 0-based.
1751 if (std::find(I->args_begin(), I->args_end(), Idx) == I->args_end()) {
1752 S.Diag(I->getLocation(), diag::err_ownership_returns_index_mismatch)
1753 << *(I->args_begin()) + 1;
1754 if (I->args_size())
1755 S.Diag(AL.getLoc(), diag::note_ownership_returns_index_mismatch)
1756 << (unsigned)Idx + 1 << Ex->getSourceRange();
1757 return;
1758 }
Ted Kremenekd21139a2010-07-31 01:52:11 +00001759 }
1760 }
Aaron Ballmanbe50eb82013-07-30 00:48:57 +00001761 OwnershipArgs.push_back(Idx);
Ted Kremenekd21139a2010-07-31 01:52:11 +00001762 }
1763
1764 unsigned* start = OwnershipArgs.data();
1765 unsigned size = OwnershipArgs.size();
1766 llvm::array_pod_sort(start, start + size);
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001767
Michael Han99315932013-01-24 16:46:58 +00001768 D->addAttr(::new (S.Context)
Richard Smith852e9ce2013-11-27 01:46:48 +00001769 OwnershipAttr(AL.getLoc(), S.Context, Module, start, size,
Michael Han99315932013-01-24 16:46:58 +00001770 AL.getAttributeSpellingListIndex()));
Ted Kremenekd21139a2010-07-31 01:52:11 +00001771}
1772
Chandler Carruthedc2c642011-07-02 00:01:44 +00001773static void handleWeakRefAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Rafael Espindolac18086a2010-02-23 22:00:30 +00001774 // Check the attribute arguments.
1775 if (Attr.getNumArgs() > 1) {
Aaron Ballmanb7243382013-07-23 19:30:11 +00001776 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
1777 << Attr.getName() << 1;
Rafael Espindolac18086a2010-02-23 22:00:30 +00001778 return;
1779 }
1780
Chandler Carruthff4c4f02011-07-01 23:49:12 +00001781 NamedDecl *nd = cast<NamedDecl>(D);
John McCall7a198ce2011-02-08 22:35:49 +00001782
Rafael Espindolac18086a2010-02-23 22:00:30 +00001783 // gcc rejects
1784 // class c {
1785 // static int a __attribute__((weakref ("v2")));
1786 // static int b() __attribute__((weakref ("f3")));
1787 // };
1788 // and ignores the attributes of
1789 // void f(void) {
1790 // static int a __attribute__((weakref ("v2")));
1791 // }
1792 // we reject them
Chandler Carruthff4c4f02011-07-01 23:49:12 +00001793 const DeclContext *Ctx = D->getDeclContext()->getRedeclContext();
Sebastian Redl50c68252010-08-31 00:36:30 +00001794 if (!Ctx->isFileContext()) {
Aaron Ballman9f6fec42014-01-02 23:02:01 +00001795 S.Diag(Attr.getLoc(), diag::err_attribute_weakref_not_global_context)
1796 << nd;
Sebastian Redl50c68252010-08-31 00:36:30 +00001797 return;
Rafael Espindolac18086a2010-02-23 22:00:30 +00001798 }
1799
1800 // The GCC manual says
1801 //
1802 // At present, a declaration to which `weakref' is attached can only
1803 // be `static'.
1804 //
1805 // It also says
1806 //
1807 // Without a TARGET,
1808 // given as an argument to `weakref' or to `alias', `weakref' is
1809 // equivalent to `weak'.
1810 //
1811 // gcc 4.4.1 will accept
1812 // int a7 __attribute__((weakref));
1813 // as
1814 // int a7 __attribute__((weak));
1815 // This looks like a bug in gcc. We reject that for now. We should revisit
1816 // it if this behaviour is actually used.
1817
Rafael Espindolac18086a2010-02-23 22:00:30 +00001818 // GCC rejects
1819 // static ((alias ("y"), weakref)).
1820 // Should we? How to check that weakref is before or after alias?
1821
Aaron Ballmanfebff0c2013-09-09 23:40:31 +00001822 // FIXME: it would be good for us to keep the WeakRefAttr as-written instead
1823 // of transforming it into an AliasAttr. The WeakRefAttr never uses the
1824 // StringRef parameter it was given anyway.
Aaron Ballman3b1dde62013-09-13 19:35:18 +00001825 StringRef Str;
Tim Northover6a6b63b2013-10-01 14:34:18 +00001826 if (Attr.getNumArgs() && S.checkStringLiteralArgumentAttr(Attr, 0, Str))
Rafael Espindolac18086a2010-02-23 22:00:30 +00001827 // GCC will accept anything as the argument of weakref. Should we
1828 // check for an existing decl?
Aaron Ballman3b1dde62013-09-13 19:35:18 +00001829 D->addAttr(::new (S.Context) AliasAttr(Attr.getRange(), S.Context, Str,
1830 Attr.getAttributeSpellingListIndex()));
Rafael Espindolac18086a2010-02-23 22:00:30 +00001831
Michael Han99315932013-01-24 16:46:58 +00001832 D->addAttr(::new (S.Context)
1833 WeakRefAttr(Attr.getRange(), S.Context,
1834 Attr.getAttributeSpellingListIndex()));
Rafael Espindolac18086a2010-02-23 22:00:30 +00001835}
1836
Dmitry Polukhin85eda122016-04-11 07:48:59 +00001837static void handleIFuncAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1838 StringRef Str;
1839 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str))
1840 return;
1841
1842 // Aliases should be on declarations, not definitions.
1843 const auto *FD = cast<FunctionDecl>(D);
1844 if (FD->isThisDeclarationADefinition()) {
1845 S.Diag(Attr.getLoc(), diag::err_alias_is_definition) << FD << 1;
1846 return;
1847 }
1848 // FIXME: it should be handled as a target specific attribute.
1849 if (S.Context.getTargetInfo().getTriple().getObjectFormat() !=
1850 llvm::Triple::ELF) {
1851 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
1852 return;
1853 }
1854
1855 D->addAttr(::new (S.Context) IFuncAttr(Attr.getRange(), S.Context, Str,
1856 Attr.getAttributeSpellingListIndex()));
1857}
1858
Benjamin Kramer6ee15622013-09-13 15:35:43 +00001859static void handleAliasAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1860 StringRef Str;
Tim Northover6a6b63b2013-10-01 14:34:18 +00001861 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str))
Benjamin Kramer6ee15622013-09-13 15:35:43 +00001862 return;
1863
Douglas Gregore8bbc122011-09-02 00:18:52 +00001864 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Rafael Espindola0017c5f2010-12-07 15:23:23 +00001865 S.Diag(Attr.getLoc(), diag::err_alias_not_supported_on_darwin);
1866 return;
1867 }
Justin Lebara8f0254b2016-01-23 21:28:10 +00001868 if (S.Context.getTargetInfo().getTriple().isNVPTX()) {
1869 S.Diag(Attr.getLoc(), diag::err_alias_not_supported_on_nvptx);
1870 }
Rafael Espindola0017c5f2010-12-07 15:23:23 +00001871
David Majnemer2dc81462015-01-19 09:00:28 +00001872 // Aliases should be on declarations, not definitions.
1873 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
1874 if (FD->isThisDeclarationADefinition()) {
Dmitry Polukhin85eda122016-04-11 07:48:59 +00001875 S.Diag(Attr.getLoc(), diag::err_alias_is_definition) << FD << 0;
David Majnemer2dc81462015-01-19 09:00:28 +00001876 return;
1877 }
1878 } else {
1879 const auto *VD = cast<VarDecl>(D);
1880 if (VD->isThisDeclarationADefinition() && VD->isExternallyVisible()) {
Dmitry Polukhin85eda122016-04-11 07:48:59 +00001881 S.Diag(Attr.getLoc(), diag::err_alias_is_definition) << VD << 0;
David Majnemer2dc81462015-01-19 09:00:28 +00001882 return;
1883 }
1884 }
1885
Chris Lattner2c6fcf52008-06-26 18:38:35 +00001886 // FIXME: check if target symbol exists in current file
Mike Stumpd3bb5572009-07-24 19:02:52 +00001887
Benjamin Kramer6ee15622013-09-13 15:35:43 +00001888 D->addAttr(::new (S.Context) AliasAttr(Attr.getRange(), S.Context, Str,
Michael Han99315932013-01-24 16:46:58 +00001889 Attr.getAttributeSpellingListIndex()));
Chris Lattner2c6fcf52008-06-26 18:38:35 +00001890}
1891
Benjamin Kramer29c2b432012-05-12 21:10:52 +00001892static void handleColdAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00001893 if (checkAttrMutualExclusion<HotAttr>(S, D, Attr.getRange(), Attr.getName()))
Benjamin Kramer29c2b432012-05-12 21:10:52 +00001894 return;
Benjamin Kramer29c2b432012-05-12 21:10:52 +00001895
Michael Han99315932013-01-24 16:46:58 +00001896 D->addAttr(::new (S.Context) ColdAttr(Attr.getRange(), S.Context,
1897 Attr.getAttributeSpellingListIndex()));
Benjamin Kramer29c2b432012-05-12 21:10:52 +00001898}
1899
1900static void handleHotAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00001901 if (checkAttrMutualExclusion<ColdAttr>(S, D, Attr.getRange(), Attr.getName()))
Benjamin Kramer29c2b432012-05-12 21:10:52 +00001902 return;
Benjamin Kramer29c2b432012-05-12 21:10:52 +00001903
Michael Han99315932013-01-24 16:46:58 +00001904 D->addAttr(::new (S.Context) HotAttr(Attr.getRange(), S.Context,
1905 Attr.getAttributeSpellingListIndex()));
Benjamin Kramer29c2b432012-05-12 21:10:52 +00001906}
1907
Hans Wennborgd3b01bc2012-06-23 11:51:46 +00001908static void handleTLSModelAttr(Sema &S, Decl *D,
1909 const AttributeList &Attr) {
Benjamin Kramer6ee15622013-09-13 15:35:43 +00001910 StringRef Model;
1911 SourceLocation LiteralLoc;
Hans Wennborgd3b01bc2012-06-23 11:51:46 +00001912 // Check that it is a string.
Tim Northover6a6b63b2013-10-01 14:34:18 +00001913 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Model, &LiteralLoc))
Hans Wennborgd3b01bc2012-06-23 11:51:46 +00001914 return;
Hans Wennborgd3b01bc2012-06-23 11:51:46 +00001915
Hans Wennborgd3b01bc2012-06-23 11:51:46 +00001916 // Check that the value.
Hans Wennborgd3b01bc2012-06-23 11:51:46 +00001917 if (Model != "global-dynamic" && Model != "local-dynamic"
1918 && Model != "initial-exec" && Model != "local-exec") {
Benjamin Kramer6ee15622013-09-13 15:35:43 +00001919 S.Diag(LiteralLoc, diag::err_attr_tlsmodel_arg);
Hans Wennborgd3b01bc2012-06-23 11:51:46 +00001920 return;
1921 }
1922
Michael Han99315932013-01-24 16:46:58 +00001923 D->addAttr(::new (S.Context)
1924 TLSModelAttr(Attr.getRange(), S.Context, Model,
1925 Attr.getAttributeSpellingListIndex()));
Hans Wennborgd3b01bc2012-06-23 11:51:46 +00001926}
1927
David Majnemer631a90b2015-02-04 07:23:21 +00001928static void handleRestrictAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1929 QualType ResultType = getFunctionOrMethodResultType(D);
1930 if (ResultType->isAnyPointerType() || ResultType->isBlockPointerType()) {
1931 D->addAttr(::new (S.Context) RestrictAttr(
1932 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
1933 return;
Ryan Flynn1f1fdc02009-08-09 20:07:29 +00001934 }
1935
David Majnemer631a90b2015-02-04 07:23:21 +00001936 S.Diag(Attr.getLoc(), diag::warn_attribute_return_pointers_only)
1937 << Attr.getName() << getFunctionOrMethodResultSourceRange(D);
Ryan Flynn1f1fdc02009-08-09 20:07:29 +00001938}
1939
Chandler Carruthedc2c642011-07-02 00:01:44 +00001940static void handleCommonAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Eli Friedman6fc7ad12013-06-20 22:55:04 +00001941 if (S.LangOpts.CPlusPlus) {
Aaron Ballman3db89662013-11-24 21:48:06 +00001942 S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang)
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00001943 << Attr.getName() << AttributeLangSupport::Cpp;
Eli Friedman6fc7ad12013-06-20 22:55:04 +00001944 return;
1945 }
1946
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00001947 if (CommonAttr *CA = S.mergeCommonAttr(D, Attr.getRange(), Attr.getName(),
1948 Attr.getAttributeSpellingListIndex()))
1949 D->addAttr(CA);
Eric Christopher8a2ee392010-12-02 02:45:55 +00001950}
1951
Charles Davis0e379112016-08-08 21:19:08 +00001952static void handleNakedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1953 if (checkAttrMutualExclusion<DisableTailCallsAttr>(S, D, Attr.getRange(),
1954 Attr.getName()))
1955 return;
1956
Saleem Abdulrasoolb51bcaf2017-04-07 15:13:47 +00001957 if (Attr.isDeclspecAttribute()) {
1958 const auto &Triple = S.getASTContext().getTargetInfo().getTriple();
1959 const auto &Arch = Triple.getArch();
1960 if (Arch != llvm::Triple::x86 &&
1961 (Arch != llvm::Triple::arm && Arch != llvm::Triple::thumb)) {
1962 S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_on_arch)
1963 << Attr.getName() << Triple.getArchName();
1964 return;
1965 }
1966 }
1967
Charles Davis0e379112016-08-08 21:19:08 +00001968 D->addAttr(::new (S.Context) NakedAttr(Attr.getRange(), S.Context,
1969 Attr.getAttributeSpellingListIndex()));
1970}
1971
Erich Keaneb11ebc52017-09-27 03:20:13 +00001972static void handleNoReturnAttr(Sema &S, Decl *D, const AttributeList &Attrs) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00001973 if (hasDeclarator(D)) return;
John McCall3882ace2011-01-05 12:14:39 +00001974
Erich Keaneb11ebc52017-09-27 03:20:13 +00001975 if (S.CheckNoReturnAttr(Attrs))
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +00001976 return;
John McCall3882ace2011-01-05 12:14:39 +00001977
Chandler Carruthff4c4f02011-07-01 23:49:12 +00001978 if (!isa<ObjCMethodDecl>(D)) {
Erich Keaneb11ebc52017-09-27 03:20:13 +00001979 S.Diag(Attrs.getLoc(), diag::warn_attribute_wrong_decl_type)
1980 << Attrs.getName() << ExpectedFunctionOrMethod;
John McCall3882ace2011-01-05 12:14:39 +00001981 return;
1982 }
1983
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +00001984 D->addAttr(::new (S.Context) NoReturnAttr(
Erich Keaneb11ebc52017-09-27 03:20:13 +00001985 Attrs.getRange(), S.Context, Attrs.getAttributeSpellingListIndex()));
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +00001986}
1987
1988static void handleNoCallerSavedRegsAttr(Sema &S, Decl *D,
1989 const AttributeList &Attr) {
1990 if (S.CheckNoCallerSavedRegsAttr(Attr))
1991 return;
1992
1993 D->addAttr(::new (S.Context) AnyX86NoCallerSavedRegistersAttr(
1994 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
John McCall3882ace2011-01-05 12:14:39 +00001995}
1996
Erich Keaneb11ebc52017-09-27 03:20:13 +00001997bool Sema::CheckNoReturnAttr(const AttributeList &Attrs) {
1998 if (!checkAttributeNumArgs(*this, Attrs, 0)) {
1999 Attrs.setInvalid();
John McCall3882ace2011-01-05 12:14:39 +00002000 return true;
2001 }
2002
2003 return false;
Ted Kremenek40f4ee72009-04-10 00:01:14 +00002004}
2005
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +00002006bool Sema::CheckNoCallerSavedRegsAttr(const AttributeList &Attr) {
2007 // Check whether the attribute is valid on the current target.
2008 if (!Attr.existsInTarget(Context.getTargetInfo())) {
2009 Diag(Attr.getLoc(), diag::warn_unknown_attribute_ignored) << Attr.getName();
2010 Attr.setInvalid();
2011 return true;
2012 }
2013
2014 if (!checkAttributeNumArgs(*this, Attr, 0)) {
2015 Attr.setInvalid();
2016 return true;
2017 }
2018
2019 return false;
2020}
2021
Chandler Carruthedc2c642011-07-02 00:01:44 +00002022static void handleAnalyzerNoReturnAttr(Sema &S, Decl *D,
2023 const AttributeList &Attr) {
Ted Kremenek5295ce82010-08-19 00:51:58 +00002024
2025 // The checking path for 'noreturn' and 'analyzer_noreturn' are different
2026 // because 'analyzer_noreturn' does not impact the type.
David Majnemer06864812015-04-07 06:01:53 +00002027 if (!isFunctionOrMethodOrBlock(D)) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00002028 ValueDecl *VD = dyn_cast<ValueDecl>(D);
Craig Topperc3ec1492014-05-26 06:22:03 +00002029 if (!VD || (!VD->getType()->isBlockPointerType() &&
2030 !VD->getType()->isFunctionPointerType())) {
Ted Kremenek5295ce82010-08-19 00:51:58 +00002031 S.Diag(Attr.getLoc(),
Richard Smith89645bc2013-01-02 12:01:23 +00002032 Attr.isCXX11Attribute() ? diag::err_attribute_wrong_decl_type
Craig Topper8f7f3ea2015-11-17 05:40:05 +00002033 : diag::warn_attribute_wrong_decl_type)
John McCall5fca7ea2011-03-02 12:29:23 +00002034 << Attr.getName() << ExpectedFunctionMethodOrBlock;
Ted Kremenek5295ce82010-08-19 00:51:58 +00002035 return;
2036 }
2037 }
2038
Michael Han99315932013-01-24 16:46:58 +00002039 D->addAttr(::new (S.Context)
2040 AnalyzerNoReturnAttr(Attr.getRange(), S.Context,
2041 Attr.getAttributeSpellingListIndex()));
Chris Lattner2c6fcf52008-06-26 18:38:35 +00002042}
2043
John Thompsoncdb847ba2010-08-09 21:53:52 +00002044// PS3 PPU-specific.
Chandler Carruthedc2c642011-07-02 00:01:44 +00002045static void handleVecReturnAttr(Sema &S, Decl *D, const AttributeList &Attr) {
John Thompsoncdb847ba2010-08-09 21:53:52 +00002046/*
2047 Returning a Vector Class in Registers
2048
Eric Christopherbc638a82010-12-01 22:13:54 +00002049 According to the PPU ABI specifications, a class with a single member of
2050 vector type is returned in memory when used as the return value of a function.
2051 This results in inefficient code when implementing vector classes. To return
2052 the value in a single vector register, add the vecreturn attribute to the
2053 class definition. This attribute is also applicable to struct types.
John Thompsoncdb847ba2010-08-09 21:53:52 +00002054
2055 Example:
2056
2057 struct Vector
2058 {
2059 __vector float xyzw;
2060 } __attribute__((vecreturn));
2061
2062 Vector Add(Vector lhs, Vector rhs)
2063 {
2064 Vector result;
2065 result.xyzw = vec_add(lhs.xyzw, rhs.xyzw);
2066 return result; // This will be returned in a register
2067 }
2068*/
Aaron Ballman3e424b52013-12-26 18:30:57 +00002069 if (VecReturnAttr *A = D->getAttr<VecReturnAttr>()) {
2070 S.Diag(Attr.getLoc(), diag::err_repeat_attribute) << A;
John Thompsoncdb847ba2010-08-09 21:53:52 +00002071 return;
2072 }
2073
Chandler Carruthff4c4f02011-07-01 23:49:12 +00002074 RecordDecl *record = cast<RecordDecl>(D);
John Thompson9a587aaa2010-09-18 01:12:07 +00002075 int count = 0;
2076
2077 if (!isa<CXXRecordDecl>(record)) {
2078 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
2079 return;
2080 }
2081
2082 if (!cast<CXXRecordDecl>(record)->isPOD()) {
2083 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_pod_record);
2084 return;
2085 }
2086
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00002087 for (const auto *I : record->fields()) {
2088 if ((count == 1) || !I->getType()->isVectorType()) {
John Thompson9a587aaa2010-09-18 01:12:07 +00002089 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
2090 return;
2091 }
2092 count++;
2093 }
2094
Michael Han99315932013-01-24 16:46:58 +00002095 D->addAttr(::new (S.Context)
2096 VecReturnAttr(Attr.getRange(), S.Context,
2097 Attr.getAttributeSpellingListIndex()));
John Thompsoncdb847ba2010-08-09 21:53:52 +00002098}
2099
Richard Smithe233fbf2013-01-28 22:42:45 +00002100static void handleDependencyAttr(Sema &S, Scope *Scope, Decl *D,
2101 const AttributeList &Attr) {
2102 if (isa<ParmVarDecl>(D)) {
2103 // [[carries_dependency]] can only be applied to a parameter if it is a
2104 // parameter of a function declaration or lambda.
2105 if (!(Scope->getFlags() & clang::Scope::FunctionDeclarationScope)) {
2106 S.Diag(Attr.getLoc(),
2107 diag::err_carries_dependency_param_not_function_decl);
2108 return;
2109 }
Alexis Hunt96d5c762009-11-21 08:43:09 +00002110 }
Richard Smithe233fbf2013-01-28 22:42:45 +00002111
2112 D->addAttr(::new (S.Context) CarriesDependencyAttr(
2113 Attr.getRange(), S.Context,
2114 Attr.getAttributeSpellingListIndex()));
Alexis Hunt96d5c762009-11-21 08:43:09 +00002115}
2116
Akira Hatanakac8667622015-11-06 23:56:15 +00002117static void handleNotTailCalledAttr(Sema &S, Decl *D,
2118 const AttributeList &Attr) {
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00002119 if (checkAttrMutualExclusion<AlwaysInlineAttr>(S, D, Attr.getRange(),
2120 Attr.getName()))
Akira Hatanakac8667622015-11-06 23:56:15 +00002121 return;
2122
2123 D->addAttr(::new (S.Context) NotTailCalledAttr(
2124 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
2125}
2126
Akira Hatanaka7828b1e2015-11-13 00:42:21 +00002127static void handleDisableTailCallsAttr(Sema &S, Decl *D,
2128 const AttributeList &Attr) {
2129 if (checkAttrMutualExclusion<NakedAttr>(S, D, Attr.getRange(),
2130 Attr.getName()))
2131 return;
2132
2133 D->addAttr(::new (S.Context) DisableTailCallsAttr(
2134 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
2135}
2136
Chandler Carruthedc2c642011-07-02 00:01:44 +00002137static void handleUsedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00002138 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Rafael Espindola87198cd2013-08-16 23:18:50 +00002139 if (VD->hasLocalStorage()) {
Aaron Ballman88fe3222013-12-26 17:30:44 +00002140 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
Daniel Dunbarfee07a02009-02-13 19:23:53 +00002141 return;
2142 }
Chandler Carruthff4c4f02011-07-01 23:49:12 +00002143 } else if (!isFunctionOrMethod(D)) {
Daniel Dunbarfee07a02009-02-13 19:23:53 +00002144 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
John McCall5fca7ea2011-03-02 12:29:23 +00002145 << Attr.getName() << ExpectedVariableOrFunction;
Daniel Dunbarfee07a02009-02-13 19:23:53 +00002146 return;
2147 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00002148
Michael Han99315932013-01-24 16:46:58 +00002149 D->addAttr(::new (S.Context)
2150 UsedAttr(Attr.getRange(), S.Context,
2151 Attr.getAttributeSpellingListIndex()));
Daniel Dunbarfee07a02009-02-13 19:23:53 +00002152}
2153
Aaron Ballman0bcd6c12016-03-09 16:48:08 +00002154static void handleUnusedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2155 bool IsCXX1zAttr = Attr.isCXX11Attribute() && !Attr.getScopeName();
2156
2157 if (IsCXX1zAttr && isa<VarDecl>(D)) {
2158 // The C++1z spelling of this attribute cannot be applied to a static data
2159 // member per [dcl.attr.unused]p2.
2160 if (cast<VarDecl>(D)->isStaticDataMember()) {
2161 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2162 << Attr.getName() << ExpectedForMaybeUnused;
2163 return;
2164 }
2165 }
2166
2167 // If this is spelled as the standard C++1z attribute, but not in C++1z, warn
2168 // about using it as an extension.
2169 if (!S.getLangOpts().CPlusPlus1z && IsCXX1zAttr)
Richard Smithb115e5d2017-08-13 23:37:29 +00002170 S.Diag(Attr.getLoc(), diag::ext_cxx17_attr) << Attr.getName();
Aaron Ballman0bcd6c12016-03-09 16:48:08 +00002171
2172 D->addAttr(::new (S.Context) UnusedAttr(
2173 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
2174}
2175
Chandler Carruthedc2c642011-07-02 00:01:44 +00002176static void handleConstructorAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00002177 uint32_t priority = ConstructorAttr::DefaultPriority;
Aaron Ballman8ed8dbd2014-07-31 16:37:04 +00002178 if (Attr.getNumArgs() &&
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00002179 !checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), priority))
2180 return;
Mike Stumpd3bb5572009-07-24 19:02:52 +00002181
Michael Han99315932013-01-24 16:46:58 +00002182 D->addAttr(::new (S.Context)
2183 ConstructorAttr(Attr.getRange(), S.Context, priority,
2184 Attr.getAttributeSpellingListIndex()));
Daniel Dunbar032db472008-07-31 22:40:48 +00002185}
2186
Chandler Carruthedc2c642011-07-02 00:01:44 +00002187static void handleDestructorAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballmanf28e4992014-01-20 15:22:57 +00002188 uint32_t priority = DestructorAttr::DefaultPriority;
Aaron Ballman8ed8dbd2014-07-31 16:37:04 +00002189 if (Attr.getNumArgs() &&
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00002190 !checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), priority))
2191 return;
Mike Stumpd3bb5572009-07-24 19:02:52 +00002192
Michael Han99315932013-01-24 16:46:58 +00002193 D->addAttr(::new (S.Context)
2194 DestructorAttr(Attr.getRange(), S.Context, priority,
2195 Attr.getAttributeSpellingListIndex()));
Daniel Dunbar032db472008-07-31 22:40:48 +00002196}
2197
Benjamin Kramerf435ab42012-05-16 12:19:08 +00002198template <typename AttrTy>
Aaron Ballman8b8ebdd2013-07-18 13:13:52 +00002199static void handleAttrWithMessage(Sema &S, Decl *D,
2200 const AttributeList &Attr) {
Benjamin Kramerf435ab42012-05-16 12:19:08 +00002201 // Handle the case where the attribute has a text message.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002202 StringRef Str;
Aaron Ballman8ed8dbd2014-07-31 16:37:04 +00002203 if (Attr.getNumArgs() == 1 && !S.checkStringLiteralArgumentAttr(Attr, 0, Str))
Benjamin Kramer6ee15622013-09-13 15:35:43 +00002204 return;
Mike Stumpd3bb5572009-07-24 19:02:52 +00002205
Michael Han99315932013-01-24 16:46:58 +00002206 D->addAttr(::new (S.Context) AttrTy(Attr.getRange(), S.Context, Str,
2207 Attr.getAttributeSpellingListIndex()));
Fariborz Jahanian1470e932008-12-17 01:07:27 +00002208}
2209
Ted Kremenek438f8db2014-02-22 01:06:05 +00002210static void handleObjCSuppresProtocolAttr(Sema &S, Decl *D,
Ted Kremenek28eace62013-11-23 01:01:34 +00002211 const AttributeList &Attr) {
Ted Kremenek438f8db2014-02-22 01:06:05 +00002212 if (!cast<ObjCProtocolDecl>(D)->isThisDeclarationADefinition()) {
Ted Kremenek27cfe102014-02-21 22:49:04 +00002213 S.Diag(Attr.getLoc(), diag::err_objc_attr_protocol_requires_definition)
2214 << Attr.getName() << Attr.getRange();
2215 return;
2216 }
2217
Ted Kremenek28eace62013-11-23 01:01:34 +00002218 D->addAttr(::new (S.Context)
Ted Kremenekf41cf7f12013-12-10 19:43:48 +00002219 ObjCExplicitProtocolImplAttr(Attr.getRange(), S.Context,
2220 Attr.getAttributeSpellingListIndex()));
Ted Kremenek28eace62013-11-23 01:01:34 +00002221}
2222
Jordy Rose740b0c22012-05-08 03:27:22 +00002223static bool checkAvailabilityAttr(Sema &S, SourceRange Range,
2224 IdentifierInfo *Platform,
2225 VersionTuple Introduced,
2226 VersionTuple Deprecated,
2227 VersionTuple Obsoleted) {
Rafael Espindola2d243bf2012-05-06 19:56:25 +00002228 StringRef PlatformName
2229 = AvailabilityAttr::getPrettyPlatformName(Platform->getName());
2230 if (PlatformName.empty())
2231 PlatformName = Platform->getName();
2232
2233 // Ensure that Introduced <= Deprecated <= Obsoleted (although not all
2234 // of these steps are needed).
2235 if (!Introduced.empty() && !Deprecated.empty() &&
2236 !(Introduced <= Deprecated)) {
2237 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2238 << 1 << PlatformName << Deprecated.getAsString()
2239 << 0 << Introduced.getAsString();
2240 return true;
2241 }
2242
2243 if (!Introduced.empty() && !Obsoleted.empty() &&
2244 !(Introduced <= Obsoleted)) {
2245 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2246 << 2 << PlatformName << Obsoleted.getAsString()
2247 << 0 << Introduced.getAsString();
2248 return true;
2249 }
2250
2251 if (!Deprecated.empty() && !Obsoleted.empty() &&
2252 !(Deprecated <= Obsoleted)) {
2253 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2254 << 2 << PlatformName << Obsoleted.getAsString()
2255 << 1 << Deprecated.getAsString();
2256 return true;
2257 }
2258
2259 return false;
2260}
2261
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002262/// \brief Check whether the two versions match.
2263///
2264/// If either version tuple is empty, then they are assumed to match. If
2265/// \p BeforeIsOkay is true, then \p X can be less than or equal to \p Y.
2266static bool versionsMatch(const VersionTuple &X, const VersionTuple &Y,
2267 bool BeforeIsOkay) {
2268 if (X.empty() || Y.empty())
2269 return true;
2270
2271 if (X == Y)
2272 return true;
2273
2274 if (BeforeIsOkay && X < Y)
2275 return true;
2276
2277 return false;
2278}
2279
Rafael Espindolaa3aea432013-01-08 22:04:34 +00002280AvailabilityAttr *Sema::mergeAvailabilityAttr(NamedDecl *D, SourceRange Range,
Rafael Espindolae200f1c2012-05-13 03:25:18 +00002281 IdentifierInfo *Platform,
Manman Ren719a8642016-05-06 21:04:01 +00002282 bool Implicit,
Rafael Espindolae200f1c2012-05-13 03:25:18 +00002283 VersionTuple Introduced,
2284 VersionTuple Deprecated,
2285 VersionTuple Obsoleted,
2286 bool IsUnavailable,
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002287 StringRef Message,
Manman Rend8039df2016-02-22 04:47:24 +00002288 bool IsStrict,
Manman Ren75bc6762016-03-21 17:30:55 +00002289 StringRef Replacement,
Douglas Gregord2a713e2015-09-30 21:27:42 +00002290 AvailabilityMergeKind AMK,
Michael Han99315932013-01-24 16:46:58 +00002291 unsigned AttrSpellingListIndex) {
Rafael Espindolac67f2232012-05-10 02:50:16 +00002292 VersionTuple MergedIntroduced = Introduced;
2293 VersionTuple MergedDeprecated = Deprecated;
2294 VersionTuple MergedObsoleted = Obsoleted;
Rafael Espindola2d243bf2012-05-06 19:56:25 +00002295 bool FoundAny = false;
Douglas Gregord2a713e2015-09-30 21:27:42 +00002296 bool OverrideOrImpl = false;
2297 switch (AMK) {
2298 case AMK_None:
2299 case AMK_Redeclaration:
2300 OverrideOrImpl = false;
2301 break;
2302
2303 case AMK_Override:
2304 case AMK_ProtocolImplementation:
2305 OverrideOrImpl = true;
2306 break;
2307 }
Rafael Espindola2d243bf2012-05-06 19:56:25 +00002308
Rafael Espindolac67f2232012-05-10 02:50:16 +00002309 if (D->hasAttrs()) {
2310 AttrVec &Attrs = D->getAttrs();
2311 for (unsigned i = 0, e = Attrs.size(); i != e;) {
2312 const AvailabilityAttr *OldAA = dyn_cast<AvailabilityAttr>(Attrs[i]);
2313 if (!OldAA) {
2314 ++i;
2315 continue;
2316 }
Rafael Espindola2d243bf2012-05-06 19:56:25 +00002317
Rafael Espindolac67f2232012-05-10 02:50:16 +00002318 IdentifierInfo *OldPlatform = OldAA->getPlatform();
2319 if (OldPlatform != Platform) {
2320 ++i;
2321 continue;
2322 }
2323
Tim Northover7a73cc72015-10-30 16:30:49 +00002324 // If there is an existing availability attribute for this platform that
2325 // is explicit and the new one is implicit use the explicit one and
2326 // discard the new implicit attribute.
Manman Ren719a8642016-05-06 21:04:01 +00002327 if (!OldAA->isImplicit() && Implicit) {
Tim Northover7a73cc72015-10-30 16:30:49 +00002328 return nullptr;
2329 }
2330
2331 // If there is an existing attribute for this platform that is implicit
2332 // and the new attribute is explicit then erase the old one and
2333 // continue processing the attributes.
Manman Ren719a8642016-05-06 21:04:01 +00002334 if (!Implicit && OldAA->isImplicit()) {
Tim Northover7a73cc72015-10-30 16:30:49 +00002335 Attrs.erase(Attrs.begin() + i);
2336 --e;
2337 continue;
2338 }
2339
Rafael Espindolac67f2232012-05-10 02:50:16 +00002340 FoundAny = true;
2341 VersionTuple OldIntroduced = OldAA->getIntroduced();
2342 VersionTuple OldDeprecated = OldAA->getDeprecated();
2343 VersionTuple OldObsoleted = OldAA->getObsoleted();
2344 bool OldIsUnavailable = OldAA->getUnavailable();
Rafael Espindolac67f2232012-05-10 02:50:16 +00002345
Douglas Gregord2a713e2015-09-30 21:27:42 +00002346 if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl) ||
2347 !versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl) ||
2348 !versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl) ||
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002349 !(OldIsUnavailable == IsUnavailable ||
Douglas Gregord2a713e2015-09-30 21:27:42 +00002350 (OverrideOrImpl && !OldIsUnavailable && IsUnavailable))) {
2351 if (OverrideOrImpl) {
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002352 int Which = -1;
2353 VersionTuple FirstVersion;
2354 VersionTuple SecondVersion;
Douglas Gregord2a713e2015-09-30 21:27:42 +00002355 if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl)) {
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002356 Which = 0;
2357 FirstVersion = OldIntroduced;
2358 SecondVersion = Introduced;
Douglas Gregord2a713e2015-09-30 21:27:42 +00002359 } else if (!versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl)) {
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002360 Which = 1;
2361 FirstVersion = Deprecated;
2362 SecondVersion = OldDeprecated;
Douglas Gregord2a713e2015-09-30 21:27:42 +00002363 } else if (!versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl)) {
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002364 Which = 2;
2365 FirstVersion = Obsoleted;
2366 SecondVersion = OldObsoleted;
2367 }
2368
2369 if (Which == -1) {
2370 Diag(OldAA->getLocation(),
2371 diag::warn_mismatched_availability_override_unavail)
Douglas Gregord2a713e2015-09-30 21:27:42 +00002372 << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
2373 << (AMK == AMK_Override);
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002374 } else {
2375 Diag(OldAA->getLocation(),
2376 diag::warn_mismatched_availability_override)
2377 << Which
2378 << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
Douglas Gregord2a713e2015-09-30 21:27:42 +00002379 << FirstVersion.getAsString() << SecondVersion.getAsString()
2380 << (AMK == AMK_Override);
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002381 }
Douglas Gregord2a713e2015-09-30 21:27:42 +00002382 if (AMK == AMK_Override)
2383 Diag(Range.getBegin(), diag::note_overridden_method);
2384 else
2385 Diag(Range.getBegin(), diag::note_protocol_method);
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002386 } else {
2387 Diag(OldAA->getLocation(), diag::warn_mismatched_availability);
2388 Diag(Range.getBegin(), diag::note_previous_attribute);
2389 }
2390
Rafael Espindolac67f2232012-05-10 02:50:16 +00002391 Attrs.erase(Attrs.begin() + i);
2392 --e;
2393 continue;
2394 }
2395
2396 VersionTuple MergedIntroduced2 = MergedIntroduced;
2397 VersionTuple MergedDeprecated2 = MergedDeprecated;
2398 VersionTuple MergedObsoleted2 = MergedObsoleted;
2399
2400 if (MergedIntroduced2.empty())
2401 MergedIntroduced2 = OldIntroduced;
2402 if (MergedDeprecated2.empty())
2403 MergedDeprecated2 = OldDeprecated;
2404 if (MergedObsoleted2.empty())
2405 MergedObsoleted2 = OldObsoleted;
2406
2407 if (checkAvailabilityAttr(*this, OldAA->getRange(), Platform,
2408 MergedIntroduced2, MergedDeprecated2,
2409 MergedObsoleted2)) {
2410 Attrs.erase(Attrs.begin() + i);
2411 --e;
2412 continue;
2413 }
2414
2415 MergedIntroduced = MergedIntroduced2;
2416 MergedDeprecated = MergedDeprecated2;
2417 MergedObsoleted = MergedObsoleted2;
2418 ++i;
Rafael Espindola2d243bf2012-05-06 19:56:25 +00002419 }
Rafael Espindola2d243bf2012-05-06 19:56:25 +00002420 }
2421
2422 if (FoundAny &&
2423 MergedIntroduced == Introduced &&
2424 MergedDeprecated == Deprecated &&
2425 MergedObsoleted == Obsoleted)
Craig Topperc3ec1492014-05-26 06:22:03 +00002426 return nullptr;
Rafael Espindola2d243bf2012-05-06 19:56:25 +00002427
Douglas Gregord2a713e2015-09-30 21:27:42 +00002428 // Only create a new attribute if !OverrideOrImpl, but we want to do
Ted Kremenekb5445722013-04-06 00:34:27 +00002429 // the checking.
Rafael Espindolac67f2232012-05-10 02:50:16 +00002430 if (!checkAvailabilityAttr(*this, Range, Platform, MergedIntroduced,
Ted Kremenekb5445722013-04-06 00:34:27 +00002431 MergedDeprecated, MergedObsoleted) &&
Douglas Gregord2a713e2015-09-30 21:27:42 +00002432 !OverrideOrImpl) {
Manman Ren719a8642016-05-06 21:04:01 +00002433 auto *Avail = ::new (Context) AvailabilityAttr(Range, Context, Platform,
Rafael Espindolae200f1c2012-05-13 03:25:18 +00002434 Introduced, Deprecated,
Michael Han99315932013-01-24 16:46:58 +00002435 Obsoleted, IsUnavailable, Message,
Manman Ren75bc6762016-03-21 17:30:55 +00002436 IsStrict, Replacement,
2437 AttrSpellingListIndex);
Manman Ren719a8642016-05-06 21:04:01 +00002438 Avail->setImplicit(Implicit);
2439 return Avail;
Rafael Espindola2d243bf2012-05-06 19:56:25 +00002440 }
Craig Topperc3ec1492014-05-26 06:22:03 +00002441 return nullptr;
Rafael Espindola2d243bf2012-05-06 19:56:25 +00002442}
2443
Chandler Carruthedc2c642011-07-02 00:01:44 +00002444static void handleAvailabilityAttr(Sema &S, Decl *D,
2445 const AttributeList &Attr) {
Aaron Ballman00e99962013-08-31 01:11:41 +00002446 if (!checkAttributeNumArgs(S, Attr, 1))
2447 return;
2448 IdentifierLoc *Platform = Attr.getArgAsIdent(0);
Michael Han99315932013-01-24 16:46:58 +00002449 unsigned Index = Attr.getAttributeSpellingListIndex();
2450
Aaron Ballman00e99962013-08-31 01:11:41 +00002451 IdentifierInfo *II = Platform->Ident;
2452 if (AvailabilityAttr::getPrettyPlatformName(II->getName()).empty())
2453 S.Diag(Platform->Loc, diag::warn_availability_unknown_platform)
2454 << Platform->Ident;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00002455
Rafael Espindolac231fab2013-01-08 21:30:32 +00002456 NamedDecl *ND = dyn_cast<NamedDecl>(D);
Alex Lorenz472cc792017-04-20 09:35:02 +00002457 if (!ND) // We warned about this already, so just return.
Rafael Espindolac231fab2013-01-08 21:30:32 +00002458 return;
Rafael Espindolac231fab2013-01-08 21:30:32 +00002459
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00002460 AvailabilityChange Introduced = Attr.getAvailabilityIntroduced();
2461 AvailabilityChange Deprecated = Attr.getAvailabilityDeprecated();
2462 AvailabilityChange Obsoleted = Attr.getAvailabilityObsoleted();
Douglas Gregor7ab142b2011-03-26 03:35:55 +00002463 bool IsUnavailable = Attr.getUnavailableLoc().isValid();
Manman Rend8039df2016-02-22 04:47:24 +00002464 bool IsStrict = Attr.getStrictLoc().isValid();
Fariborz Jahanian88d510d2011-12-10 00:28:41 +00002465 StringRef Str;
Benjamin Kramera9dfa922013-09-13 17:31:48 +00002466 if (const StringLiteral *SE =
2467 dyn_cast_or_null<StringLiteral>(Attr.getMessageExpr()))
Fariborz Jahanian88d510d2011-12-10 00:28:41 +00002468 Str = SE->getString();
Manman Ren75bc6762016-03-21 17:30:55 +00002469 StringRef Replacement;
2470 if (const StringLiteral *SE =
2471 dyn_cast_or_null<StringLiteral>(Attr.getReplacementExpr()))
2472 Replacement = SE->getString();
Rafael Espindola2d243bf2012-05-06 19:56:25 +00002473
Aaron Ballman00e99962013-08-31 01:11:41 +00002474 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND, Attr.getRange(), II,
Manman Ren719a8642016-05-06 21:04:01 +00002475 false/*Implicit*/,
Rafael Espindolae200f1c2012-05-13 03:25:18 +00002476 Introduced.Version,
2477 Deprecated.Version,
2478 Obsoleted.Version,
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002479 IsUnavailable, Str,
Manman Ren75bc6762016-03-21 17:30:55 +00002480 IsStrict, Replacement,
Douglas Gregord2a713e2015-09-30 21:27:42 +00002481 Sema::AMK_None,
Michael Han99315932013-01-24 16:46:58 +00002482 Index);
Rafael Espindola19de5612013-01-12 06:42:30 +00002483 if (NewAttr)
Rafael Espindolae200f1c2012-05-13 03:25:18 +00002484 D->addAttr(NewAttr);
Tim Northover7a73cc72015-10-30 16:30:49 +00002485
2486 // Transcribe "ios" to "watchos" (and add a new attribute) if the versioning
2487 // matches before the start of the watchOS platform.
2488 if (S.Context.getTargetInfo().getTriple().isWatchOS()) {
2489 IdentifierInfo *NewII = nullptr;
2490 if (II->getName() == "ios")
2491 NewII = &S.Context.Idents.get("watchos");
2492 else if (II->getName() == "ios_app_extension")
2493 NewII = &S.Context.Idents.get("watchos_app_extension");
2494
2495 if (NewII) {
2496 auto adjustWatchOSVersion = [](VersionTuple Version) -> VersionTuple {
2497 if (Version.empty())
2498 return Version;
2499 auto Major = Version.getMajor();
2500 auto NewMajor = Major >= 9 ? Major - 7 : 0;
2501 if (NewMajor >= 2) {
2502 if (Version.getMinor().hasValue()) {
2503 if (Version.getSubminor().hasValue())
2504 return VersionTuple(NewMajor, Version.getMinor().getValue(),
2505 Version.getSubminor().getValue());
2506 else
2507 return VersionTuple(NewMajor, Version.getMinor().getValue());
2508 }
2509 }
2510
2511 return VersionTuple(2, 0);
2512 };
2513
2514 auto NewIntroduced = adjustWatchOSVersion(Introduced.Version);
2515 auto NewDeprecated = adjustWatchOSVersion(Deprecated.Version);
2516 auto NewObsoleted = adjustWatchOSVersion(Obsoleted.Version);
2517
2518 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND,
Manman Ren719a8642016-05-06 21:04:01 +00002519 Attr.getRange(),
Tim Northover7a73cc72015-10-30 16:30:49 +00002520 NewII,
Manman Ren719a8642016-05-06 21:04:01 +00002521 true/*Implicit*/,
Tim Northover7a73cc72015-10-30 16:30:49 +00002522 NewIntroduced,
2523 NewDeprecated,
2524 NewObsoleted,
2525 IsUnavailable, Str,
Manman Rend8039df2016-02-22 04:47:24 +00002526 IsStrict,
Manman Ren75bc6762016-03-21 17:30:55 +00002527 Replacement,
Tim Northover7a73cc72015-10-30 16:30:49 +00002528 Sema::AMK_None,
2529 Index);
2530 if (NewAttr)
2531 D->addAttr(NewAttr);
2532 }
2533 } else if (S.Context.getTargetInfo().getTriple().isTvOS()) {
2534 // Transcribe "ios" to "tvos" (and add a new attribute) if the versioning
2535 // matches before the start of the tvOS platform.
2536 IdentifierInfo *NewII = nullptr;
2537 if (II->getName() == "ios")
2538 NewII = &S.Context.Idents.get("tvos");
2539 else if (II->getName() == "ios_app_extension")
2540 NewII = &S.Context.Idents.get("tvos_app_extension");
2541
2542 if (NewII) {
2543 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND,
Manman Ren719a8642016-05-06 21:04:01 +00002544 Attr.getRange(),
Tim Northover7a73cc72015-10-30 16:30:49 +00002545 NewII,
Manman Ren719a8642016-05-06 21:04:01 +00002546 true/*Implicit*/,
Tim Northover7a73cc72015-10-30 16:30:49 +00002547 Introduced.Version,
2548 Deprecated.Version,
2549 Obsoleted.Version,
2550 IsUnavailable, Str,
Manman Rend8039df2016-02-22 04:47:24 +00002551 IsStrict,
Manman Ren75bc6762016-03-21 17:30:55 +00002552 Replacement,
Tim Northover7a73cc72015-10-30 16:30:49 +00002553 Sema::AMK_None,
2554 Index);
2555 if (NewAttr)
2556 D->addAttr(NewAttr);
2557 }
2558 }
Rafael Espindolac67f2232012-05-10 02:50:16 +00002559}
2560
Alex Lorenzd5d27e12017-03-01 18:06:25 +00002561static void handleExternalSourceSymbolAttr(Sema &S, Decl *D,
2562 const AttributeList &Attr) {
2563 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
2564 return;
2565 assert(checkAttributeAtMostNumArgs(S, Attr, 3) &&
2566 "Invalid number of arguments in an external_source_symbol attribute");
2567
Alex Lorenzd5d27e12017-03-01 18:06:25 +00002568 StringRef Language;
2569 if (const auto *SE = dyn_cast_or_null<StringLiteral>(Attr.getArgAsExpr(0)))
2570 Language = SE->getString();
2571 StringRef DefinedIn;
2572 if (const auto *SE = dyn_cast_or_null<StringLiteral>(Attr.getArgAsExpr(1)))
2573 DefinedIn = SE->getString();
2574 bool IsGeneratedDeclaration = Attr.getArgAsIdent(2) != nullptr;
2575
2576 D->addAttr(::new (S.Context) ExternalSourceSymbolAttr(
2577 Attr.getRange(), S.Context, Language, DefinedIn, IsGeneratedDeclaration,
2578 Attr.getAttributeSpellingListIndex()));
2579}
2580
John McCalld041a9b2013-02-20 01:54:26 +00002581template <class T>
2582static T *mergeVisibilityAttr(Sema &S, Decl *D, SourceRange range,
2583 typename T::VisibilityType value,
2584 unsigned attrSpellingListIndex) {
2585 T *existingAttr = D->getAttr<T>();
2586 if (existingAttr) {
2587 typename T::VisibilityType existingValue = existingAttr->getVisibility();
2588 if (existingValue == value)
Craig Topperc3ec1492014-05-26 06:22:03 +00002589 return nullptr;
John McCalld041a9b2013-02-20 01:54:26 +00002590 S.Diag(existingAttr->getLocation(), diag::err_mismatched_visibility);
2591 S.Diag(range.getBegin(), diag::note_previous_attribute);
2592 D->dropAttr<T>();
2593 }
2594 return ::new (S.Context) T(range, S.Context, value, attrSpellingListIndex);
2595}
2596
Rafael Espindolae200f1c2012-05-13 03:25:18 +00002597VisibilityAttr *Sema::mergeVisibilityAttr(Decl *D, SourceRange Range,
Michael Han99315932013-01-24 16:46:58 +00002598 VisibilityAttr::VisibilityType Vis,
2599 unsigned AttrSpellingListIndex) {
John McCalld041a9b2013-02-20 01:54:26 +00002600 return ::mergeVisibilityAttr<VisibilityAttr>(*this, D, Range, Vis,
2601 AttrSpellingListIndex);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00002602}
2603
John McCalld041a9b2013-02-20 01:54:26 +00002604TypeVisibilityAttr *Sema::mergeTypeVisibilityAttr(Decl *D, SourceRange Range,
2605 TypeVisibilityAttr::VisibilityType Vis,
2606 unsigned AttrSpellingListIndex) {
2607 return ::mergeVisibilityAttr<TypeVisibilityAttr>(*this, D, Range, Vis,
2608 AttrSpellingListIndex);
2609}
2610
2611static void handleVisibilityAttr(Sema &S, Decl *D, const AttributeList &Attr,
2612 bool isTypeVisibility) {
2613 // Visibility attributes don't mean anything on a typedef.
2614 if (isa<TypedefNameDecl>(D)) {
2615 S.Diag(Attr.getRange().getBegin(), diag::warn_attribute_ignored)
2616 << Attr.getName();
2617 return;
2618 }
2619
2620 // 'type_visibility' can only go on a type or namespace.
2621 if (isTypeVisibility &&
2622 !(isa<TagDecl>(D) ||
2623 isa<ObjCInterfaceDecl>(D) ||
2624 isa<NamespaceDecl>(D))) {
2625 S.Diag(Attr.getRange().getBegin(), diag::err_attribute_wrong_decl_type)
2626 << Attr.getName() << ExpectedTypeOrNamespace;
2627 return;
2628 }
2629
Benjamin Kramer70370212013-09-09 15:08:57 +00002630 // Check that the argument is a string literal.
Benjamin Kramer6ee15622013-09-13 15:35:43 +00002631 StringRef TypeStr;
2632 SourceLocation LiteralLoc;
Tim Northover6a6b63b2013-10-01 14:34:18 +00002633 if (!S.checkStringLiteralArgumentAttr(Attr, 0, TypeStr, &LiteralLoc))
Chris Lattner2c6fcf52008-06-26 18:38:35 +00002634 return;
Mike Stumpd3bb5572009-07-24 19:02:52 +00002635
Alexis Huntdcfba7b2010-08-18 23:23:40 +00002636 VisibilityAttr::VisibilityType type;
Aaron Ballman682ee422013-09-11 19:47:58 +00002637 if (!VisibilityAttr::ConvertStrToVisibilityType(TypeStr, type)) {
Benjamin Kramer6ee15622013-09-13 15:35:43 +00002638 S.Diag(LiteralLoc, diag::warn_attribute_type_not_supported)
Aaron Ballman682ee422013-09-11 19:47:58 +00002639 << Attr.getName() << TypeStr;
Chris Lattner2c6fcf52008-06-26 18:38:35 +00002640 return;
2641 }
Aaron Ballman682ee422013-09-11 19:47:58 +00002642
2643 // Complain about attempts to use protected visibility on targets
2644 // (like Darwin) that don't support it.
2645 if (type == VisibilityAttr::Protected &&
2646 !S.Context.getTargetInfo().hasProtectedVisibility()) {
2647 S.Diag(Attr.getLoc(), diag::warn_attribute_protected_visibility);
2648 type = VisibilityAttr::Default;
2649 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00002650
Michael Han99315932013-01-24 16:46:58 +00002651 unsigned Index = Attr.getAttributeSpellingListIndex();
John McCalld041a9b2013-02-20 01:54:26 +00002652 clang::Attr *newAttr;
2653 if (isTypeVisibility) {
2654 newAttr = S.mergeTypeVisibilityAttr(D, Attr.getRange(),
2655 (TypeVisibilityAttr::VisibilityType) type,
2656 Index);
2657 } else {
2658 newAttr = S.mergeVisibilityAttr(D, Attr.getRange(), type, Index);
2659 }
2660 if (newAttr)
2661 D->addAttr(newAttr);
Chris Lattner2c6fcf52008-06-26 18:38:35 +00002662}
2663
Chandler Carruthedc2c642011-07-02 00:01:44 +00002664static void handleObjCMethodFamilyAttr(Sema &S, Decl *decl,
2665 const AttributeList &Attr) {
Aaron Ballman74eeeae2013-11-27 13:27:02 +00002666 ObjCMethodDecl *method = cast<ObjCMethodDecl>(decl);
Aaron Ballman00e99962013-08-31 01:11:41 +00002667 if (!Attr.isArgIdent(0)) {
2668 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2669 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
John McCall86bc21f2011-03-02 11:33:24 +00002670 return;
2671 }
Aaron Ballman00e99962013-08-31 01:11:41 +00002672
Aaron Ballman682ee422013-09-11 19:47:58 +00002673 IdentifierLoc *IL = Attr.getArgAsIdent(0);
2674 ObjCMethodFamilyAttr::FamilyKind F;
2675 if (!ObjCMethodFamilyAttr::ConvertStrToFamilyKind(IL->Ident->getName(), F)) {
2676 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << Attr.getName()
2677 << IL->Ident;
John McCall86bc21f2011-03-02 11:33:24 +00002678 return;
2679 }
2680
Alp Toker314cc812014-01-25 16:55:45 +00002681 if (F == ObjCMethodFamilyAttr::OMF_init &&
2682 !method->getReturnType()->isObjCObjectPointerType()) {
John McCall31168b02011-06-15 23:02:42 +00002683 S.Diag(method->getLocation(), diag::err_init_method_bad_return_type)
Alp Toker314cc812014-01-25 16:55:45 +00002684 << method->getReturnType();
John McCall31168b02011-06-15 23:02:42 +00002685 // Ignore the attribute.
2686 return;
2687 }
2688
Argyrios Kyrtzidis309b4c42011-09-13 16:05:58 +00002689 method->addAttr(new (S.Context) ObjCMethodFamilyAttr(Attr.getRange(),
Aaron Ballman36a53502014-01-16 13:03:14 +00002690 S.Context, F,
2691 Attr.getAttributeSpellingListIndex()));
John McCall86bc21f2011-03-02 11:33:24 +00002692}
2693
Chandler Carruthedc2c642011-07-02 00:01:44 +00002694static void handleObjCNSObject(Sema &S, Decl *D, const AttributeList &Attr) {
Richard Smithdda56e42011-04-15 14:24:37 +00002695 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
Fariborz Jahanian255c0952009-01-13 23:34:40 +00002696 QualType T = TD->getUnderlyingType();
Ted Kremenek7712eef2012-08-29 22:54:47 +00002697 if (!T->isCARCBridgableType()) {
Fariborz Jahanian255c0952009-01-13 23:34:40 +00002698 S.Diag(TD->getLocation(), diag::err_nsobject_attribute);
2699 return;
2700 }
2701 }
Fariborz Jahanianbebd0ba2012-05-31 23:18:32 +00002702 else if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) {
2703 QualType T = PD->getType();
Ted Kremenek7712eef2012-08-29 22:54:47 +00002704 if (!T->isCARCBridgableType()) {
Fariborz Jahanianbebd0ba2012-05-31 23:18:32 +00002705 S.Diag(PD->getLocation(), diag::err_nsobject_attribute);
2706 return;
2707 }
2708 }
2709 else {
Ted Kremenek05e916b2012-03-01 01:40:32 +00002710 // It is okay to include this attribute on properties, e.g.:
2711 //
2712 // @property (retain, nonatomic) struct Bork *Q __attribute__((NSObject));
2713 //
2714 // In this case it follows tradition and suppresses an error in the above
2715 // case.
Fariborz Jahaniana45495a2011-11-29 01:48:40 +00002716 S.Diag(D->getLocation(), diag::warn_nsobject_attribute);
Ted Kremenek05e916b2012-03-01 01:40:32 +00002717 }
Michael Han99315932013-01-24 16:46:58 +00002718 D->addAttr(::new (S.Context)
2719 ObjCNSObjectAttr(Attr.getRange(), S.Context,
2720 Attr.getAttributeSpellingListIndex()));
Fariborz Jahanian255c0952009-01-13 23:34:40 +00002721}
2722
Fariborz Jahanian7a60b6d2015-04-16 18:38:44 +00002723static void handleObjCIndependentClass(Sema &S, Decl *D, const AttributeList &Attr) {
2724 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
2725 QualType T = TD->getUnderlyingType();
2726 if (!T->isObjCObjectPointerType()) {
2727 S.Diag(TD->getLocation(), diag::warn_ptr_independentclass_attribute);
2728 return;
2729 }
2730 } else {
2731 S.Diag(D->getLocation(), diag::warn_independentclass_attribute);
2732 return;
2733 }
2734 D->addAttr(::new (S.Context)
2735 ObjCIndependentClassAttr(Attr.getRange(), S.Context,
2736 Attr.getAttributeSpellingListIndex()));
2737}
2738
Chandler Carruthedc2c642011-07-02 00:01:44 +00002739static void handleBlocksAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballman00e99962013-08-31 01:11:41 +00002740 if (!Attr.isArgIdent(0)) {
Aaron Ballman29982272013-07-23 14:03:57 +00002741 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
Aaron Ballman00e99962013-08-31 01:11:41 +00002742 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
Steve Naroff3405a732008-09-18 16:44:58 +00002743 return;
2744 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00002745
Aaron Ballman00e99962013-08-31 01:11:41 +00002746 IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident;
Alexis Huntdcfba7b2010-08-18 23:23:40 +00002747 BlocksAttr::BlockType type;
Aaron Ballman682ee422013-09-11 19:47:58 +00002748 if (!BlocksAttr::ConvertStrToBlockType(II->getName(), type)) {
2749 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
2750 << Attr.getName() << II;
Steve Naroff3405a732008-09-18 16:44:58 +00002751 return;
2752 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00002753
Michael Han99315932013-01-24 16:46:58 +00002754 D->addAttr(::new (S.Context)
2755 BlocksAttr(Attr.getRange(), S.Context, type,
2756 Attr.getAttributeSpellingListIndex()));
Steve Naroff3405a732008-09-18 16:44:58 +00002757}
2758
Chandler Carruthedc2c642011-07-02 00:01:44 +00002759static void handleSentinelAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballman18a78382013-11-21 00:28:23 +00002760 unsigned sentinel = (unsigned)SentinelAttr::DefaultSentinel;
Anders Carlssonc181b012008-10-05 18:05:59 +00002761 if (Attr.getNumArgs() > 0) {
Aaron Ballman00e99962013-08-31 01:11:41 +00002762 Expr *E = Attr.getArgAsExpr(0);
Anders Carlssonc181b012008-10-05 18:05:59 +00002763 llvm::APSInt Idx(32);
Douglas Gregorbdb604a2010-05-18 23:01:22 +00002764 if (E->isTypeDependent() || E->isValueDependent() ||
2765 !E->isIntegerConstantExpr(Idx, S.Context)) {
Aaron Ballman29982272013-07-23 14:03:57 +00002766 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
Aaron Ballman3bf758c2013-07-30 01:31:03 +00002767 << Attr.getName() << 1 << AANT_ArgumentIntegerConstant
Aaron Ballman29982272013-07-23 14:03:57 +00002768 << E->getSourceRange();
Anders Carlssonc181b012008-10-05 18:05:59 +00002769 return;
2770 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00002771
John McCallb46f2872011-09-09 07:56:05 +00002772 if (Idx.isSigned() && Idx.isNegative()) {
Chris Lattner3b054132008-11-19 05:08:23 +00002773 S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_less_than_zero)
2774 << E->getSourceRange();
Anders Carlssonc181b012008-10-05 18:05:59 +00002775 return;
2776 }
John McCallb46f2872011-09-09 07:56:05 +00002777
2778 sentinel = Idx.getZExtValue();
Anders Carlssonc181b012008-10-05 18:05:59 +00002779 }
2780
Aaron Ballman18a78382013-11-21 00:28:23 +00002781 unsigned nullPos = (unsigned)SentinelAttr::DefaultNullPos;
Anders Carlssonc181b012008-10-05 18:05:59 +00002782 if (Attr.getNumArgs() > 1) {
Aaron Ballman00e99962013-08-31 01:11:41 +00002783 Expr *E = Attr.getArgAsExpr(1);
Anders Carlssonc181b012008-10-05 18:05:59 +00002784 llvm::APSInt Idx(32);
Douglas Gregorbdb604a2010-05-18 23:01:22 +00002785 if (E->isTypeDependent() || E->isValueDependent() ||
2786 !E->isIntegerConstantExpr(Idx, S.Context)) {
Aaron Ballman29982272013-07-23 14:03:57 +00002787 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
Aaron Ballman3bf758c2013-07-30 01:31:03 +00002788 << Attr.getName() << 2 << AANT_ArgumentIntegerConstant
Aaron Ballman29982272013-07-23 14:03:57 +00002789 << E->getSourceRange();
Anders Carlssonc181b012008-10-05 18:05:59 +00002790 return;
2791 }
2792 nullPos = Idx.getZExtValue();
Mike Stumpd3bb5572009-07-24 19:02:52 +00002793
John McCallb46f2872011-09-09 07:56:05 +00002794 if ((Idx.isSigned() && Idx.isNegative()) || nullPos > 1) {
Anders Carlssonc181b012008-10-05 18:05:59 +00002795 // FIXME: This error message could be improved, it would be nice
2796 // to say what the bounds actually are.
Chris Lattner3b054132008-11-19 05:08:23 +00002797 S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_not_zero_or_one)
2798 << E->getSourceRange();
Anders Carlssonc181b012008-10-05 18:05:59 +00002799 return;
2800 }
2801 }
2802
Chandler Carruthff4c4f02011-07-01 23:49:12 +00002803 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
John McCallb46f2872011-09-09 07:56:05 +00002804 const FunctionType *FT = FD->getType()->castAs<FunctionType>();
Chris Lattner9363e312009-03-17 23:03:47 +00002805 if (isa<FunctionNoProtoType>(FT)) {
2806 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_named_arguments);
2807 return;
2808 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00002809
Chris Lattner9363e312009-03-17 23:03:47 +00002810 if (!cast<FunctionProtoType>(FT)->isVariadic()) {
Fariborz Jahanian6802ed92009-05-15 21:18:04 +00002811 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
Anders Carlssonc181b012008-10-05 18:05:59 +00002812 return;
Mike Stumpd3bb5572009-07-24 19:02:52 +00002813 }
Chandler Carruthff4c4f02011-07-01 23:49:12 +00002814 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Anders Carlssonc181b012008-10-05 18:05:59 +00002815 if (!MD->isVariadic()) {
Fariborz Jahanian6802ed92009-05-15 21:18:04 +00002816 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
Anders Carlssonc181b012008-10-05 18:05:59 +00002817 return;
Fariborz Jahanian6607b212009-05-14 20:53:39 +00002818 }
Eli Friedman5c5e3b72012-01-06 01:23:10 +00002819 } else if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
2820 if (!BD->isVariadic()) {
2821 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 1;
2822 return;
2823 }
Chandler Carruthff4c4f02011-07-01 23:49:12 +00002824 } else if (const VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahanian6607b212009-05-14 20:53:39 +00002825 QualType Ty = V->getType();
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00002826 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
Aaron Ballman12b9f652014-01-16 13:55:42 +00002827 const FunctionType *FT = Ty->isFunctionPointerType()
2828 ? D->getFunctionType()
Eric Christopherbc638a82010-12-01 22:13:54 +00002829 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Fariborz Jahanian6607b212009-05-14 20:53:39 +00002830 if (!cast<FunctionProtoType>(FT)->isVariadic()) {
Fariborz Jahanian6802ed92009-05-15 21:18:04 +00002831 int m = Ty->isFunctionPointerType() ? 0 : 1;
2832 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << m;
Fariborz Jahanian6607b212009-05-14 20:53:39 +00002833 return;
2834 }
Mike Stump12b8ce12009-08-04 21:02:39 +00002835 } else {
Fariborz Jahanian6607b212009-05-14 20:53:39 +00002836 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
John McCall5fca7ea2011-03-02 12:29:23 +00002837 << Attr.getName() << ExpectedFunctionMethodOrBlock;
Fariborz Jahanian6607b212009-05-14 20:53:39 +00002838 return;
2839 }
Anders Carlssonc181b012008-10-05 18:05:59 +00002840 } else {
Chris Lattner3b054132008-11-19 05:08:23 +00002841 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
John McCall5fca7ea2011-03-02 12:29:23 +00002842 << Attr.getName() << ExpectedFunctionMethodOrBlock;
Anders Carlssonc181b012008-10-05 18:05:59 +00002843 return;
2844 }
Michael Han99315932013-01-24 16:46:58 +00002845 D->addAttr(::new (S.Context)
2846 SentinelAttr(Attr.getRange(), S.Context, sentinel, nullPos,
2847 Attr.getAttributeSpellingListIndex()));
Anders Carlssonc181b012008-10-05 18:05:59 +00002848}
2849
Chandler Carruthedc2c642011-07-02 00:01:44 +00002850static void handleWarnUnusedResult(Sema &S, Decl *D, const AttributeList &Attr) {
Alp Toker314cc812014-01-25 16:55:45 +00002851 if (D->getFunctionType() &&
2852 D->getFunctionType()->getReturnType()->isVoidType()) {
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +00002853 S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method)
2854 << Attr.getName() << 0;
Nuno Lopes56abcbd2009-12-22 23:59:52 +00002855 return;
2856 }
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +00002857 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
Alp Toker314cc812014-01-25 16:55:45 +00002858 if (MD->getReturnType()->isVoidType()) {
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +00002859 S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method)
2860 << Attr.getName() << 1;
2861 return;
2862 }
2863
Aaron Ballmane7964782016-03-07 22:44:55 +00002864 // If this is spelled as the standard C++1z attribute, but not in C++1z, warn
2865 // about using it as an extension.
2866 if (!S.getLangOpts().CPlusPlus1z && Attr.isCXX11Attribute() &&
2867 !Attr.getScopeName())
Richard Smithb115e5d2017-08-13 23:37:29 +00002868 S.Diag(Attr.getLoc(), diag::ext_cxx17_attr) << Attr.getName();
Aaron Ballmane7964782016-03-07 22:44:55 +00002869
Michael Han99315932013-01-24 16:46:58 +00002870 D->addAttr(::new (S.Context)
2871 WarnUnusedResultAttr(Attr.getRange(), S.Context,
2872 Attr.getAttributeSpellingListIndex()));
Chris Lattner237f2752009-02-14 07:37:35 +00002873}
2874
Chandler Carruthedc2c642011-07-02 00:01:44 +00002875static void handleWeakImportAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Daniel Dunbar5cb85eb2009-03-06 06:39:57 +00002876 // weak_import only applies to variable & function declarations.
2877 bool isDef = false;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00002878 if (!D->canBeWeakImported(isDef)) {
2879 if (isDef)
Reid Kleckner52d598e2013-05-20 21:53:29 +00002880 S.Diag(Attr.getLoc(), diag::warn_attribute_invalid_on_definition)
2881 << "weak_import";
Douglas Gregord71149a2011-03-23 13:27:51 +00002882 else if (isa<ObjCPropertyDecl>(D) || isa<ObjCMethodDecl>(D) ||
Douglas Gregore8bbc122011-09-02 00:18:52 +00002883 (S.Context.getTargetInfo().getTriple().isOSDarwin() &&
Fariborz Jahanian3249a1e2011-10-26 23:59:12 +00002884 (isa<ObjCInterfaceDecl>(D) || isa<EnumDecl>(D)))) {
Douglas Gregord71149a2011-03-23 13:27:51 +00002885 // Nothing to warn about here.
2886 } else
Fariborz Jahanianea70a172010-04-13 20:22:35 +00002887 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
John McCall5fca7ea2011-03-02 12:29:23 +00002888 << Attr.getName() << ExpectedVariableOrFunction;
Daniel Dunbar5cb85eb2009-03-06 06:39:57 +00002889
Daniel Dunbar5cb85eb2009-03-06 06:39:57 +00002890 return;
2891 }
2892
Michael Han99315932013-01-24 16:46:58 +00002893 D->addAttr(::new (S.Context)
2894 WeakImportAttr(Attr.getRange(), S.Context,
2895 Attr.getAttributeSpellingListIndex()));
Daniel Dunbar5cb85eb2009-03-06 06:39:57 +00002896}
2897
Tanya Lattnerbcffcdf2012-07-09 22:06:01 +00002898// Handles reqd_work_group_size and work_group_size_hint.
Aaron Ballman1d0d2a42013-12-02 22:38:33 +00002899template <typename WorkGroupAttr>
Tanya Lattnerbcffcdf2012-07-09 22:06:01 +00002900static void handleWorkGroupSize(Sema &S, Decl *D,
Nick Lewyckyb9e4a3a2012-07-24 01:31:55 +00002901 const AttributeList &Attr) {
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00002902 uint32_t WGSize[3];
Joey Goulyb1d23a82014-05-19 14:41:38 +00002903 for (unsigned i = 0; i < 3; ++i) {
2904 const Expr *E = Attr.getArgAsExpr(i);
2905 if (!checkUInt32Argument(S, Attr, E, WGSize[i], i))
Nate Begemanf2758702009-06-26 06:32:41 +00002906 return;
Joey Goulyb1d23a82014-05-19 14:41:38 +00002907 if (WGSize[i] == 0) {
2908 S.Diag(Attr.getLoc(), diag::err_attribute_argument_is_zero)
2909 << Attr.getName() << E->getSourceRange();
2910 return;
2911 }
2912 }
Tanya Lattnerbcffcdf2012-07-09 22:06:01 +00002913
Aaron Ballman1d0d2a42013-12-02 22:38:33 +00002914 WorkGroupAttr *Existing = D->getAttr<WorkGroupAttr>();
2915 if (Existing && !(Existing->getXDim() == WGSize[0] &&
2916 Existing->getYDim() == WGSize[1] &&
2917 Existing->getZDim() == WGSize[2]))
2918 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) << Attr.getName();
Tanya Lattnerbcffcdf2012-07-09 22:06:01 +00002919
Aaron Ballman1d0d2a42013-12-02 22:38:33 +00002920 D->addAttr(::new (S.Context) WorkGroupAttr(Attr.getRange(), S.Context,
2921 WGSize[0], WGSize[1], WGSize[2],
Michael Han99315932013-01-24 16:46:58 +00002922 Attr.getAttributeSpellingListIndex()));
Nate Begemanf2758702009-06-26 06:32:41 +00002923}
2924
Xiuli Panbe6da4b2017-05-04 07:31:20 +00002925// Handles intel_reqd_sub_group_size.
2926static void handleSubGroupSize(Sema &S, Decl *D, const AttributeList &Attr) {
2927 uint32_t SGSize;
2928 const Expr *E = Attr.getArgAsExpr(0);
2929 if (!checkUInt32Argument(S, Attr, E, SGSize))
2930 return;
2931 if (SGSize == 0) {
2932 S.Diag(Attr.getLoc(), diag::err_attribute_argument_is_zero)
2933 << Attr.getName() << E->getSourceRange();
2934 return;
2935 }
2936
2937 OpenCLIntelReqdSubGroupSizeAttr *Existing =
2938 D->getAttr<OpenCLIntelReqdSubGroupSizeAttr>();
2939 if (Existing && Existing->getSubGroupSize() != SGSize)
2940 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) << Attr.getName();
2941
2942 D->addAttr(::new (S.Context) OpenCLIntelReqdSubGroupSizeAttr(
2943 Attr.getRange(), S.Context, SGSize,
2944 Attr.getAttributeSpellingListIndex()));
2945}
2946
Joey Goulyaba589c2013-03-08 09:42:32 +00002947static void handleVecTypeHint(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballman00e99962013-08-31 01:11:41 +00002948 if (!Attr.hasParsedType()) {
2949 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
2950 << Attr.getName() << 1;
2951 return;
2952 }
2953
Craig Topperc3ec1492014-05-26 06:22:03 +00002954 TypeSourceInfo *ParmTSI = nullptr;
Richard Smithb87c4652013-10-31 21:23:20 +00002955 QualType ParmType = S.GetTypeFromParser(Attr.getTypeArg(), &ParmTSI);
2956 assert(ParmTSI && "no type source info for attribute argument");
Joey Goulyaba589c2013-03-08 09:42:32 +00002957
2958 if (!ParmType->isExtVectorType() && !ParmType->isFloatingType() &&
2959 (ParmType->isBooleanType() ||
2960 !ParmType->isIntegralType(S.getASTContext()))) {
2961 S.Diag(Attr.getLoc(), diag::err_attribute_argument_vec_type_hint)
2962 << ParmType;
2963 return;
2964 }
2965
Aaron Ballmana9e05402013-12-02 22:16:55 +00002966 if (VecTypeHintAttr *A = D->getAttr<VecTypeHintAttr>()) {
Richard Smithb87c4652013-10-31 21:23:20 +00002967 if (!S.Context.hasSameType(A->getTypeHint(), ParmType)) {
Joey Goulyaba589c2013-03-08 09:42:32 +00002968 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) << Attr.getName();
2969 return;
2970 }
2971 }
2972
2973 D->addAttr(::new (S.Context) VecTypeHintAttr(Attr.getLoc(), S.Context,
Aaron Ballman36a53502014-01-16 13:03:14 +00002974 ParmTSI,
2975 Attr.getAttributeSpellingListIndex()));
Joey Goulyaba589c2013-03-08 09:42:32 +00002976}
2977
Rafael Espindolae200f1c2012-05-13 03:25:18 +00002978SectionAttr *Sema::mergeSectionAttr(Decl *D, SourceRange Range,
Michael Han99315932013-01-24 16:46:58 +00002979 StringRef Name,
2980 unsigned AttrSpellingListIndex) {
Rafael Espindola9869c3a2012-05-13 02:42:42 +00002981 if (SectionAttr *ExistingAttr = D->getAttr<SectionAttr>()) {
2982 if (ExistingAttr->getName() == Name)
Craig Topperc3ec1492014-05-26 06:22:03 +00002983 return nullptr;
Rafael Espindola9869c3a2012-05-13 02:42:42 +00002984 Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section);
2985 Diag(Range.getBegin(), diag::note_previous_attribute);
Craig Topperc3ec1492014-05-26 06:22:03 +00002986 return nullptr;
Rafael Espindola9869c3a2012-05-13 02:42:42 +00002987 }
Michael Han99315932013-01-24 16:46:58 +00002988 return ::new (Context) SectionAttr(Range, Context, Name,
2989 AttrSpellingListIndex);
Rafael Espindola9869c3a2012-05-13 02:42:42 +00002990}
2991
Reid Kleckner2a133222015-03-04 23:39:17 +00002992bool Sema::checkSectionName(SourceLocation LiteralLoc, StringRef SecName) {
2993 std::string Error = Context.getTargetInfo().isValidSectionSpecifier(SecName);
2994 if (!Error.empty()) {
2995 Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target) << Error;
2996 return false;
2997 }
2998 return true;
2999}
3000
Chandler Carruthedc2c642011-07-02 00:01:44 +00003001static void handleSectionAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Daniel Dunbar648bf782009-02-12 17:28:23 +00003002 // Make sure that there is a string literal as the sections's single
3003 // argument.
Benjamin Kramer6ee15622013-09-13 15:35:43 +00003004 StringRef Str;
3005 SourceLocation LiteralLoc;
Tim Northover6a6b63b2013-10-01 14:34:18 +00003006 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &LiteralLoc))
Daniel Dunbar648bf782009-02-12 17:28:23 +00003007 return;
Mike Stump11289f42009-09-09 15:08:12 +00003008
Reid Kleckner2a133222015-03-04 23:39:17 +00003009 if (!S.checkSectionName(LiteralLoc, Str))
3010 return;
3011
Chris Lattner30ba6742009-08-10 19:03:04 +00003012 // If the target wants to validate the section specifier, make it happen.
Benjamin Kramer6ee15622013-09-13 15:35:43 +00003013 std::string Error = S.Context.getTargetInfo().isValidSectionSpecifier(Str);
Chris Lattner20aee9b2010-01-12 20:58:53 +00003014 if (!Error.empty()) {
Benjamin Kramer6ee15622013-09-13 15:35:43 +00003015 S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target)
Chris Lattner20aee9b2010-01-12 20:58:53 +00003016 << Error;
Chris Lattner30ba6742009-08-10 19:03:04 +00003017 return;
3018 }
Mike Stump11289f42009-09-09 15:08:12 +00003019
Michael Han99315932013-01-24 16:46:58 +00003020 unsigned Index = Attr.getAttributeSpellingListIndex();
Benjamin Kramer6ee15622013-09-13 15:35:43 +00003021 SectionAttr *NewAttr = S.mergeSectionAttr(D, Attr.getRange(), Str, Index);
Rafael Espindolae200f1c2012-05-13 03:25:18 +00003022 if (NewAttr)
3023 D->addAttr(NewAttr);
Daniel Dunbar648bf782009-02-12 17:28:23 +00003024}
3025
Erich Keane57e15cd2017-07-19 22:06:33 +00003026// Check for things we'd like to warn about. Multiversioning issues are
3027// handled later in the process, once we know how many exist.
3028bool Sema::checkTargetAttr(SourceLocation LiteralLoc, StringRef AttrStr) {
3029 enum FirstParam { Unsupported, Duplicate };
3030 enum SecondParam { None, Architecture };
Eric Christopher789a7ad2015-06-12 01:36:05 +00003031 for (auto Str : {"tune=", "fpmath="})
3032 if (AttrStr.find(Str) != StringRef::npos)
Erich Keane57e15cd2017-07-19 22:06:33 +00003033 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3034 << Unsupported << None << Str;
3035
3036 TargetAttr::ParsedTargetAttr ParsedAttrs = TargetAttr::parse(AttrStr);
3037
3038 if (!ParsedAttrs.Architecture.empty() &&
3039 !Context.getTargetInfo().isValidCPUName(ParsedAttrs.Architecture))
3040 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3041 << Unsupported << Architecture << ParsedAttrs.Architecture;
3042
3043 if (ParsedAttrs.DuplicateArchitecture)
3044 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3045 << Duplicate << None << "arch=";
3046
3047 for (const auto &Feature : ParsedAttrs.Features) {
3048 auto CurFeature = StringRef(Feature).drop_front(); // remove + or -.
3049 if (!Context.getTargetInfo().isValidFeatureName(CurFeature))
3050 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3051 << Unsupported << None << CurFeature;
3052 }
3053
3054 return true;
Eric Christopher789a7ad2015-06-12 01:36:05 +00003055}
3056
Eric Christopher11acf732015-06-12 01:35:52 +00003057static void handleTargetAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Eric Christopher11acf732015-06-12 01:35:52 +00003058 StringRef Str;
3059 SourceLocation LiteralLoc;
Erich Keane57e15cd2017-07-19 22:06:33 +00003060 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &LiteralLoc) ||
3061 !S.checkTargetAttr(LiteralLoc, Str))
Eric Christopher11acf732015-06-12 01:35:52 +00003062 return;
3063 unsigned Index = Attr.getAttributeSpellingListIndex();
3064 TargetAttr *NewAttr =
3065 ::new (S.Context) TargetAttr(Attr.getRange(), S.Context, Str, Index);
3066 D->addAttr(NewAttr);
3067}
3068
Chandler Carruthedc2c642011-07-02 00:01:44 +00003069static void handleCleanupAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003070 VarDecl *VD = cast<VarDecl>(D);
3071 if (!VD->hasLocalStorage()) {
Aaron Ballmanc12aaff2013-09-11 01:37:41 +00003072 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
Anders Carlssond277d792009-01-31 01:16:18 +00003073 return;
3074 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00003075
Aaron Ballmanc12aaff2013-09-11 01:37:41 +00003076 Expr *E = Attr.getArgAsExpr(0);
3077 SourceLocation Loc = E->getExprLoc();
Craig Topperc3ec1492014-05-26 06:22:03 +00003078 FunctionDecl *FD = nullptr;
Aaron Ballmanc12aaff2013-09-11 01:37:41 +00003079 DeclarationNameInfo NI;
Aaron Ballman00e99962013-08-31 01:11:41 +00003080
Aaron Ballmanc12aaff2013-09-11 01:37:41 +00003081 // gcc only allows for simple identifiers. Since we support more than gcc, we
3082 // will warn the user.
3083 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3084 if (DRE->hasQualifier())
3085 S.Diag(Loc, diag::warn_cleanup_ext);
3086 FD = dyn_cast<FunctionDecl>(DRE->getDecl());
3087 NI = DRE->getNameInfo();
3088 if (!FD) {
3089 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 1
3090 << NI.getName();
3091 return;
3092 }
3093 } else if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
3094 if (ULE->hasExplicitTemplateArgs())
3095 S.Diag(Loc, diag::warn_cleanup_ext);
Aaron Ballmanc12aaff2013-09-11 01:37:41 +00003096 FD = S.ResolveSingleFunctionTemplateSpecialization(ULE, true);
3097 NI = ULE->getNameInfo();
Alp Toker67b47ac2013-10-20 18:48:56 +00003098 if (!FD) {
3099 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 2
3100 << NI.getName();
3101 if (ULE->getType() == S.Context.OverloadTy)
3102 S.NoteAllOverloadCandidates(ULE);
3103 return;
3104 }
Aaron Ballmanc12aaff2013-09-11 01:37:41 +00003105 } else {
3106 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 0;
Anders Carlssond277d792009-01-31 01:16:18 +00003107 return;
3108 }
3109
Anders Carlssond277d792009-01-31 01:16:18 +00003110 if (FD->getNumParams() != 1) {
Aaron Ballmanc12aaff2013-09-11 01:37:41 +00003111 S.Diag(Loc, diag::err_attribute_cleanup_func_must_take_one_arg)
3112 << NI.getName();
Anders Carlssond277d792009-01-31 01:16:18 +00003113 return;
3114 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00003115
Anders Carlsson723f55d2009-02-07 23:16:50 +00003116 // We're currently more strict than GCC about what function types we accept.
3117 // If this ever proves to be a problem it should be easy to fix.
3118 QualType Ty = S.Context.getPointerType(VD->getType());
3119 QualType ParamTy = FD->getParamDecl(0)->getType();
Douglas Gregorc03a1082011-01-28 02:26:04 +00003120 if (S.CheckAssignmentConstraints(FD->getParamDecl(0)->getLocation(),
3121 ParamTy, Ty) != Sema::Compatible) {
Aaron Ballmanc12aaff2013-09-11 01:37:41 +00003122 S.Diag(Loc, diag::err_attribute_cleanup_func_arg_incompatible_type)
3123 << NI.getName() << ParamTy << Ty;
Anders Carlsson723f55d2009-02-07 23:16:50 +00003124 return;
3125 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00003126
Michael Han99315932013-01-24 16:46:58 +00003127 D->addAttr(::new (S.Context)
3128 CleanupAttr(Attr.getRange(), S.Context, FD,
3129 Attr.getAttributeSpellingListIndex()));
Anders Carlssond277d792009-01-31 01:16:18 +00003130}
3131
Akira Hatanaka3c268af2017-03-21 02:23:00 +00003132static void handleEnumExtensibilityAttr(Sema &S, Decl *D,
3133 const AttributeList &Attr) {
3134 if (!Attr.isArgIdent(0)) {
3135 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
3136 << Attr.getName() << 0 << AANT_ArgumentIdentifier;
3137 return;
3138 }
3139
3140 EnumExtensibilityAttr::Kind ExtensibilityKind;
3141 IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident;
3142 if (!EnumExtensibilityAttr::ConvertStrToKind(II->getName(),
3143 ExtensibilityKind)) {
3144 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
3145 << Attr.getName() << II;
3146 return;
3147 }
3148
3149 D->addAttr(::new (S.Context) EnumExtensibilityAttr(
3150 Attr.getRange(), S.Context, ExtensibilityKind,
3151 Attr.getAttributeSpellingListIndex()));
3152}
3153
Mike Stumpd3bb5572009-07-24 19:02:52 +00003154/// Handle __attribute__((format_arg((idx)))) attribute based on
Bill Wendling44426052012-12-20 19:22:21 +00003155/// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
Chandler Carruthedc2c642011-07-02 00:01:44 +00003156static void handleFormatArgAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballman00e99962013-08-31 01:11:41 +00003157 Expr *IdxExpr = Attr.getArgAsExpr(0);
Alp Toker601b22c2014-01-21 23:35:24 +00003158 uint64_t Idx;
3159 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 1, IdxExpr, Idx))
Fariborz Jahanianf1c25022009-05-20 17:41:43 +00003160 return;
Chandler Carruth743682b2010-11-16 08:35:43 +00003161
Eric Christopherb64963e2015-08-13 21:34:35 +00003162 // Make sure the format string is really a string.
Alp Toker601b22c2014-01-21 23:35:24 +00003163 QualType Ty = getFunctionOrMethodParamType(D, Idx);
Mike Stumpd3bb5572009-07-24 19:02:52 +00003164
Eric Christopherb64963e2015-08-13 21:34:35 +00003165 bool NotNSStringTy = !isNSStringType(Ty, S.Context);
3166 if (NotNSStringTy &&
Fariborz Jahanianf1c25022009-05-20 17:41:43 +00003167 !isCFStringType(Ty, S.Context) &&
3168 (!Ty->isPointerType() ||
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003169 !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
Fariborz Jahanianf1c25022009-05-20 17:41:43 +00003170 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
Eric Christopherb64963e2015-08-13 21:34:35 +00003171 << "a string type" << IdxExpr->getSourceRange()
3172 << getFunctionOrMethodParamRange(D, 0);
Fariborz Jahanianf1c25022009-05-20 17:41:43 +00003173 return;
Mike Stumpd3bb5572009-07-24 19:02:52 +00003174 }
Chandler Carruthff4c4f02011-07-01 23:49:12 +00003175 Ty = getFunctionOrMethodResultType(D);
Fariborz Jahanianf1c25022009-05-20 17:41:43 +00003176 if (!isNSStringType(Ty, S.Context) &&
3177 !isCFStringType(Ty, S.Context) &&
3178 (!Ty->isPointerType() ||
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003179 !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
Fariborz Jahanianf1c25022009-05-20 17:41:43 +00003180 S.Diag(Attr.getLoc(), diag::err_format_attribute_result_not)
Eric Christopherb64963e2015-08-13 21:34:35 +00003181 << (NotNSStringTy ? "string type" : "NSString")
Aaron Ballman2f9e88b2014-08-04 15:17:29 +00003182 << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, 0);
Fariborz Jahanianf1c25022009-05-20 17:41:43 +00003183 return;
Mike Stumpd3bb5572009-07-24 19:02:52 +00003184 }
3185
Alp Toker601b22c2014-01-21 23:35:24 +00003186 // We cannot use the Idx returned from checkFunctionOrMethodParameterIndex
Aaron Ballmanbe50eb82013-07-30 00:48:57 +00003187 // because that has corrected for the implicit this parameter, and is zero-
3188 // based. The attribute expects what the user wrote explicitly.
3189 llvm::APSInt Val;
3190 IdxExpr->EvaluateAsInt(Val, S.Context);
3191
Michael Han99315932013-01-24 16:46:58 +00003192 D->addAttr(::new (S.Context)
Aaron Ballmanbe50eb82013-07-30 00:48:57 +00003193 FormatArgAttr(Attr.getRange(), S.Context, Val.getZExtValue(),
Michael Han99315932013-01-24 16:46:58 +00003194 Attr.getAttributeSpellingListIndex()));
Fariborz Jahanianf1c25022009-05-20 17:41:43 +00003195}
3196
Daniel Dunbarccbd9a42009-10-18 02:09:17 +00003197enum FormatAttrKind {
3198 CFStringFormat,
3199 NSStringFormat,
3200 StrftimeFormat,
3201 SupportedFormat,
Chris Lattner12161d32010-03-22 21:08:50 +00003202 IgnoredFormat,
Daniel Dunbarccbd9a42009-10-18 02:09:17 +00003203 InvalidFormat
3204};
3205
3206/// getFormatAttrKind - Map from format attribute names to supported format
3207/// types.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003208static FormatAttrKind getFormatAttrKind(StringRef Format) {
Benjamin Kramer96a44b62012-05-16 12:44:25 +00003209 return llvm::StringSwitch<FormatAttrKind>(Format)
Mehdi Amini06d367c2016-10-24 20:39:34 +00003210 // Check for formats that get handled specially.
3211 .Case("NSString", NSStringFormat)
3212 .Case("CFString", CFStringFormat)
3213 .Case("strftime", StrftimeFormat)
Daniel Dunbarccbd9a42009-10-18 02:09:17 +00003214
Mehdi Amini06d367c2016-10-24 20:39:34 +00003215 // Otherwise, check for supported formats.
3216 .Cases("scanf", "printf", "printf0", "strfmon", SupportedFormat)
3217 .Cases("cmn_err", "vcmn_err", "zcmn_err", SupportedFormat)
3218 .Case("kprintf", SupportedFormat) // OpenBSD.
3219 .Case("freebsd_kprintf", SupportedFormat) // FreeBSD.
3220 .Case("os_trace", SupportedFormat)
3221 .Case("os_log", SupportedFormat)
Daniel Dunbarccbd9a42009-10-18 02:09:17 +00003222
Mehdi Amini06d367c2016-10-24 20:39:34 +00003223 .Cases("gcc_diag", "gcc_cdiag", "gcc_cxxdiag", "gcc_tdiag", IgnoredFormat)
3224 .Default(InvalidFormat);
Daniel Dunbarccbd9a42009-10-18 02:09:17 +00003225}
3226
Fariborz Jahanianef5f6212010-06-18 21:44:06 +00003227/// Handle __attribute__((init_priority(priority))) attributes based on
Bill Wendling44426052012-12-20 19:22:21 +00003228/// http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html
Chandler Carruthedc2c642011-07-02 00:01:44 +00003229static void handleInitPriorityAttr(Sema &S, Decl *D,
3230 const AttributeList &Attr) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003231 if (!S.getLangOpts().CPlusPlus) {
Fariborz Jahanianef5f6212010-06-18 21:44:06 +00003232 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
3233 return;
3234 }
3235
Aaron Ballman4a611152013-11-27 16:34:09 +00003236 if (S.getCurFunctionOrMethodDecl()) {
Fariborz Jahanian0bf5ee72010-06-18 23:14:53 +00003237 S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr);
3238 Attr.setInvalid();
3239 return;
3240 }
Aaron Ballman4a611152013-11-27 16:34:09 +00003241 QualType T = cast<VarDecl>(D)->getType();
Fariborz Jahanian0bf5ee72010-06-18 23:14:53 +00003242 if (S.Context.getAsArrayType(T))
3243 T = S.Context.getBaseElementType(T);
3244 if (!T->getAs<RecordType>()) {
3245 S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr);
3246 Attr.setInvalid();
3247 return;
3248 }
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00003249
3250 Expr *E = Attr.getArgAsExpr(0);
3251 uint32_t prioritynum;
3252 if (!checkUInt32Argument(S, Attr, E, prioritynum)) {
Fariborz Jahanianef5f6212010-06-18 21:44:06 +00003253 Attr.setInvalid();
3254 return;
3255 }
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00003256
Fariborz Jahanianef5f6212010-06-18 21:44:06 +00003257 if (prioritynum < 101 || prioritynum > 65535) {
3258 S.Diag(Attr.getLoc(), diag::err_attribute_argument_outof_range)
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00003259 << E->getSourceRange() << Attr.getName() << 101 << 65535;
Fariborz Jahanianef5f6212010-06-18 21:44:06 +00003260 Attr.setInvalid();
3261 return;
3262 }
Michael Han99315932013-01-24 16:46:58 +00003263 D->addAttr(::new (S.Context)
3264 InitPriorityAttr(Attr.getRange(), S.Context, prioritynum,
3265 Attr.getAttributeSpellingListIndex()));
Fariborz Jahanianef5f6212010-06-18 21:44:06 +00003266}
3267
Aaron Ballmanf58070b2013-09-03 21:02:22 +00003268FormatAttr *Sema::mergeFormatAttr(Decl *D, SourceRange Range,
3269 IdentifierInfo *Format, int FormatIdx,
3270 int FirstArg,
Michael Han99315932013-01-24 16:46:58 +00003271 unsigned AttrSpellingListIndex) {
Rafael Espindola92d49452012-05-11 00:36:07 +00003272 // Check whether we already have an equivalent format attribute.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003273 for (auto *F : D->specific_attrs<FormatAttr>()) {
3274 if (F->getType() == Format &&
3275 F->getFormatIdx() == FormatIdx &&
3276 F->getFirstArg() == FirstArg) {
Rafael Espindola92d49452012-05-11 00:36:07 +00003277 // If we don't have a valid location for this attribute, adopt the
3278 // location.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003279 if (F->getLocation().isInvalid())
3280 F->setRange(Range);
Craig Topperc3ec1492014-05-26 06:22:03 +00003281 return nullptr;
Rafael Espindola92d49452012-05-11 00:36:07 +00003282 }
3283 }
3284
Aaron Ballmanf58070b2013-09-03 21:02:22 +00003285 return ::new (Context) FormatAttr(Range, Context, Format, FormatIdx,
3286 FirstArg, AttrSpellingListIndex);
Rafael Espindola92d49452012-05-11 00:36:07 +00003287}
3288
Mike Stumpd3bb5572009-07-24 19:02:52 +00003289/// Handle __attribute__((format(type,idx,firstarg))) attributes based on
Bill Wendling44426052012-12-20 19:22:21 +00003290/// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
Chandler Carruthedc2c642011-07-02 00:01:44 +00003291static void handleFormatAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballman00e99962013-08-31 01:11:41 +00003292 if (!Attr.isArgIdent(0)) {
Aaron Ballman29982272013-07-23 14:03:57 +00003293 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
Aaron Ballman00e99962013-08-31 01:11:41 +00003294 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003295 return;
3296 }
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003297
Chandler Carruth743682b2010-11-16 08:35:43 +00003298 // In C++ the implicit 'this' function parameter also counts, and they are
3299 // counted from one.
Chandler Carruthff4c4f02011-07-01 23:49:12 +00003300 bool HasImplicitThisParam = isInstanceMethod(D);
Alp Toker601b22c2014-01-21 23:35:24 +00003301 unsigned NumArgs = getFunctionOrMethodNumParams(D) + HasImplicitThisParam;
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003302
Aaron Ballman00e99962013-08-31 01:11:41 +00003303 IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident;
3304 StringRef Format = II->getName();
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003305
Aaron Ballman8b5e7ba2015-10-08 19:24:08 +00003306 if (normalizeName(Format)) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00003307 // If we've modified the string name, we need a new identifier for it.
3308 II = &S.Context.Idents.get(Format);
3309 }
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003310
Daniel Dunbarccbd9a42009-10-18 02:09:17 +00003311 // Check for supported formats.
3312 FormatAttrKind Kind = getFormatAttrKind(Format);
Chris Lattner12161d32010-03-22 21:08:50 +00003313
3314 if (Kind == IgnoredFormat)
3315 return;
3316
Daniel Dunbarccbd9a42009-10-18 02:09:17 +00003317 if (Kind == InvalidFormat) {
Chris Lattner3b054132008-11-19 05:08:23 +00003318 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
Aaron Ballman190bad42013-12-26 16:13:50 +00003319 << Attr.getName() << II->getName();
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003320 return;
3321 }
3322
3323 // checks for the 2nd argument
Aaron Ballman00e99962013-08-31 01:11:41 +00003324 Expr *IdxExpr = Attr.getArgAsExpr(1);
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00003325 uint32_t Idx;
3326 if (!checkUInt32Argument(S, Attr, IdxExpr, Idx, 2))
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003327 return;
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003328
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00003329 if (Idx < 1 || Idx > NumArgs) {
Chris Lattner3b054132008-11-19 05:08:23 +00003330 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
Aaron Ballmanfaed0fa2013-12-26 16:30:30 +00003331 << Attr.getName() << 2 << IdxExpr->getSourceRange();
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003332 return;
3333 }
3334
3335 // FIXME: Do we need to bounds check?
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00003336 unsigned ArgIdx = Idx - 1;
Mike Stumpd3bb5572009-07-24 19:02:52 +00003337
Sebastian Redl6eedcc12009-11-17 18:02:24 +00003338 if (HasImplicitThisParam) {
3339 if (ArgIdx == 0) {
Chandler Carruth743682b2010-11-16 08:35:43 +00003340 S.Diag(Attr.getLoc(),
3341 diag::err_format_attribute_implicit_this_format_string)
3342 << IdxExpr->getSourceRange();
Sebastian Redl6eedcc12009-11-17 18:02:24 +00003343 return;
3344 }
3345 ArgIdx--;
3346 }
Mike Stump11289f42009-09-09 15:08:12 +00003347
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003348 // make sure the format string is really a string
Alp Toker601b22c2014-01-21 23:35:24 +00003349 QualType Ty = getFunctionOrMethodParamType(D, ArgIdx);
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003350
Daniel Dunbarccbd9a42009-10-18 02:09:17 +00003351 if (Kind == CFStringFormat) {
Daniel Dunbar980c6692008-09-26 03:32:58 +00003352 if (!isCFStringType(Ty, S.Context)) {
Chris Lattner3b054132008-11-19 05:08:23 +00003353 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
Aaron Ballmandfe8cc52014-08-04 15:26:33 +00003354 << "a CFString" << IdxExpr->getSourceRange()
3355 << getFunctionOrMethodParamRange(D, ArgIdx);
Daniel Dunbar980c6692008-09-26 03:32:58 +00003356 return;
3357 }
Daniel Dunbarccbd9a42009-10-18 02:09:17 +00003358 } else if (Kind == NSStringFormat) {
Mike Stump87c57ac2009-05-16 07:39:55 +00003359 // FIXME: do we need to check if the type is NSString*? What are the
3360 // semantics?
Chris Lattnerb632a6e2008-06-29 00:43:07 +00003361 if (!isNSStringType(Ty, S.Context)) {
Chris Lattner3b054132008-11-19 05:08:23 +00003362 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
Aaron Ballmandfe8cc52014-08-04 15:26:33 +00003363 << "an NSString" << IdxExpr->getSourceRange()
3364 << getFunctionOrMethodParamRange(D, ArgIdx);
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003365 return;
Mike Stumpd3bb5572009-07-24 19:02:52 +00003366 }
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003367 } else if (!Ty->isPointerType() ||
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003368 !Ty->getAs<PointerType>()->getPointeeType()->isCharType()) {
Chris Lattner3b054132008-11-19 05:08:23 +00003369 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
Aaron Ballmandfe8cc52014-08-04 15:26:33 +00003370 << "a string type" << IdxExpr->getSourceRange()
3371 << getFunctionOrMethodParamRange(D, ArgIdx);
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003372 return;
3373 }
3374
3375 // check the 3rd argument
Aaron Ballman00e99962013-08-31 01:11:41 +00003376 Expr *FirstArgExpr = Attr.getArgAsExpr(2);
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00003377 uint32_t FirstArg;
3378 if (!checkUInt32Argument(S, Attr, FirstArgExpr, FirstArg, 3))
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003379 return;
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003380
3381 // check if the function is variadic if the 3rd argument non-zero
3382 if (FirstArg != 0) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00003383 if (isFunctionOrMethodVariadic(D)) {
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003384 ++NumArgs; // +1 for ...
3385 } else {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00003386 S.Diag(D->getLocation(), diag::err_format_attribute_requires_variadic);
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003387 return;
3388 }
3389 }
3390
Chris Lattner4bd8dd82008-11-19 08:23:25 +00003391 // strftime requires FirstArg to be 0 because it doesn't read from any
3392 // variable the input is just the current time + the format string.
Daniel Dunbarccbd9a42009-10-18 02:09:17 +00003393 if (Kind == StrftimeFormat) {
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003394 if (FirstArg != 0) {
Chris Lattner3b054132008-11-19 05:08:23 +00003395 S.Diag(Attr.getLoc(), diag::err_format_strftime_third_parameter)
3396 << FirstArgExpr->getSourceRange();
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003397 return;
3398 }
3399 // if 0 it disables parameter checking (to use with e.g. va_list)
3400 } else if (FirstArg != 0 && FirstArg != NumArgs) {
Chris Lattner3b054132008-11-19 05:08:23 +00003401 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
Aaron Ballmanfaed0fa2013-12-26 16:30:30 +00003402 << Attr.getName() << 3 << FirstArgExpr->getSourceRange();
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003403 return;
3404 }
3405
Aaron Ballmanf58070b2013-09-03 21:02:22 +00003406 FormatAttr *NewAttr = S.mergeFormatAttr(D, Attr.getRange(), II,
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00003407 Idx, FirstArg,
Michael Han99315932013-01-24 16:46:58 +00003408 Attr.getAttributeSpellingListIndex());
Rafael Espindolae200f1c2012-05-13 03:25:18 +00003409 if (NewAttr)
3410 D->addAttr(NewAttr);
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003411}
3412
Chandler Carruthedc2c642011-07-02 00:01:44 +00003413static void handleTransparentUnionAttr(Sema &S, Decl *D,
3414 const AttributeList &Attr) {
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003415 // Try to find the underlying union declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +00003416 RecordDecl *RD = nullptr;
Chandler Carruthff4c4f02011-07-01 23:49:12 +00003417 TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003418 if (TD && TD->getUnderlyingType()->isUnionType())
3419 RD = TD->getUnderlyingType()->getAsUnionType()->getDecl();
3420 else
Chandler Carruthff4c4f02011-07-01 23:49:12 +00003421 RD = dyn_cast<RecordDecl>(D);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003422
3423 if (!RD || !RD->isUnion()) {
Chris Lattner3b054132008-11-19 05:08:23 +00003424 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
John McCall5fca7ea2011-03-02 12:29:23 +00003425 << Attr.getName() << ExpectedUnion;
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003426 return;
3427 }
3428
John McCallf937c022011-10-07 06:10:15 +00003429 if (!RD->isCompleteDefinition()) {
Erich Keane2fe684b2017-02-28 20:44:39 +00003430 if (!RD->isBeingDefined())
3431 S.Diag(Attr.getLoc(),
3432 diag::warn_transparent_union_attribute_not_definition);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003433 return;
3434 }
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003435
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003436 RecordDecl::field_iterator Field = RD->field_begin(),
3437 FieldEnd = RD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003438 if (Field == FieldEnd) {
3439 S.Diag(Attr.getLoc(), diag::warn_transparent_union_attribute_zero_fields);
3440 return;
3441 }
Eli Friedman7c9ba6a2008-09-02 05:19:23 +00003442
David Blaikie40ed2972012-06-06 20:45:41 +00003443 FieldDecl *FirstField = *Field;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003444 QualType FirstType = FirstField->getType();
Douglas Gregor21872662010-06-30 17:24:13 +00003445 if (FirstType->hasFloatingRepresentation() || FirstType->isVectorType()) {
Mike Stumpd3bb5572009-07-24 19:02:52 +00003446 S.Diag(FirstField->getLocation(),
Douglas Gregor21872662010-06-30 17:24:13 +00003447 diag::warn_transparent_union_attribute_floating)
3448 << FirstType->isVectorType() << FirstType;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003449 return;
3450 }
3451
Alex Lorenz6f4bc4f2016-10-06 09:47:29 +00003452 if (FirstType->isIncompleteType())
3453 return;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003454 uint64_t FirstSize = S.Context.getTypeSize(FirstType);
3455 uint64_t FirstAlign = S.Context.getTypeAlign(FirstType);
3456 for (; Field != FieldEnd; ++Field) {
3457 QualType FieldType = Field->getType();
Alex Lorenz6f4bc4f2016-10-06 09:47:29 +00003458 if (FieldType->isIncompleteType())
3459 return;
Aaron Ballman54fe5eb2014-01-28 01:47:34 +00003460 // FIXME: this isn't fully correct; we also need to test whether the
3461 // members of the union would all have the same calling convention as the
3462 // first member of the union. Checking just the size and alignment isn't
3463 // sufficient (consider structs passed on the stack instead of in registers
3464 // as an example).
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003465 if (S.Context.getTypeSize(FieldType) != FirstSize ||
Aaron Ballman54fe5eb2014-01-28 01:47:34 +00003466 S.Context.getTypeAlign(FieldType) > FirstAlign) {
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003467 // Warn if we drop the attribute.
3468 bool isSize = S.Context.getTypeSize(FieldType) != FirstSize;
Mike Stumpd3bb5572009-07-24 19:02:52 +00003469 unsigned FieldBits = isSize? S.Context.getTypeSize(FieldType)
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003470 : S.Context.getTypeAlign(FieldType);
Mike Stumpd3bb5572009-07-24 19:02:52 +00003471 S.Diag(Field->getLocation(),
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003472 diag::warn_transparent_union_attribute_field_size_align)
3473 << isSize << Field->getDeclName() << FieldBits;
3474 unsigned FirstBits = isSize? FirstSize : FirstAlign;
Mike Stumpd3bb5572009-07-24 19:02:52 +00003475 S.Diag(FirstField->getLocation(),
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003476 diag::note_transparent_union_first_field_size_align)
3477 << isSize << FirstBits;
Eli Friedman7c9ba6a2008-09-02 05:19:23 +00003478 return;
3479 }
3480 }
3481
Michael Han99315932013-01-24 16:46:58 +00003482 RD->addAttr(::new (S.Context)
3483 TransparentUnionAttr(Attr.getRange(), S.Context,
3484 Attr.getAttributeSpellingListIndex()));
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003485}
3486
Chandler Carruthedc2c642011-07-02 00:01:44 +00003487static void handleAnnotateAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003488 // Make sure that there is a string literal as the annotation's single
3489 // argument.
Benjamin Kramer6ee15622013-09-13 15:35:43 +00003490 StringRef Str;
Tim Northover6a6b63b2013-10-01 14:34:18 +00003491 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str))
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003492 return;
Julien Lerouge5a6b6982011-09-09 22:41:49 +00003493
3494 // Don't duplicate annotations that are already set.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003495 for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
3496 if (I->getAnnotation() == Str)
Benjamin Kramer6ee15622013-09-13 15:35:43 +00003497 return;
Julien Lerouge5a6b6982011-09-09 22:41:49 +00003498 }
Michael Han99315932013-01-24 16:46:58 +00003499
3500 D->addAttr(::new (S.Context)
Benjamin Kramer6ee15622013-09-13 15:35:43 +00003501 AnnotateAttr(Attr.getRange(), S.Context, Str,
Michael Han99315932013-01-24 16:46:58 +00003502 Attr.getAttributeSpellingListIndex()));
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003503}
3504
Hal Finkel1b0d24e2014-10-02 21:21:25 +00003505static void handleAlignValueAttr(Sema &S, Decl *D,
3506 const AttributeList &Attr) {
3507 S.AddAlignValueAttr(Attr.getRange(), D, Attr.getArgAsExpr(0),
3508 Attr.getAttributeSpellingListIndex());
3509}
3510
3511void Sema::AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E,
3512 unsigned SpellingListIndex) {
3513 AlignValueAttr TmpAttr(AttrRange, Context, E, SpellingListIndex);
3514 SourceLocation AttrLoc = AttrRange.getBegin();
3515
3516 QualType T;
3517 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
3518 T = TD->getUnderlyingType();
3519 else if (ValueDecl *VD = dyn_cast<ValueDecl>(D))
3520 T = VD->getType();
3521 else
3522 llvm_unreachable("Unknown decl type for align_value");
3523
3524 if (!T->isDependentType() && !T->isAnyPointerType() &&
3525 !T->isReferenceType() && !T->isMemberPointerType()) {
3526 Diag(AttrLoc, diag::warn_attribute_pointer_or_reference_only)
3527 << &TmpAttr /*TmpAttr.getName()*/ << T << D->getSourceRange();
3528 return;
3529 }
3530
3531 if (!E->isValueDependent()) {
David Majnemer0be6bd02015-07-26 09:02:21 +00003532 llvm::APSInt Alignment;
Hal Finkel1b0d24e2014-10-02 21:21:25 +00003533 ExprResult ICE
3534 = VerifyIntegerConstantExpression(E, &Alignment,
3535 diag::err_align_value_attribute_argument_not_int,
3536 /*AllowFold*/ false);
3537 if (ICE.isInvalid())
3538 return;
3539
3540 if (!Alignment.isPowerOf2()) {
3541 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
3542 << E->getSourceRange();
3543 return;
3544 }
3545
3546 D->addAttr(::new (Context)
3547 AlignValueAttr(AttrRange, Context, ICE.get(),
3548 SpellingListIndex));
3549 return;
3550 }
3551
3552 // Save dependent expressions in the AST to be instantiated.
3553 D->addAttr(::new (Context) AlignValueAttr(TmpAttr));
Hal Finkel1b0d24e2014-10-02 21:21:25 +00003554}
3555
Chandler Carruthedc2c642011-07-02 00:01:44 +00003556static void handleAlignedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003557 // check the attribute arguments.
Chris Lattner4a927cb2008-06-28 23:36:30 +00003558 if (Attr.getNumArgs() > 1) {
Aaron Ballmanb7243382013-07-23 19:30:11 +00003559 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
3560 << Attr.getName() << 1;
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003561 return;
3562 }
Aaron Ballman478faed2012-06-19 22:09:27 +00003563
Richard Smith848e1f12013-02-01 08:12:08 +00003564 if (Attr.getNumArgs() == 0) {
3565 D->addAttr(::new (S.Context) AlignedAttr(Attr.getRange(), S.Context,
Craig Topperc3ec1492014-05-26 06:22:03 +00003566 true, nullptr, Attr.getAttributeSpellingListIndex()));
Richard Smith848e1f12013-02-01 08:12:08 +00003567 return;
3568 }
3569
Aaron Ballman00e99962013-08-31 01:11:41 +00003570 Expr *E = Attr.getArgAsExpr(0);
Richard Smith44c247f2013-02-22 08:32:16 +00003571 if (Attr.isPackExpansion() && !E->containsUnexpandedParameterPack()) {
3572 S.Diag(Attr.getEllipsisLoc(),
3573 diag::err_pack_expansion_without_parameter_packs);
3574 return;
3575 }
3576
3577 if (!Attr.isPackExpansion() && S.DiagnoseUnexpandedParameterPack(E))
3578 return;
3579
David Majnemer26a1e0e2015-04-07 02:37:09 +00003580 if (E->isValueDependent()) {
3581 if (const auto *TND = dyn_cast<TypedefNameDecl>(D)) {
3582 if (!TND->getUnderlyingType()->isDependentType()) {
3583 S.Diag(Attr.getLoc(), diag::err_alignment_dependent_typedef_name)
3584 << E->getSourceRange();
3585 return;
3586 }
3587 }
3588 }
3589
Richard Smith44c247f2013-02-22 08:32:16 +00003590 S.AddAlignedAttr(Attr.getRange(), D, E, Attr.getAttributeSpellingListIndex(),
3591 Attr.isPackExpansion());
Richard Smith848e1f12013-02-01 08:12:08 +00003592}
3593
3594void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
Richard Smith44c247f2013-02-22 08:32:16 +00003595 unsigned SpellingListIndex, bool IsPackExpansion) {
Richard Smith848e1f12013-02-01 08:12:08 +00003596 AlignedAttr TmpAttr(AttrRange, Context, true, E, SpellingListIndex);
3597 SourceLocation AttrLoc = AttrRange.getBegin();
3598
Richard Smith1dba27c2013-01-29 09:02:09 +00003599 // C++11 alignas(...) and C11 _Alignas(...) have additional requirements.
Richard Smith848e1f12013-02-01 08:12:08 +00003600 if (TmpAttr.isAlignas()) {
Richard Smith1dba27c2013-01-29 09:02:09 +00003601 // C++11 [dcl.align]p1:
3602 // An alignment-specifier may be applied to a variable or to a class
3603 // data member, but it shall not be applied to a bit-field, a function
3604 // parameter, the formal parameter of a catch clause, or a variable
3605 // declared with the register storage class specifier. An
3606 // alignment-specifier may also be applied to the declaration of a class
3607 // or enumeration type.
3608 // C11 6.7.5/2:
3609 // An alignment attribute shall not be specified in a declaration of
3610 // a typedef, or a bit-field, or a function, or a parameter, or an
3611 // object declared with the register storage-class specifier.
3612 int DiagKind = -1;
3613 if (isa<ParmVarDecl>(D)) {
3614 DiagKind = 0;
3615 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3616 if (VD->getStorageClass() == SC_Register)
3617 DiagKind = 1;
3618 if (VD->isExceptionVariable())
3619 DiagKind = 2;
3620 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
3621 if (FD->isBitField())
3622 DiagKind = 3;
3623 } else if (!isa<TagDecl>(D)) {
Aaron Ballman3d216a52014-01-02 23:39:11 +00003624 Diag(AttrLoc, diag::err_attribute_wrong_decl_type) << &TmpAttr
Richard Smith9eaab4b2013-02-01 08:25:07 +00003625 << (TmpAttr.isC11() ? ExpectedVariableOrField
3626 : ExpectedVariableFieldOrTag);
Richard Smith1dba27c2013-01-29 09:02:09 +00003627 return;
3628 }
3629 if (DiagKind != -1) {
Richard Smith848e1f12013-02-01 08:12:08 +00003630 Diag(AttrLoc, diag::err_alignas_attribute_wrong_decl_type)
Aaron Ballman3d216a52014-01-02 23:39:11 +00003631 << &TmpAttr << DiagKind;
Richard Smith1dba27c2013-01-29 09:02:09 +00003632 return;
3633 }
3634 }
3635
Chandler Carruthf40c42f2010-06-25 03:22:07 +00003636 if (E->isTypeDependent() || E->isValueDependent()) {
3637 // Save dependent expressions in the AST to be instantiated.
Richard Smith44c247f2013-02-22 08:32:16 +00003638 AlignedAttr *AA = ::new (Context) AlignedAttr(TmpAttr);
3639 AA->setPackExpansion(IsPackExpansion);
3640 D->addAttr(AA);
Chandler Carruthf40c42f2010-06-25 03:22:07 +00003641 return;
3642 }
Michael Hanaf02bbe2013-02-01 01:19:17 +00003643
Alexis Huntdcfba7b2010-08-18 23:23:40 +00003644 // FIXME: Cache the number on the Attr object?
David Majnemer0be6bd02015-07-26 09:02:21 +00003645 llvm::APSInt Alignment;
Douglas Gregore2b37442012-05-04 22:38:52 +00003646 ExprResult ICE
3647 = VerifyIntegerConstantExpression(E, &Alignment,
3648 diag::err_aligned_attribute_argument_not_int,
3649 /*AllowFold*/ false);
Richard Smithf4c51d92012-02-04 09:53:13 +00003650 if (ICE.isInvalid())
Chris Lattner4627b742008-06-28 23:50:44 +00003651 return;
Richard Smith848e1f12013-02-01 08:12:08 +00003652
David Majnemer0be6bd02015-07-26 09:02:21 +00003653 uint64_t AlignVal = Alignment.getZExtValue();
3654
Richard Smith848e1f12013-02-01 08:12:08 +00003655 // C++11 [dcl.align]p2:
3656 // -- if the constant expression evaluates to zero, the alignment
3657 // specifier shall have no effect
3658 // C11 6.7.5p6:
3659 // An alignment specification of zero has no effect.
Paul Robinsond30e2ee2015-07-14 20:52:32 +00003660 if (!(TmpAttr.isAlignas() && !Alignment)) {
David Majnemer0be6bd02015-07-26 09:02:21 +00003661 if (!llvm::isPowerOf2_64(AlignVal)) {
Paul Robinsond30e2ee2015-07-14 20:52:32 +00003662 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
3663 << E->getSourceRange();
3664 return;
3665 }
Daniel Dunbar6e8c07d2009-02-16 23:37:57 +00003666 }
Michael Hanaf02bbe2013-02-01 01:19:17 +00003667
David Majnemerabecae72014-02-12 20:36:10 +00003668 // Alignment calculations can wrap around if it's greater than 2**28.
David Majnemer29c69db2015-07-26 01:48:59 +00003669 unsigned MaxValidAlignment =
3670 Context.getTargetInfo().getTriple().isOSBinFormatCOFF() ? 8192
3671 : 268435456;
David Majnemer0be6bd02015-07-26 09:02:21 +00003672 if (AlignVal > MaxValidAlignment) {
David Majnemerabecae72014-02-12 20:36:10 +00003673 Diag(AttrLoc, diag::err_attribute_aligned_too_great) << MaxValidAlignment
3674 << E->getSourceRange();
3675 return;
Aaron Ballman478faed2012-06-19 22:09:27 +00003676 }
Daniel Dunbar6e8c07d2009-02-16 23:37:57 +00003677
David Majnemer0be6bd02015-07-26 09:02:21 +00003678 if (Context.getTargetInfo().isTLSSupported()) {
3679 unsigned MaxTLSAlign =
3680 Context.toCharUnitsFromBits(Context.getTargetInfo().getMaxTLSAlign())
3681 .getQuantity();
3682 auto *VD = dyn_cast<VarDecl>(D);
3683 if (MaxTLSAlign && AlignVal > MaxTLSAlign && VD &&
3684 VD->getTLSKind() != VarDecl::TLS_None) {
3685 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
3686 << (unsigned)AlignVal << VD << MaxTLSAlign;
3687 return;
3688 }
3689 }
3690
Richard Smith44c247f2013-02-22 08:32:16 +00003691 AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, true,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003692 ICE.get(), SpellingListIndex);
Richard Smith44c247f2013-02-22 08:32:16 +00003693 AA->setPackExpansion(IsPackExpansion);
3694 D->addAttr(AA);
Alexis Huntdcfba7b2010-08-18 23:23:40 +00003695}
3696
Michael Hanaf02bbe2013-02-01 01:19:17 +00003697void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *TS,
Richard Smith44c247f2013-02-22 08:32:16 +00003698 unsigned SpellingListIndex, bool IsPackExpansion) {
Alexis Huntdcfba7b2010-08-18 23:23:40 +00003699 // FIXME: Cache the number on the Attr object if non-dependent?
3700 // FIXME: Perform checking of type validity
Richard Smith44c247f2013-02-22 08:32:16 +00003701 AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, false, TS,
3702 SpellingListIndex);
3703 AA->setPackExpansion(IsPackExpansion);
3704 D->addAttr(AA);
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003705}
Chris Lattneracbc2d22008-06-27 22:18:37 +00003706
Richard Smith848e1f12013-02-01 08:12:08 +00003707void Sema::CheckAlignasUnderalignment(Decl *D) {
3708 assert(D->hasAttrs() && "no attributes on decl");
3709
David Majnemer475b25e2015-01-21 10:54:38 +00003710 QualType UnderlyingTy, DiagTy;
3711 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
3712 UnderlyingTy = DiagTy = VD->getType();
3713 } else {
3714 UnderlyingTy = DiagTy = Context.getTagDeclType(cast<TagDecl>(D));
3715 if (EnumDecl *ED = dyn_cast<EnumDecl>(D))
3716 UnderlyingTy = ED->getIntegerType();
3717 }
3718 if (DiagTy->isDependentType() || DiagTy->isIncompleteType())
Richard Smith848e1f12013-02-01 08:12:08 +00003719 return;
3720
3721 // C++11 [dcl.align]p5, C11 6.7.5/4:
3722 // The combined effect of all alignment attributes in a declaration shall
3723 // not specify an alignment that is less strict than the alignment that
3724 // would otherwise be required for the entity being declared.
Craig Topperc3ec1492014-05-26 06:22:03 +00003725 AlignedAttr *AlignasAttr = nullptr;
Richard Smith848e1f12013-02-01 08:12:08 +00003726 unsigned Align = 0;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003727 for (auto *I : D->specific_attrs<AlignedAttr>()) {
Richard Smith848e1f12013-02-01 08:12:08 +00003728 if (I->isAlignmentDependent())
3729 return;
3730 if (I->isAlignas())
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003731 AlignasAttr = I;
Richard Smith848e1f12013-02-01 08:12:08 +00003732 Align = std::max(Align, I->getAlignment(Context));
3733 }
3734
3735 if (AlignasAttr && Align) {
3736 CharUnits RequestedAlign = Context.toCharUnitsFromBits(Align);
David Majnemer475b25e2015-01-21 10:54:38 +00003737 CharUnits NaturalAlign = Context.getTypeAlignInChars(UnderlyingTy);
Richard Smith848e1f12013-02-01 08:12:08 +00003738 if (NaturalAlign > RequestedAlign)
3739 Diag(AlignasAttr->getLocation(), diag::err_alignas_underaligned)
David Majnemer475b25e2015-01-21 10:54:38 +00003740 << DiagTy << (unsigned)NaturalAlign.getQuantity();
Richard Smith848e1f12013-02-01 08:12:08 +00003741 }
3742}
3743
David Majnemer2c4e00a2014-01-29 22:07:36 +00003744bool Sema::checkMSInheritanceAttrOnDefinition(
David Majnemer4bb09802014-02-10 19:50:15 +00003745 CXXRecordDecl *RD, SourceRange Range, bool BestCase,
David Majnemer2c4e00a2014-01-29 22:07:36 +00003746 MSInheritanceAttr::Spelling SemanticSpelling) {
3747 assert(RD->hasDefinition() && "RD has no definition!");
3748
David Majnemer98c9ee22014-02-07 00:43:07 +00003749 // We may not have seen base specifiers or any virtual methods yet. We will
3750 // have to wait until the record is defined to catch any mismatches.
3751 if (!RD->getDefinition()->isCompleteDefinition())
3752 return false;
David Majnemer2c4e00a2014-01-29 22:07:36 +00003753
David Majnemer98c9ee22014-02-07 00:43:07 +00003754 // The unspecified model never matches what a definition could need.
3755 if (SemanticSpelling == MSInheritanceAttr::Keyword_unspecified_inheritance)
3756 return false;
3757
David Majnemer4bb09802014-02-10 19:50:15 +00003758 if (BestCase) {
3759 if (RD->calculateInheritanceModel() == SemanticSpelling)
3760 return false;
3761 } else {
3762 if (RD->calculateInheritanceModel() <= SemanticSpelling)
3763 return false;
3764 }
David Majnemer98c9ee22014-02-07 00:43:07 +00003765
3766 Diag(Range.getBegin(), diag::err_mismatched_ms_inheritance)
3767 << 0 /*definition*/;
3768 Diag(RD->getDefinition()->getLocation(), diag::note_defined_here)
3769 << RD->getNameAsString();
3770 return true;
David Majnemer2c4e00a2014-01-29 22:07:36 +00003771}
3772
Alexey Bataevf278eb12015-11-19 10:13:11 +00003773/// parseModeAttrArg - Parses attribute mode string and returns parsed type
3774/// attribute.
3775static void parseModeAttrArg(Sema &S, StringRef Str, unsigned &DestWidth,
3776 bool &IntegerMode, bool &ComplexMode) {
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003777 IntegerMode = true;
3778 ComplexMode = false;
Daniel Dunbarafff4342009-10-18 02:09:24 +00003779 switch (Str.size()) {
Chris Lattneracbc2d22008-06-27 22:18:37 +00003780 case 2:
Eli Friedman4735374e2009-03-03 06:41:03 +00003781 switch (Str[0]) {
Alexey Bataevf278eb12015-11-19 10:13:11 +00003782 case 'Q':
3783 DestWidth = 8;
3784 break;
3785 case 'H':
3786 DestWidth = 16;
3787 break;
3788 case 'S':
3789 DestWidth = 32;
3790 break;
3791 case 'D':
3792 DestWidth = 64;
3793 break;
3794 case 'X':
3795 DestWidth = 96;
3796 break;
3797 case 'T':
3798 DestWidth = 128;
3799 break;
Eli Friedman4735374e2009-03-03 06:41:03 +00003800 }
3801 if (Str[1] == 'F') {
3802 IntegerMode = false;
3803 } else if (Str[1] == 'C') {
3804 IntegerMode = false;
3805 ComplexMode = true;
3806 } else if (Str[1] != 'I') {
3807 DestWidth = 0;
3808 }
Chris Lattneracbc2d22008-06-27 22:18:37 +00003809 break;
3810 case 4:
3811 // FIXME: glibc uses 'word' to define register_t; this is narrower than a
3812 // pointer on PIC16 and other embedded platforms.
Daniel Dunbarafff4342009-10-18 02:09:24 +00003813 if (Str == "word")
Reid Klecknerf27e7522016-02-01 18:58:24 +00003814 DestWidth = S.Context.getTargetInfo().getRegisterWidth();
Daniel Dunbarafff4342009-10-18 02:09:24 +00003815 else if (Str == "byte")
Douglas Gregore8bbc122011-09-02 00:18:52 +00003816 DestWidth = S.Context.getTargetInfo().getCharWidth();
Chris Lattneracbc2d22008-06-27 22:18:37 +00003817 break;
3818 case 7:
Daniel Dunbarafff4342009-10-18 02:09:24 +00003819 if (Str == "pointer")
Douglas Gregore8bbc122011-09-02 00:18:52 +00003820 DestWidth = S.Context.getTargetInfo().getPointerWidth(0);
Chris Lattneracbc2d22008-06-27 22:18:37 +00003821 break;
Rafael Espindolaf0dafd32013-01-07 19:58:54 +00003822 case 11:
3823 if (Str == "unwind_word")
Rafael Espindola03705972013-01-07 20:01:57 +00003824 DestWidth = S.Context.getTargetInfo().getUnwindWordWidth();
Rafael Espindolaf0dafd32013-01-07 19:58:54 +00003825 break;
Chris Lattneracbc2d22008-06-27 22:18:37 +00003826 }
Alexey Bataevf278eb12015-11-19 10:13:11 +00003827}
3828
3829/// handleModeAttr - This attribute modifies the width of a decl with primitive
3830/// type.
3831///
3832/// Despite what would be logical, the mode attribute is a decl attribute, not a
3833/// type attribute: 'int ** __attribute((mode(HI))) *G;' tries to make 'G' be
3834/// HImode, not an intermediate pointer.
3835static void handleModeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3836 // This attribute isn't documented, but glibc uses it. It changes
3837 // the width of an int or unsigned int to the specified size.
3838 if (!Attr.isArgIdent(0)) {
3839 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << Attr.getName()
3840 << AANT_ArgumentIdentifier;
3841 return;
3842 }
3843
3844 IdentifierInfo *Name = Attr.getArgAsIdent(0)->Ident;
Alexey Bataevf278eb12015-11-19 10:13:11 +00003845
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003846 S.AddModeAttr(Attr.getRange(), D, Name, Attr.getAttributeSpellingListIndex());
3847}
3848
3849void Sema::AddModeAttr(SourceRange AttrRange, Decl *D, IdentifierInfo *Name,
3850 unsigned SpellingListIndex, bool InInstantiation) {
3851 StringRef Str = Name->getName();
Alexey Bataevf278eb12015-11-19 10:13:11 +00003852 normalizeName(Str);
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003853 SourceLocation AttrLoc = AttrRange.getBegin();
Alexey Bataevf278eb12015-11-19 10:13:11 +00003854
3855 unsigned DestWidth = 0;
3856 bool IntegerMode = true;
3857 bool ComplexMode = false;
3858 llvm::APInt VectorSize(64, 0);
3859 if (Str.size() >= 4 && Str[0] == 'V') {
3860 // Minimal length of vector mode is 4: 'V' + NUMBER(>=1) + TYPE(>=2).
3861 size_t StrSize = Str.size();
3862 size_t VectorStringLength = 0;
3863 while ((VectorStringLength + 1) < StrSize &&
3864 isdigit(Str[VectorStringLength + 1]))
3865 ++VectorStringLength;
3866 if (VectorStringLength &&
3867 !Str.substr(1, VectorStringLength).getAsInteger(10, VectorSize) &&
3868 VectorSize.isPowerOf2()) {
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003869 parseModeAttrArg(*this, Str.substr(VectorStringLength + 1), DestWidth,
Alexey Bataevf278eb12015-11-19 10:13:11 +00003870 IntegerMode, ComplexMode);
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003871 // Avoid duplicate warning from template instantiation.
3872 if (!InInstantiation)
3873 Diag(AttrLoc, diag::warn_vector_mode_deprecated);
Alexey Bataevf278eb12015-11-19 10:13:11 +00003874 } else {
3875 VectorSize = 0;
3876 }
3877 }
3878
3879 if (!VectorSize)
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003880 parseModeAttrArg(*this, Str, DestWidth, IntegerMode, ComplexMode);
3881
3882 // FIXME: Sync this with InitializePredefinedMacros; we need to match int8_t
3883 // and friends, at least with glibc.
3884 // FIXME: Make sure floating-point mappings are accurate
3885 // FIXME: Support XF and TF types
3886 if (!DestWidth) {
3887 Diag(AttrLoc, diag::err_machine_mode) << 0 /*Unknown*/ << Name;
3888 return;
3889 }
Chris Lattneracbc2d22008-06-27 22:18:37 +00003890
3891 QualType OldTy;
Richard Smithdda56e42011-04-15 14:24:37 +00003892 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
Chris Lattneracbc2d22008-06-27 22:18:37 +00003893 OldTy = TD->getUnderlyingType();
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003894 else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
3895 // Something like 'typedef enum { X } __attribute__((mode(XX))) T;'.
3896 // Try to get type from enum declaration, default to int.
3897 OldTy = ED->getIntegerType();
3898 if (OldTy.isNull())
3899 OldTy = Context.IntTy;
3900 } else
Aaron Ballman6c8848a2016-01-19 22:54:26 +00003901 OldTy = cast<ValueDecl>(D)->getType();
Eli Friedman4735374e2009-03-03 06:41:03 +00003902
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003903 if (OldTy->isDependentType()) {
3904 D->addAttr(::new (Context)
3905 ModeAttr(AttrRange, Context, Name, SpellingListIndex));
3906 return;
3907 }
3908
Alexey Bataev326057d2015-06-19 07:46:21 +00003909 // Base type can also be a vector type (see PR17453).
3910 // Distinguish between base type and base element type.
3911 QualType OldElemTy = OldTy;
3912 if (const VectorType *VT = OldTy->getAs<VectorType>())
3913 OldElemTy = VT->getElementType();
3914
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003915 // GCC allows 'mode' attribute on enumeration types (even incomplete), except
3916 // for vector modes. So, 'enum X __attribute__((mode(QI)));' forms a complete
3917 // type, 'enum { A } __attribute__((mode(V4SI)))' is rejected.
3918 if ((isa<EnumDecl>(D) || OldElemTy->getAs<EnumType>()) &&
3919 VectorSize.getBoolValue()) {
3920 Diag(AttrLoc, diag::err_enum_mode_vector_type) << Name << AttrRange;
3921 return;
3922 }
3923 bool IntegralOrAnyEnumType =
3924 OldElemTy->isIntegralOrEnumerationType() || OldElemTy->getAs<EnumType>();
3925
3926 if (!OldElemTy->getAs<BuiltinType>() && !OldElemTy->isComplexType() &&
3927 !IntegralOrAnyEnumType)
3928 Diag(AttrLoc, diag::err_mode_not_primitive);
Eli Friedman4735374e2009-03-03 06:41:03 +00003929 else if (IntegerMode) {
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003930 if (!IntegralOrAnyEnumType)
3931 Diag(AttrLoc, diag::err_mode_wrong_type);
Eli Friedman4735374e2009-03-03 06:41:03 +00003932 } else if (ComplexMode) {
Alexey Bataev326057d2015-06-19 07:46:21 +00003933 if (!OldElemTy->isComplexType())
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003934 Diag(AttrLoc, diag::err_mode_wrong_type);
Eli Friedman4735374e2009-03-03 06:41:03 +00003935 } else {
Alexey Bataev326057d2015-06-19 07:46:21 +00003936 if (!OldElemTy->isFloatingType())
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003937 Diag(AttrLoc, diag::err_mode_wrong_type);
Stepan Dyatkovskiyb88c30f2013-09-18 09:08:52 +00003938 }
3939
Alexey Bataev326057d2015-06-19 07:46:21 +00003940 QualType NewElemTy;
Stepan Dyatkovskiyb88c30f2013-09-18 09:08:52 +00003941
3942 if (IntegerMode)
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003943 NewElemTy = Context.getIntTypeForBitwidth(DestWidth,
3944 OldElemTy->isSignedIntegerType());
Stepan Dyatkovskiyb88c30f2013-09-18 09:08:52 +00003945 else
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003946 NewElemTy = Context.getRealTypeForBitwidth(DestWidth);
Stepan Dyatkovskiyb88c30f2013-09-18 09:08:52 +00003947
Alexey Bataev326057d2015-06-19 07:46:21 +00003948 if (NewElemTy.isNull()) {
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003949 Diag(AttrLoc, diag::err_machine_mode) << 1 /*Unsupported*/ << Name;
Chris Lattneracbc2d22008-06-27 22:18:37 +00003950 return;
Chris Lattneracbc2d22008-06-27 22:18:37 +00003951 }
3952
Eli Friedman4735374e2009-03-03 06:41:03 +00003953 if (ComplexMode) {
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003954 NewElemTy = Context.getComplexType(NewElemTy);
Alexey Bataev326057d2015-06-19 07:46:21 +00003955 }
3956
3957 QualType NewTy = NewElemTy;
Alexey Bataevf278eb12015-11-19 10:13:11 +00003958 if (VectorSize.getBoolValue()) {
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003959 NewTy = Context.getVectorType(NewTy, VectorSize.getZExtValue(),
3960 VectorType::GenericVector);
Alexey Bataevf278eb12015-11-19 10:13:11 +00003961 } else if (const VectorType *OldVT = OldTy->getAs<VectorType>()) {
Alexey Bataev326057d2015-06-19 07:46:21 +00003962 // Complex machine mode does not support base vector types.
3963 if (ComplexMode) {
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003964 Diag(AttrLoc, diag::err_complex_mode_vector_type);
Alexey Bataev326057d2015-06-19 07:46:21 +00003965 return;
3966 }
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003967 unsigned NumElements = Context.getTypeSize(OldElemTy) *
Alexey Bataev326057d2015-06-19 07:46:21 +00003968 OldVT->getNumElements() /
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003969 Context.getTypeSize(NewElemTy);
Alexey Bataev326057d2015-06-19 07:46:21 +00003970 NewTy =
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003971 Context.getVectorType(NewElemTy, NumElements, OldVT->getVectorKind());
Alexey Bataev326057d2015-06-19 07:46:21 +00003972 }
3973
3974 if (NewTy.isNull()) {
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003975 Diag(AttrLoc, diag::err_mode_wrong_type);
Alexey Bataev326057d2015-06-19 07:46:21 +00003976 return;
Chris Lattneracbc2d22008-06-27 22:18:37 +00003977 }
3978
3979 // Install the new type.
Enea Zaffanellaa86d88c2013-06-20 12:46:19 +00003980 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
3981 TD->setModedTypeSourceInfo(TD->getTypeSourceInfo(), NewTy);
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003982 else if (EnumDecl *ED = dyn_cast<EnumDecl>(D))
3983 ED->setIntegerType(NewTy);
Enea Zaffanellaa86d88c2013-06-20 12:46:19 +00003984 else
Aaron Ballman6c8848a2016-01-19 22:54:26 +00003985 cast<ValueDecl>(D)->setType(NewTy);
Enea Zaffanellaa86d88c2013-06-20 12:46:19 +00003986
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003987 D->addAttr(::new (Context)
3988 ModeAttr(AttrRange, Context, Name, SpellingListIndex));
Chris Lattneracbc2d22008-06-27 22:18:37 +00003989}
Chris Lattner9e2aafe2008-06-29 00:23:49 +00003990
Chandler Carruthedc2c642011-07-02 00:01:44 +00003991static void handleNoDebugAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Michael Han99315932013-01-24 16:46:58 +00003992 D->addAttr(::new (S.Context)
3993 NoDebugAttr(Attr.getRange(), S.Context,
3994 Attr.getAttributeSpellingListIndex()));
Anders Carlsson76187b42009-02-13 06:46:13 +00003995}
3996
Paul Robinson30e41fb2014-12-15 18:57:28 +00003997AlwaysInlineAttr *Sema::mergeAlwaysInlineAttr(Decl *D, SourceRange Range,
Paul Robinson080b1f32015-01-13 18:34:56 +00003998 IdentifierInfo *Ident,
Paul Robinson30e41fb2014-12-15 18:57:28 +00003999 unsigned AttrSpellingListIndex) {
4000 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
Paul Robinson080b1f32015-01-13 18:34:56 +00004001 Diag(Range.getBegin(), diag::warn_attribute_ignored) << Ident;
Paul Robinson30e41fb2014-12-15 18:57:28 +00004002 Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
4003 return nullptr;
4004 }
4005
4006 if (D->hasAttr<AlwaysInlineAttr>())
4007 return nullptr;
4008
4009 return ::new (Context) AlwaysInlineAttr(Range, Context,
4010 AttrSpellingListIndex);
4011}
4012
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00004013CommonAttr *Sema::mergeCommonAttr(Decl *D, SourceRange Range,
4014 IdentifierInfo *Ident,
4015 unsigned AttrSpellingListIndex) {
4016 if (checkAttrMutualExclusion<InternalLinkageAttr>(*this, D, Range, Ident))
4017 return nullptr;
4018
4019 return ::new (Context) CommonAttr(Range, Context, AttrSpellingListIndex);
4020}
4021
4022InternalLinkageAttr *
4023Sema::mergeInternalLinkageAttr(Decl *D, SourceRange Range,
4024 IdentifierInfo *Ident,
4025 unsigned AttrSpellingListIndex) {
4026 if (auto VD = dyn_cast<VarDecl>(D)) {
4027 // Attribute applies to Var but not any subclass of it (like ParmVar,
4028 // ImplicitParm or VarTemplateSpecialization).
4029 if (VD->getKind() != Decl::Var) {
4030 Diag(Range.getBegin(), diag::warn_attribute_wrong_decl_type)
4031 << Ident << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass
4032 : ExpectedVariableOrFunction);
4033 return nullptr;
4034 }
4035 // Attribute does not apply to non-static local variables.
4036 if (VD->hasLocalStorage()) {
4037 Diag(VD->getLocation(), diag::warn_internal_linkage_local_storage);
4038 return nullptr;
4039 }
4040 }
4041
4042 if (checkAttrMutualExclusion<CommonAttr>(*this, D, Range, Ident))
4043 return nullptr;
4044
4045 return ::new (Context)
4046 InternalLinkageAttr(Range, Context, AttrSpellingListIndex);
4047}
4048
Paul Robinson30e41fb2014-12-15 18:57:28 +00004049MinSizeAttr *Sema::mergeMinSizeAttr(Decl *D, SourceRange Range,
4050 unsigned AttrSpellingListIndex) {
4051 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
4052 Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'minsize'";
4053 Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
4054 return nullptr;
4055 }
4056
4057 if (D->hasAttr<MinSizeAttr>())
4058 return nullptr;
4059
4060 return ::new (Context) MinSizeAttr(Range, Context, AttrSpellingListIndex);
4061}
4062
4063OptimizeNoneAttr *Sema::mergeOptimizeNoneAttr(Decl *D, SourceRange Range,
4064 unsigned AttrSpellingListIndex) {
4065 if (AlwaysInlineAttr *Inline = D->getAttr<AlwaysInlineAttr>()) {
4066 Diag(Inline->getLocation(), diag::warn_attribute_ignored) << Inline;
4067 Diag(Range.getBegin(), diag::note_conflicting_attribute);
4068 D->dropAttr<AlwaysInlineAttr>();
4069 }
4070 if (MinSizeAttr *MinSize = D->getAttr<MinSizeAttr>()) {
4071 Diag(MinSize->getLocation(), diag::warn_attribute_ignored) << MinSize;
4072 Diag(Range.getBegin(), diag::note_conflicting_attribute);
4073 D->dropAttr<MinSizeAttr>();
4074 }
4075
4076 if (D->hasAttr<OptimizeNoneAttr>())
4077 return nullptr;
4078
4079 return ::new (Context) OptimizeNoneAttr(Range, Context,
4080 AttrSpellingListIndex);
4081}
4082
Paul Robinsonf0674352014-03-31 22:29:15 +00004083static void handleAlwaysInlineAttr(Sema &S, Decl *D,
4084 const AttributeList &Attr) {
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00004085 if (checkAttrMutualExclusion<NotTailCalledAttr>(S, D, Attr.getRange(),
Charles Davis0e379112016-08-08 21:19:08 +00004086 Attr.getName()))
Akira Hatanakac8667622015-11-06 23:56:15 +00004087 return;
4088
Paul Robinson080b1f32015-01-13 18:34:56 +00004089 if (AlwaysInlineAttr *Inline = S.mergeAlwaysInlineAttr(
4090 D, Attr.getRange(), Attr.getName(),
4091 Attr.getAttributeSpellingListIndex()))
4092 D->addAttr(Inline);
Paul Robinsonf0674352014-03-31 22:29:15 +00004093}
4094
Paul Robinson080b1f32015-01-13 18:34:56 +00004095static void handleMinSizeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4096 if (MinSizeAttr *MinSize = S.mergeMinSizeAttr(
4097 D, Attr.getRange(), Attr.getAttributeSpellingListIndex()))
4098 D->addAttr(MinSize);
Paul Robinsonaae2fba2014-12-10 23:34:36 +00004099}
4100
Paul Robinsonf0674352014-03-31 22:29:15 +00004101static void handleOptimizeNoneAttr(Sema &S, Decl *D,
4102 const AttributeList &Attr) {
Paul Robinson080b1f32015-01-13 18:34:56 +00004103 if (OptimizeNoneAttr *Optnone = S.mergeOptimizeNoneAttr(
4104 D, Attr.getRange(), Attr.getAttributeSpellingListIndex()))
4105 D->addAttr(Optnone);
Paul Robinsonf0674352014-03-31 22:29:15 +00004106}
4107
Justin Lebare71b2fa2016-09-30 23:57:34 +00004108static void handleConstantAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4109 if (checkAttrMutualExclusion<CUDASharedAttr>(S, D, Attr.getRange(),
4110 Attr.getName()))
4111 return;
4112 auto *VD = cast<VarDecl>(D);
4113 if (!VD->hasGlobalStorage()) {
4114 S.Diag(Attr.getLoc(), diag::err_cuda_nonglobal_constant);
4115 return;
4116 }
4117 D->addAttr(::new (S.Context) CUDAConstantAttr(
4118 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4119}
4120
Justin Lebar10411012016-09-30 23:57:30 +00004121static void handleSharedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4122 if (checkAttrMutualExclusion<CUDAConstantAttr>(S, D, Attr.getRange(),
4123 Attr.getName()))
4124 return;
4125 auto *VD = cast<VarDecl>(D);
Justin Lebar281ce2a2016-10-02 15:24:50 +00004126 // extern __shared__ is only allowed on arrays with no length (e.g.
4127 // "int x[]").
4128 if (VD->hasExternalStorage() && !isa<IncompleteArrayType>(VD->getType())) {
Justin Lebar10411012016-09-30 23:57:30 +00004129 S.Diag(Attr.getLoc(), diag::err_cuda_extern_shared) << VD;
4130 return;
4131 }
Justin Lebaraa370bd2016-10-13 18:45:13 +00004132 if (S.getLangOpts().CUDA && VD->hasLocalStorage() &&
4133 S.CUDADiagIfHostCode(Attr.getLoc(), diag::err_cuda_host_shared)
4134 << S.CurrentCUDATarget())
4135 return;
Justin Lebar10411012016-09-30 23:57:30 +00004136 D->addAttr(::new (S.Context) CUDASharedAttr(
4137 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4138}
4139
Chandler Carruthedc2c642011-07-02 00:01:44 +00004140static void handleGlobalAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Justin Lebar3eaaf862016-01-13 01:07:35 +00004141 if (checkAttrMutualExclusion<CUDADeviceAttr>(S, D, Attr.getRange(),
4142 Attr.getName()) ||
4143 checkAttrMutualExclusion<CUDAHostAttr>(S, D, Attr.getRange(),
4144 Attr.getName())) {
4145 return;
4146 }
Aaron Ballman3aff6332013-12-02 19:30:36 +00004147 FunctionDecl *FD = cast<FunctionDecl>(D);
Alp Toker314cc812014-01-25 16:55:45 +00004148 if (!FD->getReturnType()->isVoidType()) {
Alp Tokerf5b10792014-07-02 12:55:58 +00004149 SourceRange RTRange = FD->getReturnTypeSourceRange();
4150 S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return)
Aaron Ballman3aff6332013-12-02 19:30:36 +00004151 << FD->getType()
Alp Tokerf5b10792014-07-02 12:55:58 +00004152 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
4153 : FixItHint());
Aaron Ballman3aff6332013-12-02 19:30:36 +00004154 return;
Peter Collingbourne6ab610c2010-12-01 03:15:31 +00004155 }
Justin Lebarc66a1062016-01-20 00:26:57 +00004156 if (const auto *Method = dyn_cast<CXXMethodDecl>(FD)) {
4157 if (Method->isInstance()) {
4158 S.Diag(Method->getLocStart(), diag::err_kern_is_nonstatic_method)
4159 << Method;
4160 return;
4161 }
4162 S.Diag(Method->getLocStart(), diag::warn_kern_is_method) << Method;
4163 }
4164 // Only warn for "inline" when compiling for host, to cut down on noise.
4165 if (FD->isInlineSpecified() && !S.getLangOpts().CUDAIsDevice)
4166 S.Diag(FD->getLocStart(), diag::warn_kern_is_inline) << FD;
Peter Collingbourne6ab610c2010-12-01 03:15:31 +00004167
Aaron Ballman3aff6332013-12-02 19:30:36 +00004168 D->addAttr(::new (S.Context)
4169 CUDAGlobalAttr(Attr.getRange(), S.Context,
Eli Bendersky83860042014-09-02 22:00:06 +00004170 Attr.getAttributeSpellingListIndex()));
Peter Collingbourne6ab610c2010-12-01 03:15:31 +00004171}
4172
Chandler Carruthedc2c642011-07-02 00:01:44 +00004173static void handleGNUInlineAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballman74eeeae2013-11-27 13:27:02 +00004174 FunctionDecl *Fn = cast<FunctionDecl>(D);
Douglas Gregor35b57532009-10-27 21:01:01 +00004175 if (!Fn->isInlineSpecified()) {
Chris Lattnerddf6ca02009-04-20 19:12:28 +00004176 S.Diag(Attr.getLoc(), diag::warn_gnu_inline_attribute_requires_inline);
Chris Lattner4225e232009-04-14 17:02:11 +00004177 return;
4178 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00004179
Michael Han99315932013-01-24 16:46:58 +00004180 D->addAttr(::new (S.Context)
4181 GNUInlineAttr(Attr.getRange(), S.Context,
4182 Attr.getAttributeSpellingListIndex()));
Chris Lattnereaad6b72009-04-14 16:30:50 +00004183}
4184
Chandler Carruthedc2c642011-07-02 00:01:44 +00004185static void handleCallConvAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004186 if (hasDeclarator(D)) return;
Abramo Bagnara50099372010-04-30 13:10:51 +00004187
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004188 // Diagnostic is emitted elsewhere: here we store the (valid) Attr
John McCall3882ace2011-01-05 12:14:39 +00004189 // in the Decl node for syntactic reasoning, e.g., pretty-printing.
4190 CallingConv CC;
Richard Smitheec7cb12015-05-28 23:38:53 +00004191 if (S.CheckCallingConvAttr(Attr, CC, /*FD*/nullptr))
John McCall3882ace2011-01-05 12:14:39 +00004192 return;
4193
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004194 if (!isa<ObjCMethodDecl>(D)) {
4195 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
4196 << Attr.getName() << ExpectedFunctionOrMethod;
John McCall3882ace2011-01-05 12:14:39 +00004197 return;
4198 }
4199
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004200 switch (Attr.getKind()) {
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004201 case AttributeList::AT_FastCall:
Michael Han99315932013-01-24 16:46:58 +00004202 D->addAttr(::new (S.Context)
4203 FastCallAttr(Attr.getRange(), S.Context,
4204 Attr.getAttributeSpellingListIndex()));
Abramo Bagnara50099372010-04-30 13:10:51 +00004205 return;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004206 case AttributeList::AT_StdCall:
Michael Han99315932013-01-24 16:46:58 +00004207 D->addAttr(::new (S.Context)
4208 StdCallAttr(Attr.getRange(), S.Context,
4209 Attr.getAttributeSpellingListIndex()));
Abramo Bagnara50099372010-04-30 13:10:51 +00004210 return;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004211 case AttributeList::AT_ThisCall:
Michael Han99315932013-01-24 16:46:58 +00004212 D->addAttr(::new (S.Context)
4213 ThisCallAttr(Attr.getRange(), S.Context,
4214 Attr.getAttributeSpellingListIndex()));
Douglas Gregor4d13d102010-08-30 23:30:49 +00004215 return;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004216 case AttributeList::AT_CDecl:
Michael Han99315932013-01-24 16:46:58 +00004217 D->addAttr(::new (S.Context)
4218 CDeclAttr(Attr.getRange(), S.Context,
4219 Attr.getAttributeSpellingListIndex()));
Abramo Bagnara50099372010-04-30 13:10:51 +00004220 return;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004221 case AttributeList::AT_Pascal:
Michael Han99315932013-01-24 16:46:58 +00004222 D->addAttr(::new (S.Context)
4223 PascalAttr(Attr.getRange(), S.Context,
4224 Attr.getAttributeSpellingListIndex()));
Dawn Perchik335e16b2010-09-03 01:29:35 +00004225 return;
John McCall477f2bb2016-03-03 06:39:32 +00004226 case AttributeList::AT_SwiftCall:
4227 D->addAttr(::new (S.Context)
4228 SwiftCallAttr(Attr.getRange(), S.Context,
4229 Attr.getAttributeSpellingListIndex()));
4230 return;
Reid Klecknerd7857f02014-10-24 17:42:17 +00004231 case AttributeList::AT_VectorCall:
4232 D->addAttr(::new (S.Context)
4233 VectorCallAttr(Attr.getRange(), S.Context,
4234 Attr.getAttributeSpellingListIndex()));
4235 return;
Charles Davisb5a214e2013-08-30 04:39:01 +00004236 case AttributeList::AT_MSABI:
4237 D->addAttr(::new (S.Context)
4238 MSABIAttr(Attr.getRange(), S.Context,
4239 Attr.getAttributeSpellingListIndex()));
4240 return;
4241 case AttributeList::AT_SysVABI:
4242 D->addAttr(::new (S.Context)
4243 SysVABIAttr(Attr.getRange(), S.Context,
4244 Attr.getAttributeSpellingListIndex()));
4245 return;
Erich Keane757d3172016-11-02 18:29:35 +00004246 case AttributeList::AT_RegCall:
4247 D->addAttr(::new (S.Context) RegCallAttr(
4248 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4249 return;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004250 case AttributeList::AT_Pcs: {
Anton Korobeynikov231e8752011-04-14 20:06:49 +00004251 PcsAttr::PCSType PCS;
Benjamin Kramer25885f42012-08-14 13:24:39 +00004252 switch (CC) {
4253 case CC_AAPCS:
Anton Korobeynikov231e8752011-04-14 20:06:49 +00004254 PCS = PcsAttr::AAPCS;
Benjamin Kramer25885f42012-08-14 13:24:39 +00004255 break;
4256 case CC_AAPCS_VFP:
Anton Korobeynikov231e8752011-04-14 20:06:49 +00004257 PCS = PcsAttr::AAPCS_VFP;
Benjamin Kramer25885f42012-08-14 13:24:39 +00004258 break;
4259 default:
4260 llvm_unreachable("unexpected calling convention in pcs attribute");
Anton Korobeynikov231e8752011-04-14 20:06:49 +00004261 }
4262
Michael Han99315932013-01-24 16:46:58 +00004263 D->addAttr(::new (S.Context)
4264 PcsAttr(Attr.getRange(), S.Context, PCS,
4265 Attr.getAttributeSpellingListIndex()));
Derek Schuffa2020962012-10-16 22:30:41 +00004266 return;
Anton Korobeynikov231e8752011-04-14 20:06:49 +00004267 }
Guy Benyeif0a014b2012-12-25 08:53:55 +00004268 case AttributeList::AT_IntelOclBicc:
Michael Han99315932013-01-24 16:46:58 +00004269 D->addAttr(::new (S.Context)
4270 IntelOclBiccAttr(Attr.getRange(), S.Context,
4271 Attr.getAttributeSpellingListIndex()));
Guy Benyeif0a014b2012-12-25 08:53:55 +00004272 return;
Roman Levenstein35aa5ce2016-03-16 18:00:46 +00004273 case AttributeList::AT_PreserveMost:
4274 D->addAttr(::new (S.Context) PreserveMostAttr(
4275 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4276 return;
4277 case AttributeList::AT_PreserveAll:
4278 D->addAttr(::new (S.Context) PreserveAllAttr(
4279 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4280 return;
Abramo Bagnara50099372010-04-30 13:10:51 +00004281 default:
4282 llvm_unreachable("unexpected attribute kind");
Abramo Bagnara50099372010-04-30 13:10:51 +00004283 }
4284}
4285
Matthias Gehre01a63382017-03-27 19:45:24 +00004286static void handleSuppressAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4287 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
4288 return;
4289
4290 std::vector<StringRef> DiagnosticIdentifiers;
4291 for (unsigned I = 0, E = Attr.getNumArgs(); I != E; ++I) {
4292 StringRef RuleName;
4293
4294 if (!S.checkStringLiteralArgumentAttr(Attr, I, RuleName, nullptr))
4295 return;
4296
4297 // FIXME: Warn if the rule name is unknown. This is tricky because only
4298 // clang-tidy knows about available rules.
4299 DiagnosticIdentifiers.push_back(RuleName);
4300 }
4301 D->addAttr(::new (S.Context) SuppressAttr(
4302 Attr.getRange(), S.Context, DiagnosticIdentifiers.data(),
4303 DiagnosticIdentifiers.size(), Attr.getAttributeSpellingListIndex()));
4304}
4305
Erich Keaneb11ebc52017-09-27 03:20:13 +00004306bool Sema::CheckCallingConvAttr(const AttributeList &Attrs, CallingConv &CC,
Aaron Ballman02df2e02012-12-09 17:45:41 +00004307 const FunctionDecl *FD) {
Erich Keaneb11ebc52017-09-27 03:20:13 +00004308 if (Attrs.isInvalid())
John McCall3882ace2011-01-05 12:14:39 +00004309 return true;
4310
Erich Keaneb11ebc52017-09-27 03:20:13 +00004311 if (Attrs.hasProcessingCache()) {
4312 CC = (CallingConv) Attrs.getProcessingCache();
John McCall3b5a8f52016-03-03 00:10:03 +00004313 return false;
4314 }
4315
Erich Keaneb11ebc52017-09-27 03:20:13 +00004316 unsigned ReqArgs = Attrs.getKind() == AttributeList::AT_Pcs ? 1 : 0;
4317 if (!checkAttributeNumArgs(*this, Attrs, ReqArgs)) {
4318 Attrs.setInvalid();
John McCall3882ace2011-01-05 12:14:39 +00004319 return true;
4320 }
4321
Aaron Ballmanab7691c2014-01-09 22:48:32 +00004322 // TODO: diagnose uses of these conventions on the wrong target.
Erich Keaneb11ebc52017-09-27 03:20:13 +00004323 switch (Attrs.getKind()) {
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004324 case AttributeList::AT_CDecl: CC = CC_C; break;
4325 case AttributeList::AT_FastCall: CC = CC_X86FastCall; break;
4326 case AttributeList::AT_StdCall: CC = CC_X86StdCall; break;
4327 case AttributeList::AT_ThisCall: CC = CC_X86ThisCall; break;
4328 case AttributeList::AT_Pascal: CC = CC_X86Pascal; break;
John McCall477f2bb2016-03-03 06:39:32 +00004329 case AttributeList::AT_SwiftCall: CC = CC_Swift; break;
Reid Klecknerd7857f02014-10-24 17:42:17 +00004330 case AttributeList::AT_VectorCall: CC = CC_X86VectorCall; break;
Erich Keane757d3172016-11-02 18:29:35 +00004331 case AttributeList::AT_RegCall: CC = CC_X86RegCall; break;
Charles Davisb5a214e2013-08-30 04:39:01 +00004332 case AttributeList::AT_MSABI:
4333 CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_C :
Martin Storsjo022e7822017-07-17 20:49:45 +00004334 CC_Win64;
Charles Davisb5a214e2013-08-30 04:39:01 +00004335 break;
4336 case AttributeList::AT_SysVABI:
4337 CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_X86_64SysV :
4338 CC_C;
4339 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004340 case AttributeList::AT_Pcs: {
Aaron Ballmand6600a52013-09-13 17:48:25 +00004341 StringRef StrRef;
Erich Keaneb11ebc52017-09-27 03:20:13 +00004342 if (!checkStringLiteralArgumentAttr(Attrs, 0, StrRef)) {
4343 Attrs.setInvalid();
Anton Korobeynikov231e8752011-04-14 20:06:49 +00004344 return true;
4345 }
Anton Korobeynikov231e8752011-04-14 20:06:49 +00004346 if (StrRef == "aapcs") {
4347 CC = CC_AAPCS;
4348 break;
4349 } else if (StrRef == "aapcs-vfp") {
4350 CC = CC_AAPCS_VFP;
4351 break;
4352 }
Benjamin Kramer833fb9f2012-08-14 13:13:47 +00004353
Erich Keaneb11ebc52017-09-27 03:20:13 +00004354 Attrs.setInvalid();
4355 Diag(Attrs.getLoc(), diag::err_invalid_pcs);
Benjamin Kramer833fb9f2012-08-14 13:13:47 +00004356 return true;
Anton Korobeynikov231e8752011-04-14 20:06:49 +00004357 }
Guy Benyeif0a014b2012-12-25 08:53:55 +00004358 case AttributeList::AT_IntelOclBicc: CC = CC_IntelOclBicc; break;
Roman Levenstein35aa5ce2016-03-16 18:00:46 +00004359 case AttributeList::AT_PreserveMost: CC = CC_PreserveMost; break;
4360 case AttributeList::AT_PreserveAll: CC = CC_PreserveAll; break;
David Blaikie8a40f702012-01-17 06:56:22 +00004361 default: llvm_unreachable("unexpected attribute kind");
John McCall3882ace2011-01-05 12:14:39 +00004362 }
4363
Aaron Ballmane91c6be2012-10-02 14:26:08 +00004364 const TargetInfo &TI = Context.getTargetInfo();
4365 TargetInfo::CallingConvCheckResult A = TI.checkCallingConvention(CC);
Reid Kleckner9fde2e02015-02-26 19:43:46 +00004366 if (A != TargetInfo::CCCR_OK) {
4367 if (A == TargetInfo::CCCR_Warning)
Erich Keaneb11ebc52017-09-27 03:20:13 +00004368 Diag(Attrs.getLoc(), diag::warn_cconv_ignored) << Attrs.getName();
Aaron Ballman02df2e02012-12-09 17:45:41 +00004369
Reid Kleckner9fde2e02015-02-26 19:43:46 +00004370 // This convention is not valid for the target. Use the default function or
4371 // method calling convention.
Alexey Bataeva7547182016-05-18 09:06:38 +00004372 bool IsCXXMethod = false, IsVariadic = false;
4373 if (FD) {
4374 IsCXXMethod = FD->isCXXInstanceMember();
4375 IsVariadic = FD->isVariadic();
4376 }
4377 CC = Context.getDefaultCallingConvention(IsVariadic, IsCXXMethod);
Aaron Ballmane91c6be2012-10-02 14:26:08 +00004378 }
4379
Erich Keaneb11ebc52017-09-27 03:20:13 +00004380 Attrs.setProcessingCache((unsigned) CC);
John McCall3882ace2011-01-05 12:14:39 +00004381 return false;
4382}
4383
John McCall477f2bb2016-03-03 06:39:32 +00004384/// Pointer-like types in the default address space.
4385static bool isValidSwiftContextType(QualType type) {
4386 if (!type->hasPointerRepresentation())
4387 return type->isDependentType();
4388 return type->getPointeeType().getAddressSpace() == 0;
4389}
4390
4391/// Pointers and references in the default address space.
4392static bool isValidSwiftIndirectResultType(QualType type) {
4393 if (auto ptrType = type->getAs<PointerType>()) {
4394 type = ptrType->getPointeeType();
4395 } else if (auto refType = type->getAs<ReferenceType>()) {
4396 type = refType->getPointeeType();
4397 } else {
4398 return type->isDependentType();
4399 }
4400 return type.getAddressSpace() == 0;
4401}
4402
4403/// Pointers and references to pointers in the default address space.
4404static bool isValidSwiftErrorResultType(QualType type) {
4405 if (auto ptrType = type->getAs<PointerType>()) {
4406 type = ptrType->getPointeeType();
4407 } else if (auto refType = type->getAs<ReferenceType>()) {
4408 type = refType->getPointeeType();
4409 } else {
4410 return type->isDependentType();
4411 }
4412 if (!type.getQualifiers().empty())
4413 return false;
4414 return isValidSwiftContextType(type);
4415}
4416
Erich Keaneb11ebc52017-09-27 03:20:13 +00004417static void handleParameterABIAttr(Sema &S, Decl *D, const AttributeList &Attrs,
4418 ParameterABI Abi) {
4419 S.AddParameterABIAttr(Attrs.getRange(), D, Abi,
4420 Attrs.getAttributeSpellingListIndex());
John McCall477f2bb2016-03-03 06:39:32 +00004421}
4422
4423void Sema::AddParameterABIAttr(SourceRange range, Decl *D, ParameterABI abi,
4424 unsigned spellingIndex) {
4425
4426 QualType type = cast<ParmVarDecl>(D)->getType();
4427
4428 if (auto existingAttr = D->getAttr<ParameterABIAttr>()) {
4429 if (existingAttr->getABI() != abi) {
4430 Diag(range.getBegin(), diag::err_attributes_are_not_compatible)
4431 << getParameterABISpelling(abi) << existingAttr;
4432 Diag(existingAttr->getLocation(), diag::note_conflicting_attribute);
4433 return;
4434 }
4435 }
4436
4437 switch (abi) {
4438 case ParameterABI::Ordinary:
4439 llvm_unreachable("explicit attribute for ordinary parameter ABI?");
4440
4441 case ParameterABI::SwiftContext:
4442 if (!isValidSwiftContextType(type)) {
4443 Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type)
4444 << getParameterABISpelling(abi)
4445 << /*pointer to pointer */ 0 << type;
4446 }
4447 D->addAttr(::new (Context)
4448 SwiftContextAttr(range, Context, spellingIndex));
4449 return;
4450
4451 case ParameterABI::SwiftErrorResult:
4452 if (!isValidSwiftErrorResultType(type)) {
4453 Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type)
4454 << getParameterABISpelling(abi)
4455 << /*pointer to pointer */ 1 << type;
4456 }
4457 D->addAttr(::new (Context)
4458 SwiftErrorResultAttr(range, Context, spellingIndex));
4459 return;
4460
4461 case ParameterABI::SwiftIndirectResult:
4462 if (!isValidSwiftIndirectResultType(type)) {
4463 Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type)
4464 << getParameterABISpelling(abi)
4465 << /*pointer*/ 0 << type;
4466 }
4467 D->addAttr(::new (Context)
4468 SwiftIndirectResultAttr(range, Context, spellingIndex));
4469 return;
4470 }
4471 llvm_unreachable("bad parameter ABI attribute");
4472}
4473
John McCall3882ace2011-01-05 12:14:39 +00004474/// Checks a regparm attribute, returning true if it is ill-formed and
4475/// otherwise setting numParams to the appropriate value.
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004476bool Sema::CheckRegparmAttr(const AttributeList &Attr, unsigned &numParams) {
4477 if (Attr.isInvalid())
John McCall3882ace2011-01-05 12:14:39 +00004478 return true;
4479
Aaron Ballmanc2cbc662013-07-18 18:01:48 +00004480 if (!checkAttributeNumArgs(*this, Attr, 1)) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004481 Attr.setInvalid();
John McCall3882ace2011-01-05 12:14:39 +00004482 return true;
Fariborz Jahaniana2d609e2009-03-27 18:38:55 +00004483 }
Eli Friedman7044b762009-03-27 21:06:47 +00004484
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00004485 uint32_t NP;
Aaron Ballman00e99962013-08-31 01:11:41 +00004486 Expr *NumParamsExpr = Attr.getArgAsExpr(0);
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00004487 if (!checkUInt32Argument(*this, Attr, NumParamsExpr, NP)) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004488 Attr.setInvalid();
John McCall3882ace2011-01-05 12:14:39 +00004489 return true;
Eli Friedman7044b762009-03-27 21:06:47 +00004490 }
4491
Douglas Gregore8bbc122011-09-02 00:18:52 +00004492 if (Context.getTargetInfo().getRegParmMax() == 0) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004493 Diag(Attr.getLoc(), diag::err_attribute_regparm_wrong_platform)
Eli Friedman7044b762009-03-27 21:06:47 +00004494 << NumParamsExpr->getSourceRange();
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004495 Attr.setInvalid();
John McCall3882ace2011-01-05 12:14:39 +00004496 return true;
Eli Friedman7044b762009-03-27 21:06:47 +00004497 }
4498
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00004499 numParams = NP;
Douglas Gregore8bbc122011-09-02 00:18:52 +00004500 if (numParams > Context.getTargetInfo().getRegParmMax()) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004501 Diag(Attr.getLoc(), diag::err_attribute_regparm_invalid_number)
Douglas Gregore8bbc122011-09-02 00:18:52 +00004502 << Context.getTargetInfo().getRegParmMax() << NumParamsExpr->getSourceRange();
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004503 Attr.setInvalid();
John McCall3882ace2011-01-05 12:14:39 +00004504 return true;
Eli Friedman7044b762009-03-27 21:06:47 +00004505 }
4506
John McCall3882ace2011-01-05 12:14:39 +00004507 return false;
Fariborz Jahaniana2d609e2009-03-27 18:38:55 +00004508}
4509
Artem Belevichbcec9da2016-06-06 22:54:57 +00004510// Checks whether an argument of launch_bounds attribute is
4511// acceptable, performs implicit conversion to Rvalue, and returns
4512// non-nullptr Expr result on success. Otherwise, it returns nullptr
4513// and may output an error.
4514static Expr *makeLaunchBoundsArgExpr(Sema &S, Expr *E,
4515 const CUDALaunchBoundsAttr &Attr,
4516 const unsigned Idx) {
Artem Belevich7093e402015-04-21 22:55:54 +00004517 if (S.DiagnoseUnexpandedParameterPack(E))
Artem Belevichbcec9da2016-06-06 22:54:57 +00004518 return nullptr;
Artem Belevich7093e402015-04-21 22:55:54 +00004519
4520 // Accept template arguments for now as they depend on something else.
4521 // We'll get to check them when they eventually get instantiated.
4522 if (E->isValueDependent())
Artem Belevichbcec9da2016-06-06 22:54:57 +00004523 return E;
Artem Belevich7093e402015-04-21 22:55:54 +00004524
4525 llvm::APSInt I(64);
4526 if (!E->isIntegerConstantExpr(I, S.Context)) {
4527 S.Diag(E->getExprLoc(), diag::err_attribute_argument_n_type)
4528 << &Attr << Idx << AANT_ArgumentIntegerConstant << E->getSourceRange();
Artem Belevichbcec9da2016-06-06 22:54:57 +00004529 return nullptr;
Artem Belevich7093e402015-04-21 22:55:54 +00004530 }
4531 // Make sure we can fit it in 32 bits.
4532 if (!I.isIntN(32)) {
4533 S.Diag(E->getExprLoc(), diag::err_ice_too_large) << I.toString(10, false)
4534 << 32 << /* Unsigned */ 1;
Artem Belevichbcec9da2016-06-06 22:54:57 +00004535 return nullptr;
Artem Belevich7093e402015-04-21 22:55:54 +00004536 }
4537 if (I < 0)
4538 S.Diag(E->getExprLoc(), diag::warn_attribute_argument_n_negative)
4539 << &Attr << Idx << E->getSourceRange();
4540
Artem Belevichbcec9da2016-06-06 22:54:57 +00004541 // We may need to perform implicit conversion of the argument.
4542 InitializedEntity Entity = InitializedEntity::InitializeParameter(
4543 S.Context, S.Context.getConstType(S.Context.IntTy), /*consume*/ false);
4544 ExprResult ValArg = S.PerformCopyInitialization(Entity, SourceLocation(), E);
4545 assert(!ValArg.isInvalid() &&
4546 "Unexpected PerformCopyInitialization() failure.");
4547
4548 return ValArg.getAs<Expr>();
Artem Belevich7093e402015-04-21 22:55:54 +00004549}
4550
4551void Sema::AddLaunchBoundsAttr(SourceRange AttrRange, Decl *D, Expr *MaxThreads,
4552 Expr *MinBlocks, unsigned SpellingListIndex) {
4553 CUDALaunchBoundsAttr TmpAttr(AttrRange, Context, MaxThreads, MinBlocks,
4554 SpellingListIndex);
Artem Belevichbcec9da2016-06-06 22:54:57 +00004555 MaxThreads = makeLaunchBoundsArgExpr(*this, MaxThreads, TmpAttr, 0);
4556 if (MaxThreads == nullptr)
Aaron Ballman3aff6332013-12-02 19:30:36 +00004557 return;
4558
Artem Belevichbcec9da2016-06-06 22:54:57 +00004559 if (MinBlocks) {
4560 MinBlocks = makeLaunchBoundsArgExpr(*this, MinBlocks, TmpAttr, 1);
4561 if (MinBlocks == nullptr)
4562 return;
4563 }
Artem Belevich7093e402015-04-21 22:55:54 +00004564
4565 D->addAttr(::new (Context) CUDALaunchBoundsAttr(
4566 AttrRange, Context, MaxThreads, MinBlocks, SpellingListIndex));
4567}
4568
4569static void handleLaunchBoundsAttr(Sema &S, Decl *D,
4570 const AttributeList &Attr) {
4571 if (!checkAttributeAtLeastNumArgs(S, Attr, 1) ||
4572 !checkAttributeAtMostNumArgs(S, Attr, 2))
4573 return;
4574
4575 S.AddLaunchBoundsAttr(Attr.getRange(), D, Attr.getArgAsExpr(0),
4576 Attr.getNumArgs() > 1 ? Attr.getArgAsExpr(1) : nullptr,
4577 Attr.getAttributeSpellingListIndex());
Peter Collingbourne827301e2010-12-12 23:03:07 +00004578}
4579
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004580static void handleArgumentWithTypeTagAttr(Sema &S, Decl *D,
4581 const AttributeList &Attr) {
Aaron Ballman00e99962013-08-31 01:11:41 +00004582 if (!Attr.isArgIdent(0)) {
Aaron Ballman29982272013-07-23 14:03:57 +00004583 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
Aaron Ballman3bf758c2013-07-30 01:31:03 +00004584 << Attr.getName() << /* arg num = */ 1 << AANT_ArgumentIdentifier;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004585 return;
4586 }
Aaron Ballman00e99962013-08-31 01:11:41 +00004587
4588 if (!checkAttributeNumArgs(S, Attr, 3))
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004589 return;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004590
Aaron Ballman00e99962013-08-31 01:11:41 +00004591 IdentifierInfo *ArgumentKind = Attr.getArgAsIdent(0)->Ident;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004592
4593 if (!isFunctionOrMethod(D) || !hasFunctionProto(D)) {
4594 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
4595 << Attr.getName() << ExpectedFunctionOrMethod;
4596 return;
4597 }
4598
4599 uint64_t ArgumentIdx;
Alp Toker601b22c2014-01-21 23:35:24 +00004600 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 2, Attr.getArgAsExpr(1),
4601 ArgumentIdx))
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004602 return;
4603
4604 uint64_t TypeTagIdx;
Alp Toker601b22c2014-01-21 23:35:24 +00004605 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 3, Attr.getArgAsExpr(2),
4606 TypeTagIdx))
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004607 return;
4608
Aaron Ballmanfaed0fa2013-12-26 16:30:30 +00004609 bool IsPointer = (Attr.getName()->getName() == "pointer_with_type_tag");
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004610 if (IsPointer) {
4611 // Ensure that buffer has a pointer type.
Alp Toker601b22c2014-01-21 23:35:24 +00004612 QualType BufferTy = getFunctionOrMethodParamType(D, ArgumentIdx);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004613 if (!BufferTy->isPointerType()) {
4614 S.Diag(Attr.getLoc(), diag::err_attribute_pointers_only)
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00004615 << Attr.getName() << 0;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004616 }
4617 }
4618
Michael Han99315932013-01-24 16:46:58 +00004619 D->addAttr(::new (S.Context)
4620 ArgumentWithTypeTagAttr(Attr.getRange(), S.Context, ArgumentKind,
4621 ArgumentIdx, TypeTagIdx, IsPointer,
4622 Attr.getAttributeSpellingListIndex()));
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004623}
4624
4625static void handleTypeTagForDatatypeAttr(Sema &S, Decl *D,
4626 const AttributeList &Attr) {
Aaron Ballman00e99962013-08-31 01:11:41 +00004627 if (!Attr.isArgIdent(0)) {
Aaron Ballman29982272013-07-23 14:03:57 +00004628 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
Aaron Ballman3bf758c2013-07-30 01:31:03 +00004629 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004630 return;
4631 }
Aaron Ballman00e99962013-08-31 01:11:41 +00004632
4633 if (!checkAttributeNumArgs(S, Attr, 1))
4634 return;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004635
Aaron Ballman90f8c6f2013-11-25 18:50:49 +00004636 if (!isa<VarDecl>(D)) {
4637 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
4638 << Attr.getName() << ExpectedVariable;
4639 return;
4640 }
4641
Aaron Ballman00e99962013-08-31 01:11:41 +00004642 IdentifierInfo *PointerKind = Attr.getArgAsIdent(0)->Ident;
Craig Topperc3ec1492014-05-26 06:22:03 +00004643 TypeSourceInfo *MatchingCTypeLoc = nullptr;
Richard Smithb87c4652013-10-31 21:23:20 +00004644 S.GetTypeFromParser(Attr.getMatchingCType(), &MatchingCTypeLoc);
4645 assert(MatchingCTypeLoc && "no type source info for attribute argument");
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004646
Michael Han99315932013-01-24 16:46:58 +00004647 D->addAttr(::new (S.Context)
4648 TypeTagForDatatypeAttr(Attr.getRange(), S.Context, PointerKind,
Richard Smithb87c4652013-10-31 21:23:20 +00004649 MatchingCTypeLoc,
Michael Han99315932013-01-24 16:46:58 +00004650 Attr.getLayoutCompatible(),
4651 Attr.getMustBeNull(),
4652 Attr.getAttributeSpellingListIndex()));
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004653}
4654
Dean Michael Berris418da3f2017-03-06 07:08:21 +00004655static void handleXRayLogArgsAttr(Sema &S, Decl *D,
4656 const AttributeList &Attr) {
4657 uint64_t ArgCount;
Dean Michael Berris7456a282017-06-16 03:22:09 +00004658
Dean Michael Berris418da3f2017-03-06 07:08:21 +00004659 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 1, Attr.getArgAsExpr(0),
Dean Michael Berris7456a282017-06-16 03:22:09 +00004660 ArgCount,
4661 true /* AllowImplicitThis*/))
Dean Michael Berris418da3f2017-03-06 07:08:21 +00004662 return;
4663
4664 // ArgCount isn't a parameter index [0;n), it's a count [1;n] - hence + 1.
4665 D->addAttr(::new (S.Context)
Dean Michael Berris7456a282017-06-16 03:22:09 +00004666 XRayLogArgsAttr(Attr.getRange(), S.Context, ++ArgCount,
4667 Attr.getAttributeSpellingListIndex()));
Dean Michael Berris418da3f2017-03-06 07:08:21 +00004668}
4669
Chris Lattner9e2aafe2008-06-29 00:23:49 +00004670//===----------------------------------------------------------------------===//
Ted Kremenek9ecdfaf2009-05-09 02:44:38 +00004671// Checker-specific attribute handlers.
4672//===----------------------------------------------------------------------===//
4673
Fariborz Jahanian4eba3dc2014-06-12 16:12:30 +00004674static bool isValidSubjectOfNSReturnsRetainedAttribute(QualType type) {
Fariborz Jahanian9c100322014-06-11 21:22:53 +00004675 return type->isDependentType() ||
Fariborz Jahanian4eba3dc2014-06-12 16:12:30 +00004676 type->isObjCRetainableType();
Fariborz Jahanian9c100322014-06-11 21:22:53 +00004677}
4678
John McCalled433932011-01-25 03:31:58 +00004679static bool isValidSubjectOfNSAttribute(Sema &S, QualType type) {
Douglas Gregorf892c7f2011-10-09 22:26:49 +00004680 return type->isDependentType() ||
4681 type->isObjCObjectPointerType() ||
4682 S.Context.isObjCNSObjectType(type);
John McCalled433932011-01-25 03:31:58 +00004683}
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004684
John McCalled433932011-01-25 03:31:58 +00004685static bool isValidSubjectOfCFAttribute(Sema &S, QualType type) {
Douglas Gregorf892c7f2011-10-09 22:26:49 +00004686 return type->isDependentType() ||
4687 type->isPointerType() ||
4688 isValidSubjectOfNSAttribute(S, type);
John McCalled433932011-01-25 03:31:58 +00004689}
4690
Chandler Carruthedc2c642011-07-02 00:01:44 +00004691static void handleNSConsumedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
John McCall3b5a8f52016-03-03 00:10:03 +00004692 S.AddNSConsumedAttr(Attr.getRange(), D, Attr.getAttributeSpellingListIndex(),
4693 Attr.getKind() == AttributeList::AT_NSConsumed,
4694 /*template instantiation*/ false);
4695}
Aaron Ballman74eeeae2013-11-27 13:27:02 +00004696
John McCall3b5a8f52016-03-03 00:10:03 +00004697void Sema::AddNSConsumedAttr(SourceRange attrRange, Decl *D,
4698 unsigned spellingIndex, bool isNSConsumed,
4699 bool isTemplateInstantiation) {
4700 ParmVarDecl *param = cast<ParmVarDecl>(D);
4701 bool typeOK;
4702
4703 if (isNSConsumed) {
4704 typeOK = isValidSubjectOfNSAttribute(*this, param->getType());
John McCalled433932011-01-25 03:31:58 +00004705 } else {
John McCall3b5a8f52016-03-03 00:10:03 +00004706 typeOK = isValidSubjectOfCFAttribute(*this, param->getType());
John McCalled433932011-01-25 03:31:58 +00004707 }
4708
4709 if (!typeOK) {
John McCall3b5a8f52016-03-03 00:10:03 +00004710 // These attributes are normally just advisory, but in ARC, ns_consumed
4711 // is significant. Allow non-dependent code to contain inappropriate
4712 // attributes even in ARC, but require template instantiations to be
4713 // set up correctly.
4714 Diag(D->getLocStart(),
4715 (isTemplateInstantiation && isNSConsumed &&
4716 getLangOpts().ObjCAutoRefCount
4717 ? diag::err_ns_attribute_wrong_parameter_type
4718 : diag::warn_ns_attribute_wrong_parameter_type))
4719 << attrRange
4720 << (isNSConsumed ? "ns_consumed" : "cf_consumed")
4721 << (isNSConsumed ? /*objc pointers*/ 0 : /*cf pointers*/ 1);
John McCalled433932011-01-25 03:31:58 +00004722 return;
4723 }
4724
John McCall3b5a8f52016-03-03 00:10:03 +00004725 if (isNSConsumed)
4726 param->addAttr(::new (Context)
4727 NSConsumedAttr(attrRange, Context, spellingIndex));
John McCalled433932011-01-25 03:31:58 +00004728 else
John McCall3b5a8f52016-03-03 00:10:03 +00004729 param->addAttr(::new (Context)
4730 CFConsumedAttr(attrRange, Context, spellingIndex));
John McCalled433932011-01-25 03:31:58 +00004731}
4732
John McCall12251882017-07-15 11:06:46 +00004733bool Sema::checkNSReturnsRetainedReturnType(SourceLocation loc,
4734 QualType type) {
4735 if (isValidSubjectOfNSReturnsRetainedAttribute(type))
4736 return false;
4737
4738 Diag(loc, diag::warn_ns_attribute_wrong_return_type)
4739 << "'ns_returns_retained'" << 0 << 0;
4740 return true;
4741}
4742
Chandler Carruthedc2c642011-07-02 00:01:44 +00004743static void handleNSReturnsRetainedAttr(Sema &S, Decl *D,
4744 const AttributeList &Attr) {
John McCalled433932011-01-25 03:31:58 +00004745 QualType returnType;
Mike Stumpd3bb5572009-07-24 19:02:52 +00004746
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004747 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
Alp Toker314cc812014-01-25 16:55:45 +00004748 returnType = MD->getReturnType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00004749 else if (S.getLangOpts().ObjCAutoRefCount && hasDeclarator(D) &&
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004750 (Attr.getKind() == AttributeList::AT_NSReturnsRetained))
John McCall31168b02011-06-15 23:02:42 +00004751 return; // ignore: was handled as a type attribute
Fariborz Jahanian272b7dc2012-08-28 22:26:21 +00004752 else if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
4753 returnType = PD->getType();
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004754 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
Alp Toker314cc812014-01-25 16:55:45 +00004755 returnType = FD->getReturnType();
Douglas Gregoreb6e64c2015-06-19 23:17:46 +00004756 else if (auto *Param = dyn_cast<ParmVarDecl>(D)) {
4757 returnType = Param->getType()->getPointeeType();
4758 if (returnType.isNull()) {
4759 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_parameter_type)
4760 << Attr.getName() << /*pointer-to-CF*/2
4761 << Attr.getRange();
4762 return;
4763 }
John McCall12251882017-07-15 11:06:46 +00004764 } else if (Attr.isUsedAsTypeAttr()) {
4765 return;
Douglas Gregoreb6e64c2015-06-19 23:17:46 +00004766 } else {
4767 AttributeDeclKind ExpectedDeclKind;
4768 switch (Attr.getKind()) {
4769 default: llvm_unreachable("invalid ownership attribute");
4770 case AttributeList::AT_NSReturnsRetained:
4771 case AttributeList::AT_NSReturnsAutoreleased:
4772 case AttributeList::AT_NSReturnsNotRetained:
4773 ExpectedDeclKind = ExpectedFunctionOrMethod;
4774 break;
4775
4776 case AttributeList::AT_CFReturnsRetained:
4777 case AttributeList::AT_CFReturnsNotRetained:
4778 ExpectedDeclKind = ExpectedFunctionMethodOrParameter;
4779 break;
4780 }
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004781 S.Diag(D->getLocStart(), diag::warn_attribute_wrong_decl_type)
Douglas Gregoreb6e64c2015-06-19 23:17:46 +00004782 << Attr.getRange() << Attr.getName() << ExpectedDeclKind;
Ted Kremenek9ecdfaf2009-05-09 02:44:38 +00004783 return;
4784 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00004785
John McCalled433932011-01-25 03:31:58 +00004786 bool typeOK;
4787 bool cf;
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004788 switch (Attr.getKind()) {
David Blaikie8a40f702012-01-17 06:56:22 +00004789 default: llvm_unreachable("invalid ownership attribute");
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004790 case AttributeList::AT_NSReturnsRetained:
Fariborz Jahanian4eba3dc2014-06-12 16:12:30 +00004791 typeOK = isValidSubjectOfNSReturnsRetainedAttribute(returnType);
Fariborz Jahanian9c100322014-06-11 21:22:53 +00004792 cf = false;
4793 break;
4794
4795 case AttributeList::AT_NSReturnsAutoreleased:
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004796 case AttributeList::AT_NSReturnsNotRetained:
John McCalled433932011-01-25 03:31:58 +00004797 typeOK = isValidSubjectOfNSAttribute(S, returnType);
4798 cf = false;
4799 break;
4800
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004801 case AttributeList::AT_CFReturnsRetained:
4802 case AttributeList::AT_CFReturnsNotRetained:
John McCalled433932011-01-25 03:31:58 +00004803 typeOK = isValidSubjectOfCFAttribute(S, returnType);
4804 cf = true;
4805 break;
4806 }
4807
4808 if (!typeOK) {
John McCall12251882017-07-15 11:06:46 +00004809 if (Attr.isUsedAsTypeAttr())
4810 return;
4811
Douglas Gregoreb6e64c2015-06-19 23:17:46 +00004812 if (isa<ParmVarDecl>(D)) {
4813 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_parameter_type)
4814 << Attr.getName() << /*pointer-to-CF*/2
4815 << Attr.getRange();
4816 } else {
4817 // Needs to be kept in sync with warn_ns_attribute_wrong_return_type.
4818 enum : unsigned {
4819 Function,
4820 Method,
4821 Property
4822 } SubjectKind = Function;
4823 if (isa<ObjCMethodDecl>(D))
4824 SubjectKind = Method;
4825 else if (isa<ObjCPropertyDecl>(D))
4826 SubjectKind = Property;
4827 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_return_type)
4828 << Attr.getName() << SubjectKind << cf
4829 << Attr.getRange();
4830 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00004831 return;
Ted Kremenek3b204e42009-05-13 21:07:32 +00004832 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00004833
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004834 switch (Attr.getKind()) {
Ted Kremenek9ecdfaf2009-05-09 02:44:38 +00004835 default:
David Blaikie83d382b2011-09-23 05:06:16 +00004836 llvm_unreachable("invalid ownership attribute");
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004837 case AttributeList::AT_NSReturnsAutoreleased:
Nico Weber462fd1e2015-01-07 23:50:05 +00004838 D->addAttr(::new (S.Context) NSReturnsAutoreleasedAttr(
4839 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
John McCalled433932011-01-25 03:31:58 +00004840 return;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004841 case AttributeList::AT_CFReturnsNotRetained:
Nico Weber462fd1e2015-01-07 23:50:05 +00004842 D->addAttr(::new (S.Context) CFReturnsNotRetainedAttr(
4843 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
Ted Kremenekd9c66632010-02-18 00:05:45 +00004844 return;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004845 case AttributeList::AT_NSReturnsNotRetained:
Nico Weber462fd1e2015-01-07 23:50:05 +00004846 D->addAttr(::new (S.Context) NSReturnsNotRetainedAttr(
4847 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
Ted Kremenekd9c66632010-02-18 00:05:45 +00004848 return;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004849 case AttributeList::AT_CFReturnsRetained:
Nico Weber462fd1e2015-01-07 23:50:05 +00004850 D->addAttr(::new (S.Context) CFReturnsRetainedAttr(
4851 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
Ted Kremenek9ecdfaf2009-05-09 02:44:38 +00004852 return;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004853 case AttributeList::AT_NSReturnsRetained:
Nico Weber462fd1e2015-01-07 23:50:05 +00004854 D->addAttr(::new (S.Context) NSReturnsRetainedAttr(
4855 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
Ted Kremenek9ecdfaf2009-05-09 02:44:38 +00004856 return;
4857 };
4858}
4859
John McCallcf166702011-07-22 08:53:00 +00004860static void handleObjCReturnsInnerPointerAttr(Sema &S, Decl *D,
Erich Keaneb11ebc52017-09-27 03:20:13 +00004861 const AttributeList &Attrs) {
Fariborz Jahanian8bf05562013-09-19 17:52:50 +00004862 const int EP_ObjCMethod = 1;
4863 const int EP_ObjCProperty = 2;
Fariborz Jahanian5c005832013-09-19 17:18:55 +00004864
Erich Keaneb11ebc52017-09-27 03:20:13 +00004865 SourceLocation loc = Attrs.getLoc();
Fariborz Jahanian8a5e9472013-09-19 16:37:20 +00004866 QualType resultType;
Aaron Ballman74eeeae2013-11-27 13:27:02 +00004867 if (isa<ObjCMethodDecl>(D))
Alp Toker314cc812014-01-25 16:55:45 +00004868 resultType = cast<ObjCMethodDecl>(D)->getReturnType();
Fariborz Jahanian8a5e9472013-09-19 16:37:20 +00004869 else
Aaron Ballman74eeeae2013-11-27 13:27:02 +00004870 resultType = cast<ObjCPropertyDecl>(D)->getType();
John McCallcf166702011-07-22 08:53:00 +00004871
Fariborz Jahanian044a5be2011-09-30 20:50:23 +00004872 if (!resultType->isReferenceType() &&
4873 (!resultType->isPointerType() || resultType->isObjCRetainableType())) {
Fariborz Jahanian8a5e9472013-09-19 16:37:20 +00004874 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_return_type)
John McCallcf166702011-07-22 08:53:00 +00004875 << SourceRange(loc)
Erich Keaneb11ebc52017-09-27 03:20:13 +00004876 << Attrs.getName()
Aaron Ballman74eeeae2013-11-27 13:27:02 +00004877 << (isa<ObjCMethodDecl>(D) ? EP_ObjCMethod : EP_ObjCProperty)
Fariborz Jahanian5c005832013-09-19 17:18:55 +00004878 << /*non-retainable pointer*/ 2;
John McCallcf166702011-07-22 08:53:00 +00004879
4880 // Drop the attribute.
4881 return;
4882 }
4883
Nico Weber462fd1e2015-01-07 23:50:05 +00004884 D->addAttr(::new (S.Context) ObjCReturnsInnerPointerAttr(
Erich Keaneb11ebc52017-09-27 03:20:13 +00004885 Attrs.getRange(), S.Context, Attrs.getAttributeSpellingListIndex()));
John McCallcf166702011-07-22 08:53:00 +00004886}
4887
Fariborz Jahanian566fff02012-09-07 23:46:23 +00004888static void handleObjCRequiresSuperAttr(Sema &S, Decl *D,
Erich Keaneb11ebc52017-09-27 03:20:13 +00004889 const AttributeList &Attrs) {
Aaron Ballman74eeeae2013-11-27 13:27:02 +00004890 ObjCMethodDecl *method = cast<ObjCMethodDecl>(D);
Fariborz Jahanian566fff02012-09-07 23:46:23 +00004891
Fariborz Jahanian566fff02012-09-07 23:46:23 +00004892 DeclContext *DC = method->getDeclContext();
4893 if (const ObjCProtocolDecl *PDecl = dyn_cast_or_null<ObjCProtocolDecl>(DC)) {
4894 S.Diag(D->getLocStart(), diag::warn_objc_requires_super_protocol)
Erich Keaneb11ebc52017-09-27 03:20:13 +00004895 << Attrs.getName() << 0;
Fariborz Jahanian566fff02012-09-07 23:46:23 +00004896 S.Diag(PDecl->getLocation(), diag::note_protocol_decl);
4897 return;
4898 }
4899 if (method->getMethodFamily() == OMF_dealloc) {
4900 S.Diag(D->getLocStart(), diag::warn_objc_requires_super_protocol)
Erich Keaneb11ebc52017-09-27 03:20:13 +00004901 << Attrs.getName() << 1;
Fariborz Jahanian566fff02012-09-07 23:46:23 +00004902 return;
4903 }
4904
Michael Han99315932013-01-24 16:46:58 +00004905 method->addAttr(::new (S.Context)
Erich Keaneb11ebc52017-09-27 03:20:13 +00004906 ObjCRequiresSuperAttr(Attrs.getRange(), S.Context,
4907 Attrs.getAttributeSpellingListIndex()));
Fariborz Jahanian566fff02012-09-07 23:46:23 +00004908}
4909
Aaron Ballmanfb763042013-12-02 18:05:46 +00004910static void handleCFAuditedTransferAttr(Sema &S, Decl *D,
4911 const AttributeList &Attr) {
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00004912 if (checkAttrMutualExclusion<CFUnknownTransferAttr>(S, D, Attr.getRange(),
4913 Attr.getName()))
John McCall32f5fe12011-09-30 05:12:12 +00004914 return;
John McCall32f5fe12011-09-30 05:12:12 +00004915
Aaron Ballmanfb763042013-12-02 18:05:46 +00004916 D->addAttr(::new (S.Context)
4917 CFAuditedTransferAttr(Attr.getRange(), S.Context,
4918 Attr.getAttributeSpellingListIndex()));
4919}
4920
4921static void handleCFUnknownTransferAttr(Sema &S, Decl *D,
4922 const AttributeList &Attr) {
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00004923 if (checkAttrMutualExclusion<CFAuditedTransferAttr>(S, D, Attr.getRange(),
4924 Attr.getName()))
Aaron Ballmanfb763042013-12-02 18:05:46 +00004925 return;
4926
4927 D->addAttr(::new (S.Context)
4928 CFUnknownTransferAttr(Attr.getRange(), S.Context,
4929 Attr.getAttributeSpellingListIndex()));
John McCall32f5fe12011-09-30 05:12:12 +00004930}
4931
Fariborz Jahanian0a0a3972013-11-13 23:59:17 +00004932static void handleObjCBridgeAttr(Sema &S, Scope *Sc, Decl *D,
4933 const AttributeList &Attr) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004934 IdentifierLoc * Parm = Attr.isArgIdent(0) ? Attr.getArgAsIdent(0) : nullptr;
Ted Kremenek2d3379e2013-11-21 07:20:34 +00004935
Fariborz Jahanian0a0a3972013-11-13 23:59:17 +00004936 if (!Parm) {
Ted Kremenek2d3379e2013-11-21 07:20:34 +00004937 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
Fariborz Jahanian0a0a3972013-11-13 23:59:17 +00004938 return;
4939 }
John McCall28592582015-02-01 22:34:06 +00004940
4941 // Typedefs only allow objc_bridge(id) and have some additional checking.
4942 if (auto TD = dyn_cast<TypedefNameDecl>(D)) {
4943 if (!Parm->Ident->isStr("id")) {
4944 S.Diag(Attr.getLoc(), diag::err_objc_attr_typedef_not_id)
4945 << Attr.getName();
4946 return;
4947 }
4948
4949 // Only allow 'cv void *'.
4950 QualType T = TD->getUnderlyingType();
4951 if (!T->isVoidPointerType()) {
4952 S.Diag(Attr.getLoc(), diag::err_objc_attr_typedef_not_void_pointer);
4953 return;
4954 }
4955 }
Fariborz Jahanian0a0a3972013-11-13 23:59:17 +00004956
4957 D->addAttr(::new (S.Context)
Ted Kremenek2d3379e2013-11-21 07:20:34 +00004958 ObjCBridgeAttr(Attr.getRange(), S.Context, Parm->Ident,
Fariborz Jahanian0a0a3972013-11-13 23:59:17 +00004959 Attr.getAttributeSpellingListIndex()));
4960}
4961
Fariborz Jahanian87c77912013-11-21 20:50:32 +00004962static void handleObjCBridgeMutableAttr(Sema &S, Scope *Sc, Decl *D,
4963 const AttributeList &Attr) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004964 IdentifierLoc * Parm = Attr.isArgIdent(0) ? Attr.getArgAsIdent(0) : nullptr;
4965
Fariborz Jahanian87c77912013-11-21 20:50:32 +00004966 if (!Parm) {
4967 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
4968 return;
4969 }
4970
4971 D->addAttr(::new (S.Context)
4972 ObjCBridgeMutableAttr(Attr.getRange(), S.Context, Parm->Ident,
4973 Attr.getAttributeSpellingListIndex()));
4974}
4975
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00004976static void handleObjCBridgeRelatedAttr(Sema &S, Scope *Sc, Decl *D,
4977 const AttributeList &Attr) {
4978 IdentifierInfo *RelatedClass =
Craig Topperc3ec1492014-05-26 06:22:03 +00004979 Attr.isArgIdent(0) ? Attr.getArgAsIdent(0)->Ident : nullptr;
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00004980 if (!RelatedClass) {
4981 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
4982 return;
4983 }
4984 IdentifierInfo *ClassMethod =
Craig Topperc3ec1492014-05-26 06:22:03 +00004985 Attr.getArgAsIdent(1) ? Attr.getArgAsIdent(1)->Ident : nullptr;
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00004986 IdentifierInfo *InstanceMethod =
Craig Topperc3ec1492014-05-26 06:22:03 +00004987 Attr.getArgAsIdent(2) ? Attr.getArgAsIdent(2)->Ident : nullptr;
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00004988 D->addAttr(::new (S.Context)
4989 ObjCBridgeRelatedAttr(Attr.getRange(), S.Context, RelatedClass,
4990 ClassMethod, InstanceMethod,
4991 Attr.getAttributeSpellingListIndex()));
4992}
4993
Argyrios Kyrtzidisd1438b42013-12-03 21:11:25 +00004994static void handleObjCDesignatedInitializer(Sema &S, Decl *D,
4995 const AttributeList &Attr) {
Fariborz Jahanian6efab6e2014-03-14 18:19:46 +00004996 ObjCInterfaceDecl *IFace;
Nico Weber462fd1e2015-01-07 23:50:05 +00004997 if (ObjCCategoryDecl *CatDecl =
4998 dyn_cast<ObjCCategoryDecl>(D->getDeclContext()))
Fariborz Jahanian6efab6e2014-03-14 18:19:46 +00004999 IFace = CatDecl->getClassInterface();
5000 else
5001 IFace = cast<ObjCInterfaceDecl>(D->getDeclContext());
Ben Langmuirc91ac9e2015-01-20 20:41:36 +00005002
5003 if (!IFace)
5004 return;
5005
Argyrios Kyrtzidis9ed9e5f2013-12-03 21:11:30 +00005006 IFace->setHasDesignatedInitializers();
Argyrios Kyrtzidise8186812013-12-07 06:08:04 +00005007 D->addAttr(::new (S.Context)
Argyrios Kyrtzidisd1438b42013-12-03 21:11:25 +00005008 ObjCDesignatedInitializerAttr(Attr.getRange(), S.Context,
5009 Attr.getAttributeSpellingListIndex()));
5010}
5011
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00005012static void handleObjCRuntimeName(Sema &S, Decl *D,
5013 const AttributeList &Attr) {
Fariborz Jahaniana2e5deb2014-07-16 19:44:34 +00005014 StringRef MetaDataName;
5015 if (!S.checkStringLiteralArgumentAttr(Attr, 0, MetaDataName))
5016 return;
5017 D->addAttr(::new (S.Context)
5018 ObjCRuntimeNameAttr(Attr.getRange(), S.Context,
5019 MetaDataName,
5020 Attr.getAttributeSpellingListIndex()));
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00005021}
5022
Nico Webera6916892016-06-10 18:53:04 +00005023// When a user wants to use objc_boxable with a union or struct
5024// but they don't have access to the declaration (legacy/third-party code)
5025// then they can 'enable' this feature with a typedef:
Alex Denisovfde64952015-06-26 05:28:36 +00005026// typedef struct __attribute((objc_boxable)) legacy_struct legacy_struct;
5027static void handleObjCBoxable(Sema &S, Decl *D, const AttributeList &Attr) {
5028 bool notify = false;
5029
5030 RecordDecl *RD = dyn_cast<RecordDecl>(D);
5031 if (RD && RD->getDefinition()) {
5032 RD = RD->getDefinition();
5033 notify = true;
5034 }
5035
5036 if (RD) {
5037 ObjCBoxableAttr *BoxableAttr = ::new (S.Context)
5038 ObjCBoxableAttr(Attr.getRange(), S.Context,
5039 Attr.getAttributeSpellingListIndex());
5040 RD->addAttr(BoxableAttr);
5041 if (notify) {
5042 // we need to notify ASTReader/ASTWriter about
5043 // modification of existing declaration
5044 if (ASTMutationListener *L = S.getASTMutationListener())
5045 L->AddedAttributeToRecord(BoxableAttr, RD);
5046 }
5047 }
5048}
5049
Chandler Carruthedc2c642011-07-02 00:01:44 +00005050static void handleObjCOwnershipAttr(Sema &S, Decl *D,
5051 const AttributeList &Attr) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00005052 if (hasDeclarator(D)) return;
John McCall31168b02011-06-15 23:02:42 +00005053
Chandler Carruthff4c4f02011-07-01 23:49:12 +00005054 S.Diag(D->getLocStart(), diag::err_attribute_wrong_decl_type)
Douglas Gregor5c3cc422012-03-14 16:55:17 +00005055 << Attr.getRange() << Attr.getName() << ExpectedVariable;
John McCall31168b02011-06-15 23:02:42 +00005056}
5057
Chandler Carruthedc2c642011-07-02 00:01:44 +00005058static void handleObjCPreciseLifetimeAttr(Sema &S, Decl *D,
5059 const AttributeList &Attr) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00005060 ValueDecl *vd = cast<ValueDecl>(D);
John McCall31168b02011-06-15 23:02:42 +00005061 QualType type = vd->getType();
5062
5063 if (!type->isDependentType() &&
5064 !type->isObjCLifetimeType()) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00005065 S.Diag(Attr.getLoc(), diag::err_objc_precise_lifetime_bad_type)
John McCall31168b02011-06-15 23:02:42 +00005066 << type;
5067 return;
5068 }
5069
5070 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5071
5072 // If we have no lifetime yet, check the lifetime we're presumably
5073 // going to infer.
5074 if (lifetime == Qualifiers::OCL_None && !type->isDependentType())
5075 lifetime = type->getObjCARCImplicitLifetime();
5076
5077 switch (lifetime) {
5078 case Qualifiers::OCL_None:
5079 assert(type->isDependentType() &&
5080 "didn't infer lifetime for non-dependent type?");
5081 break;
5082
5083 case Qualifiers::OCL_Weak: // meaningful
5084 case Qualifiers::OCL_Strong: // meaningful
5085 break;
5086
5087 case Qualifiers::OCL_ExplicitNone:
5088 case Qualifiers::OCL_Autoreleasing:
Chandler Carruthff4c4f02011-07-01 23:49:12 +00005089 S.Diag(Attr.getLoc(), diag::warn_objc_precise_lifetime_meaningless)
John McCall31168b02011-06-15 23:02:42 +00005090 << (lifetime == Qualifiers::OCL_Autoreleasing);
5091 break;
5092 }
5093
Chandler Carruthff4c4f02011-07-01 23:49:12 +00005094 D->addAttr(::new (S.Context)
Michael Han99315932013-01-24 16:46:58 +00005095 ObjCPreciseLifetimeAttr(Attr.getRange(), S.Context,
5096 Attr.getAttributeSpellingListIndex()));
John McCall31168b02011-06-15 23:02:42 +00005097}
5098
Francois Picheta83957a2010-12-19 06:50:37 +00005099//===----------------------------------------------------------------------===//
5100// Microsoft specific attribute handlers.
5101//===----------------------------------------------------------------------===//
5102
Nico Weber88f5ed92016-09-13 18:55:26 +00005103UuidAttr *Sema::mergeUuidAttr(Decl *D, SourceRange Range,
5104 unsigned AttrSpellingListIndex, StringRef Uuid) {
5105 if (const auto *UA = D->getAttr<UuidAttr>()) {
Nico Weberd58c2602016-09-14 01:16:54 +00005106 if (UA->getGuid().equals_lower(Uuid))
Nico Weber88f5ed92016-09-13 18:55:26 +00005107 return nullptr;
5108 Diag(UA->getLocation(), diag::err_mismatched_uuid);
5109 Diag(Range.getBegin(), diag::note_previous_uuid);
5110 D->dropAttr<UuidAttr>();
5111 }
5112
5113 return ::new (Context) UuidAttr(Range, Context, Uuid, AttrSpellingListIndex);
5114}
5115
Chandler Carruthedc2c642011-07-02 00:01:44 +00005116static void handleUuidAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballmandf8fe4c2013-11-24 21:35:16 +00005117 if (!S.LangOpts.CPlusPlus) {
5118 S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang)
5119 << Attr.getName() << AttributeLangSupport::C;
5120 return;
5121 }
5122
Benjamin Kramer6ee15622013-09-13 15:35:43 +00005123 StringRef StrRef;
5124 SourceLocation LiteralLoc;
Tim Northover6a6b63b2013-10-01 14:34:18 +00005125 if (!S.checkStringLiteralArgumentAttr(Attr, 0, StrRef, &LiteralLoc))
Reid Kleckner140c4a72013-05-17 14:04:52 +00005126 return;
Francois Pichet7da11662010-12-20 01:41:49 +00005127
David Majnemer89085342013-08-09 08:56:20 +00005128 // GUID format is "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" or
5129 // "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}", normalize to the former.
David Majnemer89085342013-08-09 08:56:20 +00005130 if (StrRef.size() == 38 && StrRef.front() == '{' && StrRef.back() == '}')
5131 StrRef = StrRef.drop_front().drop_back();
Francois Pichet7da11662010-12-20 01:41:49 +00005132
Reid Kleckner140c4a72013-05-17 14:04:52 +00005133 // Validate GUID length.
David Majnemer89085342013-08-09 08:56:20 +00005134 if (StrRef.size() != 36) {
Benjamin Kramer6ee15622013-09-13 15:35:43 +00005135 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
Reid Kleckner140c4a72013-05-17 14:04:52 +00005136 return;
5137 }
Anders Carlsson19588aa2011-01-23 21:07:30 +00005138
David Majnemer89085342013-08-09 08:56:20 +00005139 for (unsigned i = 0; i < 36; ++i) {
Reid Kleckner140c4a72013-05-17 14:04:52 +00005140 if (i == 8 || i == 13 || i == 18 || i == 23) {
David Majnemer89085342013-08-09 08:56:20 +00005141 if (StrRef[i] != '-') {
Benjamin Kramer6ee15622013-09-13 15:35:43 +00005142 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
Francois Pichet7da11662010-12-20 01:41:49 +00005143 return;
5144 }
David Majnemer89085342013-08-09 08:56:20 +00005145 } else if (!isHexDigit(StrRef[i])) {
Benjamin Kramer6ee15622013-09-13 15:35:43 +00005146 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
Reid Kleckner140c4a72013-05-17 14:04:52 +00005147 return;
Francois Pichet7da11662010-12-20 01:41:49 +00005148 }
Reid Kleckner140c4a72013-05-17 14:04:52 +00005149 }
Francois Picheta83957a2010-12-19 06:50:37 +00005150
Nico Weber469891e2017-05-05 17:05:56 +00005151 // FIXME: It'd be nice to also emit a fixit removing uuid(...) (and, if it's
5152 // the only thing in the [] list, the [] too), and add an insertion of
5153 // __declspec(uuid(...)). But sadly, neither the SourceLocs of the commas
5154 // separating attributes nor of the [ and the ] are in the AST.
Nico Weber0a234042017-05-05 17:15:08 +00005155 // Cf "SourceLocations of attribute list delimiters - [[ ... , ... ]] etc"
Nico Weber469891e2017-05-05 17:05:56 +00005156 // on cfe-dev.
5157 if (Attr.isMicrosoftAttribute()) // Check for [uuid(...)] spelling.
5158 S.Diag(Attr.getLoc(), diag::warn_atl_uuid_deprecated);
5159
Nico Weber88f5ed92016-09-13 18:55:26 +00005160 UuidAttr *UA = S.mergeUuidAttr(D, Attr.getRange(),
5161 Attr.getAttributeSpellingListIndex(), StrRef);
5162 if (UA)
5163 D->addAttr(UA);
Charles Davis163855f2010-02-16 18:27:26 +00005164}
5165
David Majnemer2c4e00a2014-01-29 22:07:36 +00005166static void handleMSInheritanceAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5167 if (!S.LangOpts.CPlusPlus) {
5168 S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang)
5169 << Attr.getName() << AttributeLangSupport::C;
5170 return;
5171 }
5172 MSInheritanceAttr *IA = S.mergeMSInheritanceAttr(
David Majnemer4bb09802014-02-10 19:50:15 +00005173 D, Attr.getRange(), /*BestCase=*/true,
5174 Attr.getAttributeSpellingListIndex(),
David Majnemer2c4e00a2014-01-29 22:07:36 +00005175 (MSInheritanceAttr::Spelling)Attr.getSemanticSpelling());
David Majnemer929025d2016-01-26 19:30:26 +00005176 if (IA) {
David Majnemer2c4e00a2014-01-29 22:07:36 +00005177 D->addAttr(IA);
David Majnemer929025d2016-01-26 19:30:26 +00005178 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
5179 }
David Majnemer2c4e00a2014-01-29 22:07:36 +00005180}
5181
Reid Kleckner7d6d2702014-05-01 03:16:47 +00005182static void handleDeclspecThreadAttr(Sema &S, Decl *D,
5183 const AttributeList &Attr) {
5184 VarDecl *VD = cast<VarDecl>(D);
5185 if (!S.Context.getTargetInfo().isTLSSupported()) {
5186 S.Diag(Attr.getLoc(), diag::err_thread_unsupported);
5187 return;
5188 }
5189 if (VD->getTSCSpec() != TSCS_unspecified) {
5190 S.Diag(Attr.getLoc(), diag::err_declspec_thread_on_thread_variable);
5191 return;
5192 }
5193 if (VD->hasLocalStorage()) {
5194 S.Diag(Attr.getLoc(), diag::err_thread_non_global) << "__declspec(thread)";
5195 return;
5196 }
5197 VD->addAttr(::new (S.Context) ThreadAttr(
5198 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
5199}
5200
Dmitry Polukhinbf17ecf2016-03-09 15:30:53 +00005201static void handleAbiTagAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5202 SmallVector<StringRef, 4> Tags;
5203 for (unsigned I = 0, E = Attr.getNumArgs(); I != E; ++I) {
5204 StringRef Tag;
5205 if (!S.checkStringLiteralArgumentAttr(Attr, I, Tag))
5206 return;
5207 Tags.push_back(Tag);
5208 }
5209
5210 if (const auto *NS = dyn_cast<NamespaceDecl>(D)) {
5211 if (!NS->isInline()) {
5212 S.Diag(Attr.getLoc(), diag::warn_attr_abi_tag_namespace) << 0;
5213 return;
5214 }
5215 if (NS->isAnonymousNamespace()) {
5216 S.Diag(Attr.getLoc(), diag::warn_attr_abi_tag_namespace) << 1;
5217 return;
5218 }
5219 if (Attr.getNumArgs() == 0)
5220 Tags.push_back(NS->getName());
5221 } else if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
5222 return;
5223
5224 // Store tags sorted and without duplicates.
5225 std::sort(Tags.begin(), Tags.end());
5226 Tags.erase(std::unique(Tags.begin(), Tags.end()), Tags.end());
5227
5228 D->addAttr(::new (S.Context)
5229 AbiTagAttr(Attr.getRange(), S.Context, Tags.data(), Tags.size(),
5230 Attr.getAttributeSpellingListIndex()));
Dmitry Polukhinbf17ecf2016-03-09 15:30:53 +00005231}
5232
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005233static void handleARMInterruptAttr(Sema &S, Decl *D,
5234 const AttributeList &Attr) {
5235 // Check the attribute arguments.
5236 if (Attr.getNumArgs() > 1) {
5237 S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments)
5238 << Attr.getName() << 1;
5239 return;
5240 }
5241
5242 StringRef Str;
5243 SourceLocation ArgLoc;
5244
5245 if (Attr.getNumArgs() == 0)
5246 Str = "";
5247 else if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &ArgLoc))
5248 return;
5249
5250 ARMInterruptAttr::InterruptType Kind;
5251 if (!ARMInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
5252 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
5253 << Attr.getName() << Str << ArgLoc;
5254 return;
5255 }
5256
5257 unsigned Index = Attr.getAttributeSpellingListIndex();
5258 D->addAttr(::new (S.Context)
5259 ARMInterruptAttr(Attr.getLoc(), S.Context, Kind, Index));
5260}
5261
5262static void handleMSP430InterruptAttr(Sema &S, Decl *D,
5263 const AttributeList &Attr) {
5264 if (!checkAttributeNumArgs(S, Attr, 1))
5265 return;
5266
5267 if (!Attr.isArgExpr(0)) {
5268 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << Attr.getName()
5269 << AANT_ArgumentIntegerConstant;
5270 return;
5271 }
5272
5273 // FIXME: Check for decl - it should be void ()(void).
5274
5275 Expr *NumParamsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
5276 llvm::APSInt NumParams(32);
5277 if (!NumParamsExpr->isIntegerConstantExpr(NumParams, S.Context)) {
5278 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
5279 << Attr.getName() << AANT_ArgumentIntegerConstant
5280 << NumParamsExpr->getSourceRange();
5281 return;
5282 }
5283
5284 unsigned Num = NumParams.getLimitedValue(255);
5285 if ((Num & 1) || Num > 30) {
5286 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
5287 << Attr.getName() << (int)NumParams.getSExtValue()
5288 << NumParamsExpr->getSourceRange();
5289 return;
5290 }
5291
Aaron Ballman36a53502014-01-16 13:03:14 +00005292 D->addAttr(::new (S.Context)
5293 MSP430InterruptAttr(Attr.getLoc(), S.Context, Num,
5294 Attr.getAttributeSpellingListIndex()));
5295 D->addAttr(UsedAttr::CreateImplicit(S.Context));
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005296}
5297
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00005298static void handleMipsInterruptAttr(Sema &S, Decl *D,
5299 const AttributeList &Attr) {
5300 // Only one optional argument permitted.
5301 if (Attr.getNumArgs() > 1) {
5302 S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments)
5303 << Attr.getName() << 1;
5304 return;
5305 }
5306
5307 StringRef Str;
5308 SourceLocation ArgLoc;
5309
5310 if (Attr.getNumArgs() == 0)
5311 Str = "";
5312 else if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &ArgLoc))
5313 return;
5314
5315 // Semantic checks for a function with the 'interrupt' attribute for MIPS:
5316 // a) Must be a function.
5317 // b) Must have no parameters.
5318 // c) Must have the 'void' return type.
5319 // d) Cannot have the 'mips16' attribute, as that instruction set
5320 // lacks the 'eret' instruction.
5321 // e) The attribute itself must either have no argument or one of the
5322 // valid interrupt types, see [MipsInterruptDocs].
5323
5324 if (!isFunctionOrMethod(D)) {
5325 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5326 << "'interrupt'" << ExpectedFunctionOrMethod;
5327 return;
5328 }
5329
5330 if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) {
5331 S.Diag(D->getLocation(), diag::warn_mips_interrupt_attribute)
5332 << 0;
5333 return;
5334 }
5335
5336 if (!getFunctionOrMethodResultType(D)->isVoidType()) {
5337 S.Diag(D->getLocation(), diag::warn_mips_interrupt_attribute)
5338 << 1;
5339 return;
5340 }
5341
5342 if (checkAttrMutualExclusion<Mips16Attr>(S, D, Attr.getRange(),
5343 Attr.getName()))
5344 return;
5345
5346 MipsInterruptAttr::InterruptType Kind;
5347 if (!MipsInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
5348 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
5349 << Attr.getName() << "'" + std::string(Str) + "'";
5350 return;
5351 }
5352
5353 D->addAttr(::new (S.Context) MipsInterruptAttr(
5354 Attr.getLoc(), S.Context, Kind, Attr.getAttributeSpellingListIndex()));
5355}
5356
Alexey Bataevd51e9932016-01-15 04:06:31 +00005357static void handleAnyX86InterruptAttr(Sema &S, Decl *D,
5358 const AttributeList &Attr) {
5359 // Semantic checks for a function with the 'interrupt' attribute.
5360 // a) Must be a function.
5361 // b) Must have the 'void' return type.
5362 // c) Must take 1 or 2 arguments.
5363 // d) The 1st argument must be a pointer.
5364 // e) The 2nd argument (if any) must be an unsigned integer.
5365 if (!isFunctionOrMethod(D) || !hasFunctionProto(D) || isInstanceMethod(D) ||
5366 CXXMethodDecl::isStaticOverloadedOperator(
5367 cast<NamedDecl>(D)->getDeclName().getCXXOverloadedOperator())) {
5368 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
5369 << Attr.getName() << ExpectedFunctionWithProtoType;
5370 return;
5371 }
5372 // Interrupt handler must have void return type.
5373 if (!getFunctionOrMethodResultType(D)->isVoidType()) {
5374 S.Diag(getFunctionOrMethodResultSourceRange(D).getBegin(),
5375 diag::err_anyx86_interrupt_attribute)
5376 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
5377 ? 0
5378 : 1)
5379 << 0;
5380 return;
5381 }
5382 // Interrupt handler must have 1 or 2 parameters.
5383 unsigned NumParams = getFunctionOrMethodNumParams(D);
5384 if (NumParams < 1 || NumParams > 2) {
5385 S.Diag(D->getLocStart(), diag::err_anyx86_interrupt_attribute)
5386 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
5387 ? 0
5388 : 1)
5389 << 1;
5390 return;
5391 }
5392 // The first argument must be a pointer.
5393 if (!getFunctionOrMethodParamType(D, 0)->isPointerType()) {
5394 S.Diag(getFunctionOrMethodParamRange(D, 0).getBegin(),
5395 diag::err_anyx86_interrupt_attribute)
5396 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
5397 ? 0
5398 : 1)
5399 << 2;
5400 return;
5401 }
5402 // The second argument, if present, must be an unsigned integer.
5403 unsigned TypeSize =
5404 S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64
5405 ? 64
5406 : 32;
5407 if (NumParams == 2 &&
5408 (!getFunctionOrMethodParamType(D, 1)->isUnsignedIntegerType() ||
5409 S.Context.getTypeSize(getFunctionOrMethodParamType(D, 1)) != TypeSize)) {
5410 S.Diag(getFunctionOrMethodParamRange(D, 1).getBegin(),
5411 diag::err_anyx86_interrupt_attribute)
5412 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
5413 ? 0
5414 : 1)
5415 << 3 << S.Context.getIntTypeForBitwidth(TypeSize, /*Signed=*/false);
5416 return;
5417 }
5418 D->addAttr(::new (S.Context) AnyX86InterruptAttr(
5419 Attr.getLoc(), S.Context, Attr.getAttributeSpellingListIndex()));
5420 D->addAttr(UsedAttr::CreateImplicit(S.Context));
5421}
5422
Dylan McKaye8232d72017-02-08 05:09:26 +00005423static void handleAVRInterruptAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5424 if (!isFunctionOrMethod(D)) {
5425 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5426 << "'interrupt'" << ExpectedFunction;
5427 return;
5428 }
5429
5430 if (!checkAttributeNumArgs(S, Attr, 0))
5431 return;
5432
5433 handleSimpleAttribute<AVRInterruptAttr>(S, D, Attr);
5434}
5435
5436static void handleAVRSignalAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5437 if (!isFunctionOrMethod(D)) {
5438 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5439 << "'signal'" << ExpectedFunction;
5440 return;
5441 }
5442
5443 if (!checkAttributeNumArgs(S, Attr, 0))
5444 return;
5445
5446 handleSimpleAttribute<AVRSignalAttr>(S, D, Attr);
5447}
5448
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005449static void handleInterruptAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5450 // Dispatch the interrupt attribute based on the current target.
Alexey Bataevd51e9932016-01-15 04:06:31 +00005451 switch (S.Context.getTargetInfo().getTriple().getArch()) {
5452 case llvm::Triple::msp430:
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005453 handleMSP430InterruptAttr(S, D, Attr);
Alexey Bataevd51e9932016-01-15 04:06:31 +00005454 break;
5455 case llvm::Triple::mipsel:
5456 case llvm::Triple::mips:
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00005457 handleMipsInterruptAttr(S, D, Attr);
Alexey Bataevd51e9932016-01-15 04:06:31 +00005458 break;
5459 case llvm::Triple::x86:
5460 case llvm::Triple::x86_64:
5461 handleAnyX86InterruptAttr(S, D, Attr);
5462 break;
Dylan McKaye8232d72017-02-08 05:09:26 +00005463 case llvm::Triple::avr:
5464 handleAVRInterruptAttr(S, D, Attr);
5465 break;
Alexey Bataevd51e9932016-01-15 04:06:31 +00005466 default:
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005467 handleARMInterruptAttr(S, D, Attr);
Alexey Bataevd51e9932016-01-15 04:06:31 +00005468 break;
5469 }
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005470}
5471
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00005472static void handleAMDGPUFlatWorkGroupSizeAttr(Sema &S, Decl *D,
5473 const AttributeList &Attr) {
5474 uint32_t Min = 0;
5475 Expr *MinExpr = Attr.getArgAsExpr(0);
5476 if (!checkUInt32Argument(S, Attr, MinExpr, Min))
Matt Arsenault43fae6c2014-12-04 20:38:18 +00005477 return;
5478
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00005479 uint32_t Max = 0;
5480 Expr *MaxExpr = Attr.getArgAsExpr(1);
5481 if (!checkUInt32Argument(S, Attr, MaxExpr, Max))
5482 return;
5483
5484 if (Min == 0 && Max != 0) {
5485 S.Diag(Attr.getLoc(), diag::err_attribute_argument_invalid)
5486 << Attr.getName() << 0;
5487 return;
5488 }
5489 if (Min > Max) {
5490 S.Diag(Attr.getLoc(), diag::err_attribute_argument_invalid)
5491 << Attr.getName() << 1;
5492 return;
5493 }
5494
Matt Arsenault43fae6c2014-12-04 20:38:18 +00005495 D->addAttr(::new (S.Context)
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00005496 AMDGPUFlatWorkGroupSizeAttr(Attr.getLoc(), S.Context, Min, Max,
5497 Attr.getAttributeSpellingListIndex()));
5498}
5499
5500static void handleAMDGPUWavesPerEUAttr(Sema &S, Decl *D,
5501 const AttributeList &Attr) {
5502 uint32_t Min = 0;
5503 Expr *MinExpr = Attr.getArgAsExpr(0);
5504 if (!checkUInt32Argument(S, Attr, MinExpr, Min))
5505 return;
5506
5507 uint32_t Max = 0;
5508 if (Attr.getNumArgs() == 2) {
5509 Expr *MaxExpr = Attr.getArgAsExpr(1);
5510 if (!checkUInt32Argument(S, Attr, MaxExpr, Max))
5511 return;
5512 }
5513
5514 if (Min == 0 && Max != 0) {
5515 S.Diag(Attr.getLoc(), diag::err_attribute_argument_invalid)
5516 << Attr.getName() << 0;
5517 return;
5518 }
5519 if (Max != 0 && Min > Max) {
5520 S.Diag(Attr.getLoc(), diag::err_attribute_argument_invalid)
5521 << Attr.getName() << 1;
5522 return;
5523 }
5524
5525 D->addAttr(::new (S.Context)
5526 AMDGPUWavesPerEUAttr(Attr.getLoc(), S.Context, Min, Max,
5527 Attr.getAttributeSpellingListIndex()));
Matt Arsenault43fae6c2014-12-04 20:38:18 +00005528}
5529
5530static void handleAMDGPUNumSGPRAttr(Sema &S, Decl *D,
5531 const AttributeList &Attr) {
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00005532 uint32_t NumSGPR = 0;
5533 Expr *NumSGPRExpr = Attr.getArgAsExpr(0);
5534 if (!checkUInt32Argument(S, Attr, NumSGPRExpr, NumSGPR))
Matt Arsenault43fae6c2014-12-04 20:38:18 +00005535 return;
5536
5537 D->addAttr(::new (S.Context)
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00005538 AMDGPUNumSGPRAttr(Attr.getLoc(), S.Context, NumSGPR,
5539 Attr.getAttributeSpellingListIndex()));
5540}
5541
5542static void handleAMDGPUNumVGPRAttr(Sema &S, Decl *D,
5543 const AttributeList &Attr) {
5544 uint32_t NumVGPR = 0;
5545 Expr *NumVGPRExpr = Attr.getArgAsExpr(0);
5546 if (!checkUInt32Argument(S, Attr, NumVGPRExpr, NumVGPR))
5547 return;
5548
5549 D->addAttr(::new (S.Context)
5550 AMDGPUNumVGPRAttr(Attr.getLoc(), S.Context, NumVGPR,
Matt Arsenault43fae6c2014-12-04 20:38:18 +00005551 Attr.getAttributeSpellingListIndex()));
5552}
5553
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005554static void handleX86ForceAlignArgPointerAttr(Sema &S, Decl *D,
5555 const AttributeList& Attr) {
5556 // If we try to apply it to a function pointer, don't warn, but don't
5557 // do anything, either. It doesn't matter anyway, because there's nothing
5558 // special about calling a force_align_arg_pointer function.
5559 ValueDecl *VD = dyn_cast<ValueDecl>(D);
5560 if (VD && VD->getType()->isFunctionPointerType())
5561 return;
5562 // Also don't warn on function pointer typedefs.
5563 TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D);
5564 if (TD && (TD->getUnderlyingType()->isFunctionPointerType() ||
5565 TD->getUnderlyingType()->isFunctionType()))
5566 return;
5567 // Attribute can only be applied to function types.
5568 if (!isa<FunctionDecl>(D)) {
5569 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
5570 << Attr.getName() << /* function */0;
5571 return;
5572 }
5573
Aaron Ballman36a53502014-01-16 13:03:14 +00005574 D->addAttr(::new (S.Context)
5575 X86ForceAlignArgPointerAttr(Attr.getRange(), S.Context,
5576 Attr.getAttributeSpellingListIndex()));
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005577}
5578
David Majnemercd3ebfe2016-05-23 17:16:12 +00005579static void handleLayoutVersion(Sema &S, Decl *D, const AttributeList &Attr) {
5580 uint32_t Version;
5581 Expr *VersionExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
5582 if (!checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), Version))
5583 return;
5584
5585 // TODO: Investigate what happens with the next major version of MSVC.
5586 if (Version != LangOptions::MSVC2015) {
5587 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
5588 << Attr.getName() << Version << VersionExpr->getSourceRange();
5589 return;
5590 }
5591
5592 D->addAttr(::new (S.Context)
5593 LayoutVersionAttr(Attr.getRange(), S.Context, Version,
5594 Attr.getAttributeSpellingListIndex()));
5595}
5596
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005597DLLImportAttr *Sema::mergeDLLImportAttr(Decl *D, SourceRange Range,
5598 unsigned AttrSpellingListIndex) {
5599 if (D->hasAttr<DLLExportAttr>()) {
Nico Rieck60478662014-02-22 19:47:30 +00005600 Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'dllimport'";
Craig Topperc3ec1492014-05-26 06:22:03 +00005601 return nullptr;
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005602 }
5603
5604 if (D->hasAttr<DLLImportAttr>())
Craig Topperc3ec1492014-05-26 06:22:03 +00005605 return nullptr;
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005606
Aaron Ballman3f5f3e72014-01-20 16:15:55 +00005607 return ::new (Context) DLLImportAttr(Range, Context, AttrSpellingListIndex);
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005608}
5609
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005610DLLExportAttr *Sema::mergeDLLExportAttr(Decl *D, SourceRange Range,
5611 unsigned AttrSpellingListIndex) {
5612 if (DLLImportAttr *Import = D->getAttr<DLLImportAttr>()) {
Nico Rieck60478662014-02-22 19:47:30 +00005613 Diag(Import->getLocation(), diag::warn_attribute_ignored) << Import;
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005614 D->dropAttr<DLLImportAttr>();
5615 }
5616
5617 if (D->hasAttr<DLLExportAttr>())
Craig Topperc3ec1492014-05-26 06:22:03 +00005618 return nullptr;
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005619
Aaron Ballman3f5f3e72014-01-20 16:15:55 +00005620 return ::new (Context) DLLExportAttr(Range, Context, AttrSpellingListIndex);
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005621}
5622
Hans Wennborge82f19c2014-06-24 23:57:05 +00005623static void handleDLLAttr(Sema &S, Decl *D, const AttributeList &A) {
Hans Wennborg5e645282014-06-24 23:57:13 +00005624 if (isa<ClassTemplatePartialSpecializationDecl>(D) &&
5625 S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5626 S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored)
5627 << A.getName();
5628 return;
5629 }
5630
Hans Wennborg606bd6d2014-11-03 14:24:45 +00005631 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5632 if (FD->isInlined() && A.getKind() == AttributeList::AT_DLLImport &&
5633 !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5634 // MinGW doesn't allow dllimport on inline functions.
5635 S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored_on_inline)
5636 << A.getName();
5637 return;
5638 }
5639 }
5640
Hans Wennborg5869ec42015-09-15 21:05:30 +00005641 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
5642 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5643 MD->getParent()->isLambda()) {
5644 S.Diag(A.getRange().getBegin(), diag::err_attribute_dll_lambda) << A.getName();
5645 return;
5646 }
5647 }
5648
Hans Wennborge82f19c2014-06-24 23:57:05 +00005649 unsigned Index = A.getAttributeSpellingListIndex();
5650 Attr *NewAttr = A.getKind() == AttributeList::AT_DLLExport
5651 ? (Attr *)S.mergeDLLExportAttr(D, A.getRange(), Index)
5652 : (Attr *)S.mergeDLLImportAttr(D, A.getRange(), Index);
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005653 if (NewAttr)
5654 D->addAttr(NewAttr);
5655}
5656
David Majnemer2c4e00a2014-01-29 22:07:36 +00005657MSInheritanceAttr *
David Majnemer4bb09802014-02-10 19:50:15 +00005658Sema::mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase,
David Majnemer2c4e00a2014-01-29 22:07:36 +00005659 unsigned AttrSpellingListIndex,
5660 MSInheritanceAttr::Spelling SemanticSpelling) {
5661 if (MSInheritanceAttr *IA = D->getAttr<MSInheritanceAttr>()) {
5662 if (IA->getSemanticSpelling() == SemanticSpelling)
Craig Topperc3ec1492014-05-26 06:22:03 +00005663 return nullptr;
David Majnemer2c4e00a2014-01-29 22:07:36 +00005664 Diag(IA->getLocation(), diag::err_mismatched_ms_inheritance)
5665 << 1 /*previous declaration*/;
5666 Diag(Range.getBegin(), diag::note_previous_ms_inheritance);
5667 D->dropAttr<MSInheritanceAttr>();
5668 }
5669
5670 CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
5671 if (RD->hasDefinition()) {
David Majnemer4bb09802014-02-10 19:50:15 +00005672 if (checkMSInheritanceAttrOnDefinition(RD, Range, BestCase,
5673 SemanticSpelling)) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005674 return nullptr;
David Majnemer2c4e00a2014-01-29 22:07:36 +00005675 }
5676 } else {
5677 if (isa<ClassTemplatePartialSpecializationDecl>(RD)) {
5678 Diag(Range.getBegin(), diag::warn_ignored_ms_inheritance)
5679 << 1 /*partial specialization*/;
Craig Topperc3ec1492014-05-26 06:22:03 +00005680 return nullptr;
David Majnemer2c4e00a2014-01-29 22:07:36 +00005681 }
5682 if (RD->getDescribedClassTemplate()) {
5683 Diag(Range.getBegin(), diag::warn_ignored_ms_inheritance)
5684 << 0 /*primary template*/;
Craig Topperc3ec1492014-05-26 06:22:03 +00005685 return nullptr;
David Majnemer2c4e00a2014-01-29 22:07:36 +00005686 }
5687 }
5688
5689 return ::new (Context)
David Majnemer4bb09802014-02-10 19:50:15 +00005690 MSInheritanceAttr(Range, Context, BestCase, AttrSpellingListIndex);
David Majnemer2c4e00a2014-01-29 22:07:36 +00005691}
5692
Aaron Ballmanefe348e2014-02-18 17:36:50 +00005693static void handleCapabilityAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5694 // The capability attributes take a single string parameter for the name of
5695 // the capability they represent. The lockable attribute does not take any
5696 // parameters. However, semantically, both attributes represent the same
5697 // concept, and so they use the same semantic attribute. Eventually, the
5698 // lockable attribute will be removed.
Aaron Ballman6c810072014-03-05 21:47:13 +00005699 //
Alp Toker958027b2014-07-14 19:42:55 +00005700 // For backward compatibility, any capability which has no specified string
Aaron Ballman6c810072014-03-05 21:47:13 +00005701 // literal will be considered a "mutex."
5702 StringRef N("mutex");
Aaron Ballmanefe348e2014-02-18 17:36:50 +00005703 SourceLocation LiteralLoc;
5704 if (Attr.getKind() == AttributeList::AT_Capability &&
5705 !S.checkStringLiteralArgumentAttr(Attr, 0, N, &LiteralLoc))
5706 return;
5707
Aaron Ballman6c810072014-03-05 21:47:13 +00005708 // Currently, there are only two names allowed for a capability: role and
5709 // mutex (case insensitive). Diagnose other capability names.
5710 if (!N.equals_lower("mutex") && !N.equals_lower("role"))
5711 S.Diag(LiteralLoc, diag::warn_invalid_capability_name) << N;
5712
Aaron Ballmanefe348e2014-02-18 17:36:50 +00005713 D->addAttr(::new (S.Context) CapabilityAttr(Attr.getRange(), S.Context, N,
5714 Attr.getAttributeSpellingListIndex()));
5715}
5716
Aaron Ballman9e9d1842014-02-21 21:05:14 +00005717static void handleAssertCapabilityAttr(Sema &S, Decl *D,
5718 const AttributeList &Attr) {
Josh Gaoec1369e2017-08-08 19:44:34 +00005719 SmallVector<Expr*, 1> Args;
5720 if (!checkLockFunAttrCommon(S, D, Attr, Args))
5721 return;
5722
Aaron Ballman9e9d1842014-02-21 21:05:14 +00005723 D->addAttr(::new (S.Context) AssertCapabilityAttr(Attr.getRange(), S.Context,
Josh Gaoec1369e2017-08-08 19:44:34 +00005724 Args.data(), Args.size(),
Aaron Ballman9e9d1842014-02-21 21:05:14 +00005725 Attr.getAttributeSpellingListIndex()));
5726}
5727
5728static void handleAcquireCapabilityAttr(Sema &S, Decl *D,
5729 const AttributeList &Attr) {
5730 SmallVector<Expr*, 1> Args;
Aaron Ballman18d85ae2014-03-20 16:02:49 +00005731 if (!checkLockFunAttrCommon(S, D, Attr, Args))
Aaron Ballman9e9d1842014-02-21 21:05:14 +00005732 return;
5733
5734 D->addAttr(::new (S.Context) AcquireCapabilityAttr(Attr.getRange(),
5735 S.Context,
5736 Args.data(), Args.size(),
5737 Attr.getAttributeSpellingListIndex()));
5738}
5739
5740static void handleTryAcquireCapabilityAttr(Sema &S, Decl *D,
5741 const AttributeList &Attr) {
5742 SmallVector<Expr*, 2> Args;
5743 if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
5744 return;
5745
5746 D->addAttr(::new (S.Context) TryAcquireCapabilityAttr(Attr.getRange(),
5747 S.Context,
5748 Attr.getArgAsExpr(0),
5749 Args.data(),
5750 Args.size(),
5751 Attr.getAttributeSpellingListIndex()));
5752}
5753
5754static void handleReleaseCapabilityAttr(Sema &S, Decl *D,
5755 const AttributeList &Attr) {
Aaron Ballman9e9d1842014-02-21 21:05:14 +00005756 // Check that all arguments are lockable objects.
Aaron Ballman18d85ae2014-03-20 16:02:49 +00005757 SmallVector<Expr *, 1> Args;
Aaron Ballman69e6e7c2014-03-24 19:29:19 +00005758 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 0, true);
Aaron Ballman9e9d1842014-02-21 21:05:14 +00005759
Aaron Ballman18d85ae2014-03-20 16:02:49 +00005760 D->addAttr(::new (S.Context) ReleaseCapabilityAttr(
5761 Attr.getRange(), S.Context, Args.data(), Args.size(),
5762 Attr.getAttributeSpellingListIndex()));
Aaron Ballman9e9d1842014-02-21 21:05:14 +00005763}
5764
Aaron Ballmanefe348e2014-02-18 17:36:50 +00005765static void handleRequiresCapabilityAttr(Sema &S, Decl *D,
5766 const AttributeList &Attr) {
5767 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
5768 return;
5769
5770 // check that all arguments are lockable objects
5771 SmallVector<Expr*, 1> Args;
Aaron Ballman69e6e7c2014-03-24 19:29:19 +00005772 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
Aaron Ballmanefe348e2014-02-18 17:36:50 +00005773 if (Args.empty())
5774 return;
5775
5776 RequiresCapabilityAttr *RCA = ::new (S.Context)
5777 RequiresCapabilityAttr(Attr.getRange(), S.Context, Args.data(),
5778 Args.size(), Attr.getAttributeSpellingListIndex());
5779
5780 D->addAttr(RCA);
5781}
5782
Aaron Ballman43f40102014-11-14 22:34:56 +00005783static void handleDeprecatedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5784 if (auto *NSD = dyn_cast<NamespaceDecl>(D)) {
5785 if (NSD->isAnonymousNamespace()) {
5786 S.Diag(Attr.getLoc(), diag::warn_deprecated_anonymous_namespace);
5787 // Do not want to attach the attribute to the namespace because that will
5788 // cause confusing diagnostic reports for uses of declarations within the
5789 // namespace.
5790 return;
5791 }
5792 }
Saleem Abdulrasoolf931a382015-02-16 22:27:01 +00005793
Manman Renc7890fe2016-03-16 18:50:49 +00005794 // Handle the cases where the attribute has a text message.
5795 StringRef Str, Replacement;
5796 if (Attr.isArgExpr(0) && Attr.getArgAsExpr(0) &&
5797 !S.checkStringLiteralArgumentAttr(Attr, 0, Str))
5798 return;
5799
5800 // Only support a single optional message for Declspec and CXX11.
5801 if (Attr.isDeclspecAttribute() || Attr.isCXX11Attribute())
5802 checkAttributeAtMostNumArgs(S, Attr, 1);
5803 else if (Attr.isArgExpr(1) && Attr.getArgAsExpr(1) &&
5804 !S.checkStringLiteralArgumentAttr(Attr, 1, Replacement))
5805 return;
5806
Saleem Abdulrasoolf931a382015-02-16 22:27:01 +00005807 if (!S.getLangOpts().CPlusPlus14)
5808 if (Attr.isCXX11Attribute() &&
5809 !(Attr.hasScope() && Attr.getScopeName()->isStr("gnu")))
Richard Smith4f902c72016-03-08 00:32:55 +00005810 S.Diag(Attr.getLoc(), diag::ext_cxx14_attr) << Attr.getName();
Saleem Abdulrasoolf931a382015-02-16 22:27:01 +00005811
Douglas Katzman3ed0f642016-10-14 19:55:09 +00005812 D->addAttr(::new (S.Context)
5813 DeprecatedAttr(Attr.getRange(), S.Context, Str, Replacement,
5814 Attr.getAttributeSpellingListIndex()));
5815}
5816
5817static bool isGlobalVar(const Decl *D) {
5818 if (const auto *S = dyn_cast<VarDecl>(D))
5819 return S->hasGlobalStorage();
5820 return false;
Aaron Ballman43f40102014-11-14 22:34:56 +00005821}
5822
Peter Collingbourne915df992015-05-15 18:33:32 +00005823static void handleNoSanitizeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5824 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
5825 return;
5826
Benjamin Kramer1b582012016-02-13 18:11:49 +00005827 std::vector<StringRef> Sanitizers;
Peter Collingbourne915df992015-05-15 18:33:32 +00005828
5829 for (unsigned I = 0, E = Attr.getNumArgs(); I != E; ++I) {
5830 StringRef SanitizerName;
5831 SourceLocation LiteralLoc;
5832
5833 if (!S.checkStringLiteralArgumentAttr(Attr, I, SanitizerName, &LiteralLoc))
5834 return;
5835
5836 if (parseSanitizerValue(SanitizerName, /*AllowGroups=*/true) == 0)
5837 S.Diag(LiteralLoc, diag::warn_unknown_sanitizer_ignored) << SanitizerName;
Douglas Katzman3ed0f642016-10-14 19:55:09 +00005838 else if (isGlobalVar(D) && SanitizerName != "address")
5839 S.Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
5840 << Attr.getName() << ExpectedFunctionOrMethod;
Peter Collingbourne915df992015-05-15 18:33:32 +00005841 Sanitizers.push_back(SanitizerName);
5842 }
5843
5844 D->addAttr(::new (S.Context) NoSanitizeAttr(
5845 Attr.getRange(), S.Context, Sanitizers.data(), Sanitizers.size(),
5846 Attr.getAttributeSpellingListIndex()));
5847}
5848
5849static void handleNoSanitizeSpecificAttr(Sema &S, Decl *D,
5850 const AttributeList &Attr) {
Aaron Ballman8b5e7ba2015-10-08 19:24:08 +00005851 StringRef AttrName = Attr.getName()->getName();
5852 normalizeName(AttrName);
Douglas Katzman3ed0f642016-10-14 19:55:09 +00005853 StringRef SanitizerName = llvm::StringSwitch<StringRef>(AttrName)
5854 .Case("no_address_safety_analysis", "address")
5855 .Case("no_sanitize_address", "address")
5856 .Case("no_sanitize_thread", "thread")
5857 .Case("no_sanitize_memory", "memory");
5858 if (isGlobalVar(D) && SanitizerName != "address")
5859 S.Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
5860 << Attr.getName() << ExpectedFunction;
Peter Collingbourne915df992015-05-15 18:33:32 +00005861 D->addAttr(::new (S.Context)
5862 NoSanitizeAttr(Attr.getRange(), S.Context, &SanitizerName, 1,
5863 Attr.getAttributeSpellingListIndex()));
5864}
5865
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00005866static void handleInternalLinkageAttr(Sema &S, Decl *D,
5867 const AttributeList &Attr) {
5868 if (InternalLinkageAttr *Internal =
5869 S.mergeInternalLinkageAttr(D, Attr.getRange(), Attr.getName(),
5870 Attr.getAttributeSpellingListIndex()))
5871 D->addAttr(Internal);
5872}
5873
Anastasia Stulovac4bb5df2016-03-31 11:07:22 +00005874static void handleOpenCLNoSVMAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5875 if (S.LangOpts.OpenCLVersion != 200)
5876 S.Diag(Attr.getLoc(), diag::err_attribute_requires_opencl_version)
5877 << Attr.getName() << "2.0" << 0;
5878 else
5879 S.Diag(Attr.getLoc(), diag::warn_opencl_attr_deprecated_ignored)
5880 << Attr.getName() << "2.0";
5881}
5882
Aaron Ballman8ee40b72013-09-09 23:33:17 +00005883/// Handles semantic checking for features that are common to all attributes,
5884/// such as checking whether a parameter was properly specified, or the correct
5885/// number of arguments were passed, etc.
5886static bool handleCommonAttributeFeatures(Sema &S, Scope *scope, Decl *D,
5887 const AttributeList &Attr) {
5888 // Several attributes carry different semantics than the parsing requires, so
Alex Lorenz24952fb2017-04-19 15:52:11 +00005889 // those are opted out of the common argument checks.
Aaron Ballman8ee40b72013-09-09 23:33:17 +00005890 //
5891 // We also bail on unknown and ignored attributes because those are handled
5892 // as part of the target-specific handling logic.
Alex Lorenz24952fb2017-04-19 15:52:11 +00005893 if (Attr.getKind() == AttributeList::UnknownAttribute)
Aaron Ballman8ee40b72013-09-09 23:33:17 +00005894 return false;
Aaron Ballman3aff6332013-12-02 19:30:36 +00005895 // Check whether the attribute requires specific language extensions to be
5896 // enabled.
5897 if (!Attr.diagnoseLangOpts(S))
5898 return true;
Alex Lorenz24952fb2017-04-19 15:52:11 +00005899 // Check whether the attribute appertains to the given subject.
5900 if (!Attr.diagnoseAppertainsTo(S, D))
5901 return true;
5902 if (Attr.hasCustomParsing())
5903 return false;
Aaron Ballman3aff6332013-12-02 19:30:36 +00005904
Aaron Ballman8ed8dbd2014-07-31 16:37:04 +00005905 if (Attr.getMinArgs() == Attr.getMaxArgs()) {
5906 // If there are no optional arguments, then checking for the argument count
5907 // is trivial.
5908 if (!checkAttributeNumArgs(S, Attr, Attr.getMinArgs()))
5909 return true;
5910 } else {
5911 // There are optional arguments, so checking is slightly more involved.
5912 if (Attr.getMinArgs() &&
5913 !checkAttributeAtLeastNumArgs(S, Attr, Attr.getMinArgs()))
5914 return true;
5915 else if (!Attr.hasVariadicArg() && Attr.getMaxArgs() &&
5916 !checkAttributeAtMostNumArgs(S, Attr, Attr.getMaxArgs()))
5917 return true;
5918 }
Aaron Ballman74eeeae2013-11-27 13:27:02 +00005919
Aaron Ballman8ee40b72013-09-09 23:33:17 +00005920 return false;
5921}
5922
Xiuli Pan11e13f62016-02-26 03:13:03 +00005923static void handleOpenCLAccessAttr(Sema &S, Decl *D,
5924 const AttributeList &Attr) {
5925 if (D->isInvalidDecl())
5926 return;
5927
5928 // Check if there is only one access qualifier.
5929 if (D->hasAttr<OpenCLAccessAttr>()) {
5930 S.Diag(Attr.getLoc(), diag::err_opencl_multiple_access_qualifiers)
5931 << D->getSourceRange();
5932 D->setInvalidDecl(true);
5933 return;
5934 }
5935
5936 // OpenCL v2.0 s6.6 - read_write can be used for image types to specify that an
5937 // image object can be read and written.
5938 // OpenCL v2.0 s6.13.6 - A kernel cannot read from and write to the same pipe
5939 // object. Using the read_write (or __read_write) qualifier with the pipe
5940 // qualifier is a compilation error.
5941 if (const ParmVarDecl *PDecl = dyn_cast<ParmVarDecl>(D)) {
5942 const Type *DeclTy = PDecl->getType().getCanonicalType().getTypePtr();
5943 if (Attr.getName()->getName().find("read_write") != StringRef::npos) {
5944 if (S.getLangOpts().OpenCLVersion < 200 || DeclTy->isPipeType()) {
5945 S.Diag(Attr.getLoc(), diag::err_opencl_invalid_read_write)
5946 << Attr.getName() << PDecl->getType() << DeclTy->isImageType();
5947 D->setInvalidDecl(true);
5948 return;
5949 }
5950 }
5951 }
5952
5953 D->addAttr(::new (S.Context) OpenCLAccessAttr(
5954 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
5955}
5956
Ted Kremenek9ecdfaf2009-05-09 02:44:38 +00005957//===----------------------------------------------------------------------===//
Chris Lattner9e2aafe2008-06-29 00:23:49 +00005958// Top Level Sema Entry Points
5959//===----------------------------------------------------------------------===//
5960
Richard Smithf8a75c32013-08-29 00:47:48 +00005961/// ProcessDeclAttribute - Apply the specific attribute to the specified decl if
5962/// the attribute applies to decls. If the attribute is a type attribute, just
5963/// silently ignore it if a GNU attribute.
5964static void ProcessDeclAttribute(Sema &S, Scope *scope, Decl *D,
5965 const AttributeList &Attr,
5966 bool IncludeCXX11Attributes) {
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005967 if (Attr.isInvalid() || Attr.getKind() == AttributeList::IgnoredAttribute)
Richard Smithf8a75c32013-08-29 00:47:48 +00005968 return;
Abramo Bagnara50099372010-04-30 13:10:51 +00005969
Richard Smithf8a75c32013-08-29 00:47:48 +00005970 // Ignore C++11 attributes on declarator chunks: they appertain to the type
5971 // instead.
5972 if (Attr.isCXX11Attribute() && !IncludeCXX11Attributes)
5973 return;
5974
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005975 // Unknown attributes are automatically warned on. Target-specific attributes
5976 // which do not apply to the current target architecture are treated as
5977 // though they were unknown attributes.
5978 if (Attr.getKind() == AttributeList::UnknownAttribute ||
Bob Wilson7c730832015-07-20 22:57:31 +00005979 !Attr.existsInTarget(S.Context.getTargetInfo())) {
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005980 S.Diag(Attr.getLoc(), Attr.isDeclspecAttribute()
5981 ? diag::warn_unhandled_ms_attribute_ignored
5982 : diag::warn_unknown_attribute_ignored)
5983 << Attr.getName();
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005984 return;
5985 }
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005986
Aaron Ballman8ee40b72013-09-09 23:33:17 +00005987 if (handleCommonAttributeFeatures(S, scope, D, Attr))
5988 return;
5989
Chris Lattnerb632a6e2008-06-29 00:43:07 +00005990 switch (Attr.getKind()) {
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005991 default:
Richard Smith4f902c72016-03-08 00:32:55 +00005992 if (!Attr.isStmtAttr()) {
5993 // Type attributes are handled elsewhere; silently move on.
5994 assert(Attr.isTypeAttr() && "Non-type attribute not handled");
5995 break;
5996 }
5997 S.Diag(Attr.getLoc(), diag::err_stmt_attribute_invalid_on_decl)
5998 << Attr.getName() << D->getLocation();
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005999 break;
Aaron Ballmanab7691c2014-01-09 22:48:32 +00006000 case AttributeList::AT_Interrupt:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006001 handleInterruptAttr(S, D, Attr);
6002 break;
Aaron Ballmanab7691c2014-01-09 22:48:32 +00006003 case AttributeList::AT_X86ForceAlignArgPointer:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006004 handleX86ForceAlignArgPointerAttr(S, D, Attr);
6005 break;
Aaron Ballmanab7691c2014-01-09 22:48:32 +00006006 case AttributeList::AT_DLLExport:
Aaron Ballmanab7691c2014-01-09 22:48:32 +00006007 case AttributeList::AT_DLLImport:
Hans Wennborge82f19c2014-06-24 23:57:05 +00006008 handleDLLAttr(S, D, Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006009 break;
Aaron Ballmanab7691c2014-01-09 22:48:32 +00006010 case AttributeList::AT_Mips16:
Simon Atanasyan2c87f532017-05-22 12:47:43 +00006011 handleSimpleAttributeWithExclusions<Mips16Attr, MicroMipsAttr,
6012 MipsInterruptAttr>(S, D, Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006013 break;
Aaron Ballmanab7691c2014-01-09 22:48:32 +00006014 case AttributeList::AT_NoMips16:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006015 handleSimpleAttribute<NoMips16Attr>(S, D, Attr);
6016 break;
Simon Atanasyan2c87f532017-05-22 12:47:43 +00006017 case AttributeList::AT_MicroMips:
6018 handleSimpleAttributeWithExclusions<MicroMipsAttr, Mips16Attr>(S, D, Attr);
6019 break;
6020 case AttributeList::AT_NoMicroMips:
6021 handleSimpleAttribute<NoMicroMipsAttr>(S, D, Attr);
6022 break;
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006023 case AttributeList::AT_MipsLongCall:
6024 handleSimpleAttributeWithExclusions<MipsLongCallAttr, MipsShortCallAttr>(
6025 S, D, Attr);
6026 break;
6027 case AttributeList::AT_MipsShortCall:
6028 handleSimpleAttributeWithExclusions<MipsShortCallAttr, MipsLongCallAttr>(
6029 S, D, Attr);
6030 break;
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00006031 case AttributeList::AT_AMDGPUFlatWorkGroupSize:
6032 handleAMDGPUFlatWorkGroupSizeAttr(S, D, Attr);
6033 break;
6034 case AttributeList::AT_AMDGPUWavesPerEU:
6035 handleAMDGPUWavesPerEUAttr(S, D, Attr);
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006036 break;
6037 case AttributeList::AT_AMDGPUNumSGPR:
6038 handleAMDGPUNumSGPRAttr(S, D, Attr);
6039 break;
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00006040 case AttributeList::AT_AMDGPUNumVGPR:
6041 handleAMDGPUNumVGPRAttr(S, D, Attr);
6042 break;
Dylan McKaye8232d72017-02-08 05:09:26 +00006043 case AttributeList::AT_AVRSignal:
6044 handleAVRSignalAttr(S, D, Attr);
6045 break;
Aaron Ballman9beb5172013-12-02 15:13:14 +00006046 case AttributeList::AT_IBAction:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006047 handleSimpleAttribute<IBActionAttr>(S, D, Attr);
6048 break;
6049 case AttributeList::AT_IBOutlet:
6050 handleIBOutlet(S, D, Attr);
6051 break;
Richard Smith10876ef2013-01-17 01:30:42 +00006052 case AttributeList::AT_IBOutletCollection:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006053 handleIBOutletCollection(S, D, Attr);
6054 break;
Dmitry Polukhin85eda122016-04-11 07:48:59 +00006055 case AttributeList::AT_IFunc:
6056 handleIFuncAttr(S, D, Attr);
6057 break;
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006058 case AttributeList::AT_Alias:
6059 handleAliasAttr(S, D, Attr);
6060 break;
6061 case AttributeList::AT_Aligned:
6062 handleAlignedAttr(S, D, Attr);
6063 break;
Hal Finkel1b0d24e2014-10-02 21:21:25 +00006064 case AttributeList::AT_AlignValue:
6065 handleAlignValueAttr(S, D, Attr);
6066 break;
George Burgess IVe3763372016-12-22 02:50:20 +00006067 case AttributeList::AT_AllocSize:
6068 handleAllocSizeAttr(S, D, Attr);
6069 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006070 case AttributeList::AT_AlwaysInline:
Paul Robinsonf0674352014-03-31 22:29:15 +00006071 handleAlwaysInlineAttr(S, D, Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006072 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006073 case AttributeList::AT_AnalyzerNoReturn:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006074 handleAnalyzerNoReturnAttr(S, D, Attr);
6075 break;
6076 case AttributeList::AT_TLSModel:
6077 handleTLSModelAttr(S, D, Attr);
6078 break;
6079 case AttributeList::AT_Annotate:
6080 handleAnnotateAttr(S, D, Attr);
6081 break;
6082 case AttributeList::AT_Availability:
6083 handleAvailabilityAttr(S, D, Attr);
6084 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006085 case AttributeList::AT_CarriesDependency:
Richard Smithe233fbf2013-01-28 22:42:45 +00006086 handleDependencyAttr(S, scope, D, Attr);
6087 break;
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006088 case AttributeList::AT_Common:
6089 handleCommonAttr(S, D, Attr);
6090 break;
Aaron Ballman3aff6332013-12-02 19:30:36 +00006091 case AttributeList::AT_CUDAConstant:
Justin Lebare71b2fa2016-09-30 23:57:34 +00006092 handleConstantAttr(S, D, Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006093 break;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00006094 case AttributeList::AT_PassObjectSize:
6095 handlePassObjectSizeAttr(S, D, Attr);
6096 break;
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006097 case AttributeList::AT_Constructor:
6098 handleConstructorAttr(S, D, Attr);
6099 break;
Richard Smith10876ef2013-01-17 01:30:42 +00006100 case AttributeList::AT_CXX11NoReturn:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006101 handleSimpleAttribute<CXX11NoReturnAttr>(S, D, Attr);
6102 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006103 case AttributeList::AT_Deprecated:
Aaron Ballman43f40102014-11-14 22:34:56 +00006104 handleDeprecatedAttr(S, D, Attr);
Benjamin Kramerf435ab42012-05-16 12:19:08 +00006105 break;
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006106 case AttributeList::AT_Destructor:
6107 handleDestructorAttr(S, D, Attr);
6108 break;
6109 case AttributeList::AT_EnableIf:
6110 handleEnableIfAttr(S, D, Attr);
6111 break;
George Burgess IV177399e2017-01-09 04:12:14 +00006112 case AttributeList::AT_DiagnoseIf:
6113 handleDiagnoseIfAttr(S, D, Attr);
6114 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006115 case AttributeList::AT_ExtVectorType:
Chandler Carruthedc2c642011-07-02 00:01:44 +00006116 handleExtVectorTypeAttr(S, scope, D, Attr);
Chris Lattnerb632a6e2008-06-29 00:43:07 +00006117 break;
Alex Lorenzd5d27e12017-03-01 18:06:25 +00006118 case AttributeList::AT_ExternalSourceSymbol:
6119 handleExternalSourceSymbolAttr(S, D, Attr);
6120 break;
Quentin Colombet4e172062012-11-01 23:55:47 +00006121 case AttributeList::AT_MinSize:
Paul Robinsonaae2fba2014-12-10 23:34:36 +00006122 handleMinSizeAttr(S, D, Attr);
Quentin Colombet4e172062012-11-01 23:55:47 +00006123 break;
Paul Robinsonf0674352014-03-31 22:29:15 +00006124 case AttributeList::AT_OptimizeNone:
6125 handleOptimizeNoneAttr(S, D, Attr);
6126 break;
Alexis Hunt724f14e2014-11-28 00:53:20 +00006127 case AttributeList::AT_FlagEnum:
6128 handleSimpleAttribute<FlagEnumAttr>(S, D, Attr);
6129 break;
Akira Hatanaka3c268af2017-03-21 02:23:00 +00006130 case AttributeList::AT_EnumExtensibility:
6131 handleEnumExtensibilityAttr(S, D, Attr);
6132 break;
Peter Collingbourne41af7c22014-05-20 17:12:51 +00006133 case AttributeList::AT_Flatten:
6134 handleSimpleAttribute<FlattenAttr>(S, D, Attr);
6135 break;
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006136 case AttributeList::AT_Format:
6137 handleFormatAttr(S, D, Attr);
6138 break;
6139 case AttributeList::AT_FormatArg:
6140 handleFormatArgAttr(S, D, Attr);
6141 break;
6142 case AttributeList::AT_CUDAGlobal:
6143 handleGlobalAttr(S, D, Attr);
6144 break;
Aaron Ballmanf79ee272013-12-02 21:09:08 +00006145 case AttributeList::AT_CUDADevice:
Justin Lebar3eaaf862016-01-13 01:07:35 +00006146 handleSimpleAttributeWithExclusions<CUDADeviceAttr, CUDAGlobalAttr>(S, D,
6147 Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006148 break;
Aaron Ballman3aff6332013-12-02 19:30:36 +00006149 case AttributeList::AT_CUDAHost:
Justin Lebar3eaaf862016-01-13 01:07:35 +00006150 handleSimpleAttributeWithExclusions<CUDAHostAttr, CUDAGlobalAttr>(S, D,
6151 Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006152 break;
6153 case AttributeList::AT_GNUInline:
6154 handleGNUInlineAttr(S, D, Attr);
6155 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006156 case AttributeList::AT_CUDALaunchBounds:
Chandler Carruthedc2c642011-07-02 00:01:44 +00006157 handleLaunchBoundsAttr(S, D, Attr);
Peter Collingbourne827301e2010-12-12 23:03:07 +00006158 break;
David Majnemer631a90b2015-02-04 07:23:21 +00006159 case AttributeList::AT_Restrict:
6160 handleRestrictAttr(S, D, Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006161 break;
Aaron Ballman6f9165a2013-11-27 15:24:06 +00006162 case AttributeList::AT_MayAlias:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006163 handleSimpleAttribute<MayAliasAttr>(S, D, Attr);
6164 break;
6165 case AttributeList::AT_Mode:
6166 handleModeAttr(S, D, Attr);
6167 break;
David Majnemer1bf0f8e2015-07-20 22:51:52 +00006168 case AttributeList::AT_NoAlias:
6169 handleSimpleAttribute<NoAliasAttr>(S, D, Attr);
6170 break;
Aaron Ballman6f9165a2013-11-27 15:24:06 +00006171 case AttributeList::AT_NoCommon:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006172 handleSimpleAttribute<NoCommonAttr>(S, D, Attr);
6173 break;
Peter Collingbourneb4728c12014-05-19 22:14:34 +00006174 case AttributeList::AT_NoSplitStack:
6175 handleSimpleAttribute<NoSplitStackAttr>(S, D, Attr);
6176 break;
Ted Kremenek9aedc152014-01-17 06:24:56 +00006177 case AttributeList::AT_NonNull:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006178 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(D))
6179 handleNonNullAttrParameter(S, PVD, Attr);
6180 else
6181 handleNonNullAttr(S, D, Attr);
6182 break;
Aaron Ballmanfc1951c2014-01-20 14:19:44 +00006183 case AttributeList::AT_ReturnsNonNull:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006184 handleReturnsNonNullAttr(S, D, Attr);
6185 break;
Akira Hatanaka98a49332017-09-22 00:41:05 +00006186 case AttributeList::AT_NoEscape:
6187 handleNoEscapeAttr(S, D, Attr);
6188 break;
Hal Finkelee90a222014-09-26 05:04:30 +00006189 case AttributeList::AT_AssumeAligned:
6190 handleAssumeAlignedAttr(S, D, Attr);
6191 break;
Erich Keane623efd82017-03-30 21:48:55 +00006192 case AttributeList::AT_AllocAlign:
6193 handleAllocAlignAttr(S, D, Attr);
6194 break;
Aaron Ballman6f9165a2013-11-27 15:24:06 +00006195 case AttributeList::AT_Overloadable:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006196 handleSimpleAttribute<OverloadableAttr>(S, D, Attr);
6197 break;
6198 case AttributeList::AT_Ownership:
6199 handleOwnershipAttr(S, D, Attr);
6200 break;
6201 case AttributeList::AT_Cold:
6202 handleColdAttr(S, D, Attr);
6203 break;
6204 case AttributeList::AT_Hot:
6205 handleHotAttr(S, D, Attr);
6206 break;
Aaron Ballman6f9165a2013-11-27 15:24:06 +00006207 case AttributeList::AT_Naked:
Charles Davis0e379112016-08-08 21:19:08 +00006208 handleNakedAttr(S, D, Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006209 break;
6210 case AttributeList::AT_NoReturn:
6211 handleNoReturnAttr(S, D, Attr);
6212 break;
Aaron Ballmanbf7b1ee2013-12-21 16:49:29 +00006213 case AttributeList::AT_NoThrow:
Reid Klecknera3fe27f2017-10-02 17:16:14 +00006214 handleSimpleAttribute<NoThrowAttr>(S, D, Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006215 break;
Aaron Ballman3aff6332013-12-02 19:30:36 +00006216 case AttributeList::AT_CUDAShared:
Justin Lebar10411012016-09-30 23:57:30 +00006217 handleSharedAttr(S, D, Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006218 break;
6219 case AttributeList::AT_VecReturn:
6220 handleVecReturnAttr(S, D, Attr);
6221 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006222 case AttributeList::AT_ObjCOwnership:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006223 handleObjCOwnershipAttr(S, D, Attr);
6224 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006225 case AttributeList::AT_ObjCPreciseLifetime:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006226 handleObjCPreciseLifetimeAttr(S, D, Attr);
6227 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006228 case AttributeList::AT_ObjCReturnsInnerPointer:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006229 handleObjCReturnsInnerPointerAttr(S, D, Attr);
6230 break;
Fariborz Jahanian566fff02012-09-07 23:46:23 +00006231 case AttributeList::AT_ObjCRequiresSuper:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006232 handleObjCRequiresSuperAttr(S, D, Attr);
6233 break;
Fariborz Jahanian0a0a3972013-11-13 23:59:17 +00006234 case AttributeList::AT_ObjCBridge:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006235 handleObjCBridgeAttr(S, scope, D, Attr);
6236 break;
Fariborz Jahanian87c77912013-11-21 20:50:32 +00006237 case AttributeList::AT_ObjCBridgeMutable:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006238 handleObjCBridgeMutableAttr(S, scope, D, Attr);
6239 break;
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00006240 case AttributeList::AT_ObjCBridgeRelated:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006241 handleObjCBridgeRelatedAttr(S, scope, D, Attr);
6242 break;
Argyrios Kyrtzidisd1438b42013-12-03 21:11:25 +00006243 case AttributeList::AT_ObjCDesignatedInitializer:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006244 handleObjCDesignatedInitializer(S, D, Attr);
6245 break;
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006246 case AttributeList::AT_ObjCRuntimeName:
6247 handleObjCRuntimeName(S, D, Attr);
6248 break;
Douglas Gregor24ae22c2016-04-01 23:23:52 +00006249 case AttributeList::AT_ObjCRuntimeVisible:
6250 handleSimpleAttribute<ObjCRuntimeVisibleAttr>(S, D, Attr);
6251 break;
Alex Denisovfde64952015-06-26 05:28:36 +00006252 case AttributeList::AT_ObjCBoxable:
6253 handleObjCBoxable(S, D, Attr);
6254 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006255 case AttributeList::AT_CFAuditedTransfer:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006256 handleCFAuditedTransferAttr(S, D, Attr);
6257 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006258 case AttributeList::AT_CFUnknownTransfer:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006259 handleCFUnknownTransferAttr(S, D, Attr);
6260 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006261 case AttributeList::AT_CFConsumed:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006262 case AttributeList::AT_NSConsumed:
6263 handleNSConsumedAttr(S, D, Attr);
6264 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006265 case AttributeList::AT_NSConsumesSelf:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006266 handleSimpleAttribute<NSConsumesSelfAttr>(S, D, Attr);
6267 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006268 case AttributeList::AT_NSReturnsAutoreleased:
6269 case AttributeList::AT_NSReturnsNotRetained:
6270 case AttributeList::AT_CFReturnsNotRetained:
6271 case AttributeList::AT_NSReturnsRetained:
6272 case AttributeList::AT_CFReturnsRetained:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006273 handleNSReturnsRetainedAttr(S, D, Attr);
6274 break;
Tanya Lattnerbcffcdf2012-07-09 22:06:01 +00006275 case AttributeList::AT_WorkGroupSizeHint:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006276 handleWorkGroupSize<WorkGroupSizeHintAttr>(S, D, Attr);
6277 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006278 case AttributeList::AT_ReqdWorkGroupSize:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006279 handleWorkGroupSize<ReqdWorkGroupSizeAttr>(S, D, Attr);
6280 break;
Xiuli Panbe6da4b2017-05-04 07:31:20 +00006281 case AttributeList::AT_OpenCLIntelReqdSubGroupSize:
6282 handleSubGroupSize(S, D, Attr);
6283 break;
Joey Goulyaba589c2013-03-08 09:42:32 +00006284 case AttributeList::AT_VecTypeHint:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006285 handleVecTypeHint(S, D, Attr);
6286 break;
Eric Fiselier341e8252016-09-02 18:53:31 +00006287 case AttributeList::AT_RequireConstantInit:
6288 handleSimpleAttribute<RequireConstantInitAttr>(S, D, Attr);
6289 break;
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006290 case AttributeList::AT_InitPriority:
6291 handleInitPriorityAttr(S, D, Attr);
6292 break;
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006293 case AttributeList::AT_Packed:
6294 handlePackedAttr(S, D, Attr);
6295 break;
6296 case AttributeList::AT_Section:
6297 handleSectionAttr(S, D, Attr);
6298 break;
Eric Christopher11acf732015-06-12 01:35:52 +00006299 case AttributeList::AT_Target:
6300 handleTargetAttr(S, D, Attr);
6301 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006302 case AttributeList::AT_Unavailable:
Aaron Ballman8b8ebdd2013-07-18 13:13:52 +00006303 handleAttrWithMessage<UnavailableAttr>(S, D, Attr);
Benjamin Kramerf435ab42012-05-16 12:19:08 +00006304 break;
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006305 case AttributeList::AT_ArcWeakrefUnavailable:
6306 handleSimpleAttribute<ArcWeakrefUnavailableAttr>(S, D, Attr);
6307 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006308 case AttributeList::AT_ObjCRootClass:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006309 handleSimpleAttribute<ObjCRootClassAttr>(S, D, Attr);
6310 break;
Alex Lorenza8c44ba2016-10-28 10:25:10 +00006311 case AttributeList::AT_ObjCSubclassingRestricted:
6312 handleSimpleAttribute<ObjCSubclassingRestrictedAttr>(S, D, Attr);
6313 break;
Ted Kremenekf41cf7f12013-12-10 19:43:48 +00006314 case AttributeList::AT_ObjCExplicitProtocolImpl:
Ted Kremenek438f8db2014-02-22 01:06:05 +00006315 handleObjCSuppresProtocolAttr(S, D, Attr);
Ted Kremenek28eace62013-11-23 01:01:34 +00006316 break;
6317 case AttributeList::AT_ObjCRequiresPropertyDefs:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006318 handleSimpleAttribute<ObjCRequiresPropertyDefsAttr>(S, D, Attr);
6319 break;
Aaron Ballman12b9f652014-01-16 13:55:42 +00006320 case AttributeList::AT_Unused:
Aaron Ballman0bcd6c12016-03-09 16:48:08 +00006321 handleUnusedAttr(S, D, Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006322 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006323 case AttributeList::AT_ReturnsTwice:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006324 handleSimpleAttribute<ReturnsTwiceAttr>(S, D, Attr);
6325 break;
Akira Hatanakac8667622015-11-06 23:56:15 +00006326 case AttributeList::AT_NotTailCalled:
6327 handleNotTailCalledAttr(S, D, Attr);
6328 break;
Akira Hatanaka7828b1e2015-11-13 00:42:21 +00006329 case AttributeList::AT_DisableTailCalls:
6330 handleDisableTailCallsAttr(S, D, Attr);
6331 break;
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006332 case AttributeList::AT_Used:
6333 handleUsedAttr(S, D, Attr);
6334 break;
John McCalld041a9b2013-02-20 01:54:26 +00006335 case AttributeList::AT_Visibility:
6336 handleVisibilityAttr(S, D, Attr, false);
6337 break;
6338 case AttributeList::AT_TypeVisibility:
6339 handleVisibilityAttr(S, D, Attr, true);
6340 break;
Lubos Lunakedc13882013-07-20 15:05:36 +00006341 case AttributeList::AT_WarnUnused:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006342 handleSimpleAttribute<WarnUnusedAttr>(S, D, Attr);
6343 break;
6344 case AttributeList::AT_WarnUnusedResult:
6345 handleWarnUnusedResult(S, D, Attr);
Chris Lattner237f2752009-02-14 07:37:35 +00006346 break;
Aaron Ballman604dfec2013-12-02 17:07:07 +00006347 case AttributeList::AT_Weak:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006348 handleSimpleAttribute<WeakAttr>(S, D, Attr);
6349 break;
6350 case AttributeList::AT_WeakRef:
6351 handleWeakRefAttr(S, D, Attr);
6352 break;
6353 case AttributeList::AT_WeakImport:
6354 handleWeakImportAttr(S, D, Attr);
6355 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006356 case AttributeList::AT_TransparentUnion:
Chandler Carruthedc2c642011-07-02 00:01:44 +00006357 handleTransparentUnionAttr(S, D, Attr);
Chris Lattnerb632a6e2008-06-29 00:43:07 +00006358 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006359 case AttributeList::AT_ObjCException:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006360 handleSimpleAttribute<ObjCExceptionAttr>(S, D, Attr);
6361 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006362 case AttributeList::AT_ObjCMethodFamily:
Chandler Carruthedc2c642011-07-02 00:01:44 +00006363 handleObjCMethodFamilyAttr(S, D, Attr);
John McCall86bc21f2011-03-02 11:33:24 +00006364 break;
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006365 case AttributeList::AT_ObjCNSObject:
6366 handleObjCNSObject(S, D, Attr);
6367 break;
Fariborz Jahanian7a60b6d2015-04-16 18:38:44 +00006368 case AttributeList::AT_ObjCIndependentClass:
6369 handleObjCIndependentClass(S, D, Attr);
6370 break;
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006371 case AttributeList::AT_Blocks:
6372 handleBlocksAttr(S, D, Attr);
6373 break;
6374 case AttributeList::AT_Sentinel:
6375 handleSentinelAttr(S, D, Attr);
6376 break;
Aaron Ballmanbf7b1ee2013-12-21 16:49:29 +00006377 case AttributeList::AT_Const:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006378 handleSimpleAttribute<ConstAttr>(S, D, Attr);
6379 break;
Aaron Ballman6f9165a2013-11-27 15:24:06 +00006380 case AttributeList::AT_Pure:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006381 handleSimpleAttribute<PureAttr>(S, D, Attr);
6382 break;
6383 case AttributeList::AT_Cleanup:
6384 handleCleanupAttr(S, D, Attr);
6385 break;
6386 case AttributeList::AT_NoDebug:
6387 handleNoDebugAttr(S, D, Attr);
6388 break;
Aaron Ballman7c19ab12014-02-22 16:59:24 +00006389 case AttributeList::AT_NoDuplicate:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006390 handleSimpleAttribute<NoDuplicateAttr>(S, D, Attr);
6391 break;
Yaxun Liu7d07ae72016-11-01 18:45:32 +00006392 case AttributeList::AT_Convergent:
6393 handleSimpleAttribute<ConvergentAttr>(S, D, Attr);
6394 break;
Aaron Ballman6f9165a2013-11-27 15:24:06 +00006395 case AttributeList::AT_NoInline:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006396 handleSimpleAttribute<NoInlineAttr>(S, D, Attr);
6397 break;
6398 case AttributeList::AT_NoInstrumentFunction: // Interacts with -pg.
6399 handleSimpleAttribute<NoInstrumentFunctionAttr>(S, D, Attr);
6400 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006401 case AttributeList::AT_StdCall:
6402 case AttributeList::AT_CDecl:
6403 case AttributeList::AT_FastCall:
6404 case AttributeList::AT_ThisCall:
6405 case AttributeList::AT_Pascal:
Erich Keane757d3172016-11-02 18:29:35 +00006406 case AttributeList::AT_RegCall:
John McCall477f2bb2016-03-03 06:39:32 +00006407 case AttributeList::AT_SwiftCall:
Reid Klecknerd7857f02014-10-24 17:42:17 +00006408 case AttributeList::AT_VectorCall:
Charles Davisb5a214e2013-08-30 04:39:01 +00006409 case AttributeList::AT_MSABI:
6410 case AttributeList::AT_SysVABI:
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006411 case AttributeList::AT_Pcs:
Guy Benyeif0a014b2012-12-25 08:53:55 +00006412 case AttributeList::AT_IntelOclBicc:
Roman Levenstein35aa5ce2016-03-16 18:00:46 +00006413 case AttributeList::AT_PreserveMost:
6414 case AttributeList::AT_PreserveAll:
Chandler Carruthedc2c642011-07-02 00:01:44 +00006415 handleCallConvAttr(S, D, Attr);
John McCallab26cfa2010-02-05 21:31:56 +00006416 break;
Matthias Gehre01a63382017-03-27 19:45:24 +00006417 case AttributeList::AT_Suppress:
6418 handleSuppressAttr(S, D, Attr);
6419 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006420 case AttributeList::AT_OpenCLKernel:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006421 handleSimpleAttribute<OpenCLKernelAttr>(S, D, Attr);
6422 break;
Xiuli Pan11e13f62016-02-26 03:13:03 +00006423 case AttributeList::AT_OpenCLAccess:
6424 handleOpenCLAccessAttr(S, D, Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006425 break;
Anastasia Stulovafde76222016-04-01 16:05:09 +00006426 case AttributeList::AT_OpenCLNoSVM:
6427 handleOpenCLNoSVMAttr(S, D, Attr);
6428 break;
John McCall477f2bb2016-03-03 06:39:32 +00006429 case AttributeList::AT_SwiftContext:
6430 handleParameterABIAttr(S, D, Attr, ParameterABI::SwiftContext);
6431 break;
6432 case AttributeList::AT_SwiftErrorResult:
6433 handleParameterABIAttr(S, D, Attr, ParameterABI::SwiftErrorResult);
6434 break;
6435 case AttributeList::AT_SwiftIndirectResult:
6436 handleParameterABIAttr(S, D, Attr, ParameterABI::SwiftIndirectResult);
6437 break;
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00006438 case AttributeList::AT_InternalLinkage:
6439 handleInternalLinkageAttr(S, D, Attr);
6440 break;
Peter Collingbourne3afb2662016-04-28 17:09:37 +00006441 case AttributeList::AT_LTOVisibilityPublic:
6442 handleSimpleAttribute<LTOVisibilityPublicAttr>(S, D, Attr);
6443 break;
John McCall8d32c052012-05-22 21:28:12 +00006444
6445 // Microsoft attributes:
David Majnemercd3ebfe2016-05-23 17:16:12 +00006446 case AttributeList::AT_EmptyBases:
6447 handleSimpleAttribute<EmptyBasesAttr>(S, D, Attr);
6448 break;
6449 case AttributeList::AT_LayoutVersion:
6450 handleLayoutVersion(S, D, Attr);
6451 break;
David Majnemer8ab003a2015-02-02 19:30:52 +00006452 case AttributeList::AT_MSNoVTable:
6453 handleSimpleAttribute<MSNoVTableAttr>(S, D, Attr);
David Majnemer129f4172015-02-02 10:22:20 +00006454 break;
David Majnemer8ab003a2015-02-02 19:30:52 +00006455 case AttributeList::AT_MSStruct:
6456 handleSimpleAttribute<MSStructAttr>(S, D, Attr);
John McCall8d32c052012-05-22 21:28:12 +00006457 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006458 case AttributeList::AT_Uuid:
Chandler Carruthedc2c642011-07-02 00:01:44 +00006459 handleUuidAttr(S, D, Attr);
Francois Picheta83957a2010-12-19 06:50:37 +00006460 break;
Aaron Ballman8edb5c22013-12-18 23:44:18 +00006461 case AttributeList::AT_MSInheritance:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006462 handleMSInheritanceAttr(S, D, Attr);
6463 break;
Reid Klecknerb144d362013-05-20 14:02:37 +00006464 case AttributeList::AT_SelectAny:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006465 handleSimpleAttribute<SelectAnyAttr>(S, D, Attr);
6466 break;
Reid Kleckner7d6d2702014-05-01 03:16:47 +00006467 case AttributeList::AT_Thread:
6468 handleDeclspecThreadAttr(S, D, Attr);
6469 break;
David Majnemercd3ebfe2016-05-23 17:16:12 +00006470
Dmitry Polukhinbf17ecf2016-03-09 15:30:53 +00006471 case AttributeList::AT_AbiTag:
6472 handleAbiTagAttr(S, D, Attr);
6473 break;
Caitlin Sadowskiaac4d212011-07-28 17:21:07 +00006474
6475 // Thread safety attributes:
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00006476 case AttributeList::AT_AssertExclusiveLock:
6477 handleAssertExclusiveLockAttr(S, D, Attr);
6478 break;
6479 case AttributeList::AT_AssertSharedLock:
6480 handleAssertSharedLockAttr(S, D, Attr);
6481 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006482 case AttributeList::AT_GuardedVar:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006483 handleSimpleAttribute<GuardedVarAttr>(S, D, Attr);
6484 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006485 case AttributeList::AT_PtGuardedVar:
Michael Han3be3b442012-07-23 18:48:41 +00006486 handlePtGuardedVarAttr(S, D, Attr);
Caitlin Sadowskiaac4d212011-07-28 17:21:07 +00006487 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006488 case AttributeList::AT_ScopedLockable:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006489 handleSimpleAttribute<ScopedLockableAttr>(S, D, Attr);
6490 break;
Peter Collingbourne915df992015-05-15 18:33:32 +00006491 case AttributeList::AT_NoSanitize:
6492 handleNoSanitizeAttr(S, D, Attr);
6493 break;
6494 case AttributeList::AT_NoSanitizeSpecific:
6495 handleNoSanitizeSpecificAttr(S, D, Attr);
Kostya Serebryany588d6ab2012-01-24 19:25:38 +00006496 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006497 case AttributeList::AT_NoThreadSafetyAnalysis:
Aaron Ballman6f9165a2013-11-27 15:24:06 +00006498 handleSimpleAttribute<NoThreadSafetyAnalysisAttr>(S, D, Attr);
Kostya Serebryany4c0fc992013-02-26 06:58:27 +00006499 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006500 case AttributeList::AT_GuardedBy:
Caitlin Sadowski63fa6672011-07-28 20:12:35 +00006501 handleGuardedByAttr(S, D, Attr);
6502 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006503 case AttributeList::AT_PtGuardedBy:
Michael Han3be3b442012-07-23 18:48:41 +00006504 handlePtGuardedByAttr(S, D, Attr);
Caitlin Sadowski63fa6672011-07-28 20:12:35 +00006505 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006506 case AttributeList::AT_ExclusiveTrylockFunction:
Michael Han3be3b442012-07-23 18:48:41 +00006507 handleExclusiveTrylockFunctionAttr(S, D, Attr);
Caitlin Sadowski63fa6672011-07-28 20:12:35 +00006508 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006509 case AttributeList::AT_LockReturned:
Caitlin Sadowski63fa6672011-07-28 20:12:35 +00006510 handleLockReturnedAttr(S, D, Attr);
6511 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006512 case AttributeList::AT_LocksExcluded:
Caitlin Sadowski63fa6672011-07-28 20:12:35 +00006513 handleLocksExcludedAttr(S, D, Attr);
6514 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006515 case AttributeList::AT_SharedTrylockFunction:
Michael Han3be3b442012-07-23 18:48:41 +00006516 handleSharedTrylockFunctionAttr(S, D, Attr);
Caitlin Sadowski63fa6672011-07-28 20:12:35 +00006517 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006518 case AttributeList::AT_AcquiredBefore:
Michael Han3be3b442012-07-23 18:48:41 +00006519 handleAcquiredBeforeAttr(S, D, Attr);
Caitlin Sadowski63fa6672011-07-28 20:12:35 +00006520 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006521 case AttributeList::AT_AcquiredAfter:
Michael Han3be3b442012-07-23 18:48:41 +00006522 handleAcquiredAfterAttr(S, D, Attr);
Caitlin Sadowski63fa6672011-07-28 20:12:35 +00006523 break;
Caitlin Sadowskiaac4d212011-07-28 17:21:07 +00006524
Aaron Ballmanefe348e2014-02-18 17:36:50 +00006525 // Capability analysis attributes.
6526 case AttributeList::AT_Capability:
6527 case AttributeList::AT_Lockable:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006528 handleCapabilityAttr(S, D, Attr);
6529 break;
Aaron Ballman9e9d1842014-02-21 21:05:14 +00006530 case AttributeList::AT_RequiresCapability:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006531 handleRequiresCapabilityAttr(S, D, Attr);
6532 break;
Aaron Ballman9e9d1842014-02-21 21:05:14 +00006533
6534 case AttributeList::AT_AssertCapability:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006535 handleAssertCapabilityAttr(S, D, Attr);
6536 break;
Aaron Ballman9e9d1842014-02-21 21:05:14 +00006537 case AttributeList::AT_AcquireCapability:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006538 handleAcquireCapabilityAttr(S, D, Attr);
6539 break;
Aaron Ballman9e9d1842014-02-21 21:05:14 +00006540 case AttributeList::AT_ReleaseCapability:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006541 handleReleaseCapabilityAttr(S, D, Attr);
6542 break;
Aaron Ballman9e9d1842014-02-21 21:05:14 +00006543 case AttributeList::AT_TryAcquireCapability:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006544 handleTryAcquireCapabilityAttr(S, D, Attr);
6545 break;
Aaron Ballmanefe348e2014-02-18 17:36:50 +00006546
DeLesley Hutchins8d41d992013-10-11 22:30:48 +00006547 // Consumed analysis attributes.
DeLesley Hutchins5a715c42013-08-30 22:56:34 +00006548 case AttributeList::AT_Consumable:
6549 handleConsumableAttr(S, D, Attr);
6550 break;
DeLesley Hutchinsf28bbec2014-01-14 00:36:53 +00006551 case AttributeList::AT_ConsumableAutoCast:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006552 handleSimpleAttribute<ConsumableAutoCastAttr>(S, D, Attr);
6553 break;
DeLesley Hutchinsf28bbec2014-01-14 00:36:53 +00006554 case AttributeList::AT_ConsumableSetOnRead:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006555 handleSimpleAttribute<ConsumableSetOnReadAttr>(S, D, Attr);
6556 break;
DeLesley Hutchins210791a2013-10-04 21:28:06 +00006557 case AttributeList::AT_CallableWhen:
6558 handleCallableWhenAttr(S, D, Attr);
DeLesley Hutchins48a31762013-08-12 21:20:55 +00006559 break;
DeLesley Hutchins69391772013-10-17 23:23:53 +00006560 case AttributeList::AT_ParamTypestate:
6561 handleParamTypestateAttr(S, D, Attr);
6562 break;
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00006563 case AttributeList::AT_ReturnTypestate:
6564 handleReturnTypestateAttr(S, D, Attr);
6565 break;
DeLesley Hutchins33a29342013-10-11 23:03:26 +00006566 case AttributeList::AT_SetTypestate:
6567 handleSetTypestateAttr(S, D, Attr);
6568 break;
Chris Wailes9385f9f2013-10-29 20:28:41 +00006569 case AttributeList::AT_TestTypestate:
6570 handleTestTypestateAttr(S, D, Attr);
DeLesley Hutchins33a29342013-10-11 23:03:26 +00006571 break;
DeLesley Hutchins48a31762013-08-12 21:20:55 +00006572
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00006573 // Type safety attributes.
6574 case AttributeList::AT_ArgumentWithTypeTag:
6575 handleArgumentWithTypeTagAttr(S, D, Attr);
6576 break;
6577 case AttributeList::AT_TypeTagForDatatype:
6578 handleTypeTagForDatatypeAttr(S, D, Attr);
6579 break;
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +00006580 case AttributeList::AT_AnyX86NoCallerSavedRegisters:
6581 handleNoCallerSavedRegsAttr(S, D, Attr);
6582 break;
Pirama Arumuga Nainare5d2d712016-06-10 21:51:18 +00006583 case AttributeList::AT_RenderScriptKernel:
6584 handleSimpleAttribute<RenderScriptKernelAttr>(S, D, Attr);
Pirama Arumuga Nainar8b788d02016-06-09 23:34:20 +00006585 break;
Aaron Ballman7d2aecb2016-07-13 22:32:15 +00006586 // XRay attributes.
6587 case AttributeList::AT_XRayInstrument:
6588 handleSimpleAttribute<XRayInstrumentAttr>(S, D, Attr);
6589 break;
Dean Michael Berris418da3f2017-03-06 07:08:21 +00006590 case AttributeList::AT_XRayLogArgs:
6591 handleXRayLogArgsAttr(S, D, Attr);
6592 break;
Chris Lattnerb632a6e2008-06-29 00:43:07 +00006593 }
6594}
6595
6596/// ProcessDeclAttributeList - Apply all the decl attributes in the specified
6597/// attribute list to the specified decl, ignoring any type attributes.
Eric Christopherbc638a82010-12-01 22:13:54 +00006598void Sema::ProcessDeclAttributeList(Scope *S, Decl *D,
Peter Collingbourneb331b262011-01-21 02:08:45 +00006599 const AttributeList *AttrList,
Richard Smith10876ef2013-01-17 01:30:42 +00006600 bool IncludeCXX11Attributes) {
6601 for (const AttributeList* l = AttrList; l; l = l->getNext())
Richard Smithf8a75c32013-08-29 00:47:48 +00006602 ProcessDeclAttribute(*this, S, D, *l, IncludeCXX11Attributes);
Rafael Espindolac18086a2010-02-23 22:00:30 +00006603
Joey Gouly2cd9db12013-12-13 16:15:28 +00006604 // FIXME: We should be able to handle these cases in TableGen.
Rafael Espindolac18086a2010-02-23 22:00:30 +00006605 // GCC accepts
6606 // static int a9 __attribute__((weakref));
6607 // but that looks really pointless. We reject it.
Richard Smithf8a75c32013-08-29 00:47:48 +00006608 if (D->hasAttr<WeakRefAttr>() && !D->hasAttr<AliasAttr>()) {
Aaron Ballman9f6fec42014-01-02 23:02:01 +00006609 Diag(AttrList->getLoc(), diag::err_attribute_weakref_without_alias)
6610 << cast<NamedDecl>(D);
Rafael Espindolab3069002013-01-16 23:49:06 +00006611 D->dropAttr<WeakRefAttr>();
Rafael Espindolac18086a2010-02-23 22:00:30 +00006612 return;
Chris Lattnerb632a6e2008-06-29 00:43:07 +00006613 }
Joey Gouly2cd9db12013-12-13 16:15:28 +00006614
Aaron Ballmanbe243a72014-12-04 22:45:31 +00006615 // FIXME: We should be able to handle this in TableGen as well. It would be
6616 // good to have a way to specify "these attributes must appear as a group",
6617 // for these. Additionally, it would be good to have a way to specify "these
6618 // attribute must never appear as a group" for attributes like cold and hot.
Joey Gouly2cd9db12013-12-13 16:15:28 +00006619 if (!D->hasAttr<OpenCLKernelAttr>()) {
6620 // These attributes cannot be applied to a non-kernel function.
Aaron Ballman3e424b52013-12-26 18:30:57 +00006621 if (Attr *A = D->getAttr<ReqdWorkGroupSizeAttr>()) {
Matt Arsenaultb9e9dc52014-12-05 18:03:58 +00006622 // FIXME: This emits a different error message than
6623 // diag::err_attribute_wrong_decl_type + ExpectedKernelFunction.
Aaron Ballman3e424b52013-12-26 18:30:57 +00006624 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
Joey Gouly2cd9db12013-12-13 16:15:28 +00006625 D->setInvalidDecl();
Matt Arsenault43cfcbc2014-12-05 18:03:55 +00006626 } else if (Attr *A = D->getAttr<WorkGroupSizeHintAttr>()) {
Aaron Ballman3e424b52013-12-26 18:30:57 +00006627 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
Joey Gouly2cd9db12013-12-13 16:15:28 +00006628 D->setInvalidDecl();
Matt Arsenault43cfcbc2014-12-05 18:03:55 +00006629 } else if (Attr *A = D->getAttr<VecTypeHintAttr>()) {
Aaron Ballman3e424b52013-12-26 18:30:57 +00006630 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
Joey Gouly2cd9db12013-12-13 16:15:28 +00006631 D->setInvalidDecl();
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00006632 } else if (Attr *A = D->getAttr<AMDGPUFlatWorkGroupSizeAttr>()) {
6633 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
6634 << A << ExpectedKernelFunction;
6635 D->setInvalidDecl();
6636 } else if (Attr *A = D->getAttr<AMDGPUWavesPerEUAttr>()) {
Matt Arsenaultb9e9dc52014-12-05 18:03:58 +00006637 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
6638 << A << ExpectedKernelFunction;
6639 D->setInvalidDecl();
6640 } else if (Attr *A = D->getAttr<AMDGPUNumSGPRAttr>()) {
6641 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
6642 << A << ExpectedKernelFunction;
6643 D->setInvalidDecl();
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00006644 } else if (Attr *A = D->getAttr<AMDGPUNumVGPRAttr>()) {
6645 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
6646 << A << ExpectedKernelFunction;
6647 D->setInvalidDecl();
Xiuli Panbe6da4b2017-05-04 07:31:20 +00006648 } else if (Attr *A = D->getAttr<OpenCLIntelReqdSubGroupSizeAttr>()) {
6649 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
6650 D->setInvalidDecl();
Joey Gouly2cd9db12013-12-13 16:15:28 +00006651 }
6652 }
Chris Lattnerb632a6e2008-06-29 00:43:07 +00006653}
6654
Hiroshi Inoue939d9322017-06-30 05:40:31 +00006655// Helper for delayed processing TransparentUnion attribute.
Erich Keane2fe684b2017-02-28 20:44:39 +00006656void Sema::ProcessDeclAttributeDelayed(Decl *D, const AttributeList *AttrList) {
6657 for (const AttributeList *Attr = AttrList; Attr; Attr = Attr->getNext())
6658 if (Attr->getKind() == AttributeList::AT_TransparentUnion) {
6659 handleTransparentUnionAttr(*this, D, *Attr);
6660 break;
6661 }
6662}
6663
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00006664// Annotation attributes are the only attributes allowed after an access
6665// specifier.
6666bool Sema::ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
6667 const AttributeList *AttrList) {
6668 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006669 if (l->getKind() == AttributeList::AT_Annotate) {
David Majnemer706f3152014-12-14 01:05:01 +00006670 ProcessDeclAttribute(*this, nullptr, ASDecl, *l, l->isCXX11Attribute());
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00006671 } else {
6672 Diag(l->getLoc(), diag::err_only_annotate_after_access_spec);
6673 return true;
6674 }
6675 }
6676
6677 return false;
6678}
6679
John McCall42856de2011-10-01 05:17:03 +00006680/// checkUnusedDeclAttributes - Check a list of attributes to see if it
6681/// contains any decl attributes that we should warn about.
6682static void checkUnusedDeclAttributes(Sema &S, const AttributeList *A) {
6683 for ( ; A; A = A->getNext()) {
6684 // Only warn if the attribute is an unignored, non-type attribute.
Richard Smith810ad3e2013-01-29 10:02:16 +00006685 if (A->isUsedAsTypeAttr() || A->isInvalid()) continue;
John McCall42856de2011-10-01 05:17:03 +00006686 if (A->getKind() == AttributeList::IgnoredAttribute) continue;
6687
6688 if (A->getKind() == AttributeList::UnknownAttribute) {
6689 S.Diag(A->getLoc(), diag::warn_unknown_attribute_ignored)
6690 << A->getName() << A->getRange();
6691 } else {
6692 S.Diag(A->getLoc(), diag::warn_attribute_not_on_decl)
6693 << A->getName() << A->getRange();
6694 }
6695 }
6696}
6697
6698/// checkUnusedDeclAttributes - Given a declarator which is not being
6699/// used to build a declaration, complain about any decl attributes
6700/// which might be lying around on it.
6701void Sema::checkUnusedDeclAttributes(Declarator &D) {
6702 ::checkUnusedDeclAttributes(*this, D.getDeclSpec().getAttributes().getList());
6703 ::checkUnusedDeclAttributes(*this, D.getAttributes());
6704 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i)
6705 ::checkUnusedDeclAttributes(*this, D.getTypeObject(i).getAttrs());
6706}
6707
Ryan Flynn7d470f32009-07-30 03:15:39 +00006708/// DeclClonePragmaWeak - clone existing decl (maybe definition),
James Dennett634962f2012-06-14 21:40:34 +00006709/// \#pragma weak needs a non-definition decl and source may not have one.
Eli Friedmance3e2c82011-09-07 04:05:06 +00006710NamedDecl * Sema::DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
6711 SourceLocation Loc) {
Ryan Flynnd963a492009-07-31 02:52:19 +00006712 assert(isa<FunctionDecl>(ND) || isa<VarDecl>(ND));
Craig Topperc3ec1492014-05-26 06:22:03 +00006713 NamedDecl *NewD = nullptr;
Ryan Flynn7d470f32009-07-30 03:15:39 +00006714 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
Alexander Kornienko061900f2015-12-03 11:37:28 +00006715 FunctionDecl *NewFD;
6716 // FIXME: Missing call to CheckFunctionDeclaration().
Eli Friedmance3e2c82011-09-07 04:05:06 +00006717 // FIXME: Mangling?
6718 // FIXME: Is the qualifier info correct?
6719 // FIXME: Is the DeclContext correct?
Alexander Kornienko061900f2015-12-03 11:37:28 +00006720 NewFD = FunctionDecl::Create(FD->getASTContext(), FD->getDeclContext(),
6721 Loc, Loc, DeclarationName(II),
6722 FD->getType(), FD->getTypeSourceInfo(),
6723 SC_None, false/*isInlineSpecified*/,
6724 FD->hasPrototype(),
6725 false/*isConstexprSpecified*/);
Eli Friedmance3e2c82011-09-07 04:05:06 +00006726 NewD = NewFD;
6727
6728 if (FD->getQualifier())
Douglas Gregor14454802011-02-25 02:25:35 +00006729 NewFD->setQualifierInfo(FD->getQualifierLoc());
Eli Friedmance3e2c82011-09-07 04:05:06 +00006730
6731 // Fake up parameter variables; they are declared as if this were
6732 // a typedef.
6733 QualType FDTy = FD->getType();
6734 if (const FunctionProtoType *FT = FDTy->getAs<FunctionProtoType>()) {
6735 SmallVector<ParmVarDecl*, 16> Params;
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00006736 for (const auto &AI : FT->param_types()) {
6737 ParmVarDecl *Param = BuildParmVarDeclForTypedef(NewFD, Loc, AI);
Eli Friedmance3e2c82011-09-07 04:05:06 +00006738 Param->setScopeInfo(0, Params.size());
6739 Params.push_back(Param);
6740 }
David Blaikie9c70e042011-09-21 18:16:56 +00006741 NewFD->setParams(Params);
John McCall3e11ebe2010-03-15 10:12:16 +00006742 }
Ryan Flynn7d470f32009-07-30 03:15:39 +00006743 } else if (VarDecl *VD = dyn_cast<VarDecl>(ND)) {
6744 NewD = VarDecl::Create(VD->getASTContext(), VD->getDeclContext(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00006745 VD->getInnerLocStart(), VD->getLocation(), II,
John McCallbcd03502009-12-07 02:54:59 +00006746 VD->getType(), VD->getTypeSourceInfo(),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00006747 VD->getStorageClass());
John McCall3e11ebe2010-03-15 10:12:16 +00006748 if (VD->getQualifier()) {
6749 VarDecl *NewVD = cast<VarDecl>(NewD);
Douglas Gregor14454802011-02-25 02:25:35 +00006750 NewVD->setQualifierInfo(VD->getQualifierLoc());
John McCall3e11ebe2010-03-15 10:12:16 +00006751 }
Ryan Flynn7d470f32009-07-30 03:15:39 +00006752 }
6753 return NewD;
6754}
6755
James Dennett634962f2012-06-14 21:40:34 +00006756/// DeclApplyPragmaWeak - A declaration (maybe definition) needs \#pragma weak
Ryan Flynn7d470f32009-07-30 03:15:39 +00006757/// applied to it, possibly with an alias.
Ryan Flynnd963a492009-07-31 02:52:19 +00006758void Sema::DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W) {
Chris Lattnere6eab982009-09-08 18:10:11 +00006759 if (W.getUsed()) return; // only do this once
6760 W.setUsed(true);
6761 if (W.getAlias()) { // clone decl, impersonate __attribute(weak,alias(...))
6762 IdentifierInfo *NDId = ND->getIdentifier();
Eli Friedmance3e2c82011-09-07 04:05:06 +00006763 NamedDecl *NewD = DeclClonePragmaWeak(ND, W.getAlias(), W.getLocation());
Aaron Ballman36a53502014-01-16 13:03:14 +00006764 NewD->addAttr(AliasAttr::CreateImplicit(Context, NDId->getName(),
6765 W.getLocation()));
6766 NewD->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation()));
Chris Lattnere6eab982009-09-08 18:10:11 +00006767 WeakTopLevelDecl.push_back(NewD);
6768 // FIXME: "hideous" code from Sema::LazilyCreateBuiltin
6769 // to insert Decl at TU scope, sorry.
6770 DeclContext *SavedContext = CurContext;
6771 CurContext = Context.getTranslationUnitDecl();
Argyrios Kyrtzidis0098a4b2014-03-09 05:15:28 +00006772 NewD->setDeclContext(CurContext);
6773 NewD->setLexicalDeclContext(CurContext);
Chris Lattnere6eab982009-09-08 18:10:11 +00006774 PushOnScopeChains(NewD, S);
6775 CurContext = SavedContext;
6776 } else { // just add weak to existing
Aaron Ballman36a53502014-01-16 13:03:14 +00006777 ND->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation()));
Ryan Flynn7d470f32009-07-30 03:15:39 +00006778 }
6779}
6780
Rafael Espindolade6a39f2013-03-02 21:41:48 +00006781void Sema::ProcessPragmaWeak(Scope *S, Decl *D) {
6782 // It's valid to "forward-declare" #pragma weak, in which case we
6783 // have to do this.
6784 LoadExternalWeakUndeclaredIdentifiers();
6785 if (!WeakUndeclaredIdentifiers.empty()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006786 NamedDecl *ND = nullptr;
Rafael Espindolade6a39f2013-03-02 21:41:48 +00006787 if (VarDecl *VD = dyn_cast<VarDecl>(D))
6788 if (VD->isExternC())
6789 ND = VD;
6790 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
6791 if (FD->isExternC())
6792 ND = FD;
6793 if (ND) {
6794 if (IdentifierInfo *Id = ND->getIdentifier()) {
Chandler Carruthf85d9822015-03-26 08:32:49 +00006795 auto I = WeakUndeclaredIdentifiers.find(Id);
Rafael Espindolade6a39f2013-03-02 21:41:48 +00006796 if (I != WeakUndeclaredIdentifiers.end()) {
6797 WeakInfo W = I->second;
6798 DeclApplyPragmaWeak(S, ND, W);
6799 WeakUndeclaredIdentifiers[Id] = W;
6800 }
6801 }
6802 }
6803 }
6804}
6805
Chris Lattner9e2aafe2008-06-29 00:23:49 +00006806/// ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in
6807/// it, apply them to D. This is a bit tricky because PD can have attributes
6808/// specified in many different places, and we need to find and apply them all.
Richard Smithf8a75c32013-08-29 00:47:48 +00006809void Sema::ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD) {
Chris Lattner9e2aafe2008-06-29 00:23:49 +00006810 // Apply decl attributes from the DeclSpec if present.
John McCall53fa7142010-12-24 02:08:15 +00006811 if (const AttributeList *Attrs = PD.getDeclSpec().getAttributes().getList())
Richard Smithf8a75c32013-08-29 00:47:48 +00006812 ProcessDeclAttributeList(S, D, Attrs);
Mike Stumpd3bb5572009-07-24 19:02:52 +00006813
Chris Lattner9e2aafe2008-06-29 00:23:49 +00006814 // Walk the declarator structure, applying decl attributes that were in a type
6815 // position to the decl itself. This handles cases like:
6816 // int *__attr__(x)** D;
6817 // when X is a decl attribute.
6818 for (unsigned i = 0, e = PD.getNumTypeObjects(); i != e; ++i)
6819 if (const AttributeList *Attrs = PD.getTypeObject(i).getAttrs())
Richard Smithf8a75c32013-08-29 00:47:48 +00006820 ProcessDeclAttributeList(S, D, Attrs, /*IncludeCXX11Attributes=*/false);
Mike Stumpd3bb5572009-07-24 19:02:52 +00006821
Chris Lattner9e2aafe2008-06-29 00:23:49 +00006822 // Finally, apply any attributes on the decl itself.
6823 if (const AttributeList *Attrs = PD.getAttributes())
Richard Smithf8a75c32013-08-29 00:47:48 +00006824 ProcessDeclAttributeList(S, D, Attrs);
Alex Lorenz9e7bf162017-04-18 14:33:39 +00006825
6826 // Apply additional attributes specified by '#pragma clang attribute'.
6827 AddPragmaAttributes(S, D);
Chris Lattner9e2aafe2008-06-29 00:23:49 +00006828}
John McCall28a6aea2009-11-04 02:18:39 +00006829
John McCall31168b02011-06-15 23:02:42 +00006830/// Is the given declaration allowed to use a forbidden type?
John McCallb61e14e2015-10-27 04:54:50 +00006831/// If so, it'll still be annotated with an attribute that makes it
6832/// illegal to actually use.
6833static bool isForbiddenTypeAllowed(Sema &S, Decl *decl,
6834 const DelayedDiagnostic &diag,
John McCallc6af8c62015-10-28 05:03:19 +00006835 UnavailableAttr::ImplicitReason &reason) {
John McCall31168b02011-06-15 23:02:42 +00006836 // Private ivars are always okay. Unfortunately, people don't
6837 // always properly make their ivars private, even in system headers.
6838 // Plus we need to make fields okay, too.
Fariborz Jahanian6d5d6a22011-09-26 21:23:35 +00006839 if (!isa<FieldDecl>(decl) && !isa<ObjCPropertyDecl>(decl) &&
6840 !isa<FunctionDecl>(decl))
John McCall31168b02011-06-15 23:02:42 +00006841 return false;
6842
John McCallc6af8c62015-10-28 05:03:19 +00006843 // Silently accept unsupported uses of __weak in both user and system
6844 // declarations when it's been disabled, for ease of integration with
6845 // -fno-objc-arc files. We do have to take some care against attempts
6846 // to define such things; for now, we've only done that for ivars
6847 // and properties.
6848 if ((isa<ObjCIvarDecl>(decl) || isa<ObjCPropertyDecl>(decl))) {
6849 if (diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_disabled ||
6850 diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_no_runtime) {
6851 reason = UnavailableAttr::IR_ForbiddenWeak;
6852 return true;
6853 }
John McCallb61e14e2015-10-27 04:54:50 +00006854 }
6855
John McCallc6af8c62015-10-28 05:03:19 +00006856 // Allow all sorts of things in system headers.
6857 if (S.Context.getSourceManager().isInSystemHeader(decl->getLocation())) {
6858 // Currently, all the failures dealt with this way are due to ARC
6859 // restrictions.
6860 reason = UnavailableAttr::IR_ARCForbiddenType;
6861 return true;
John McCallb61e14e2015-10-27 04:54:50 +00006862 }
6863
6864 return false;
John McCall31168b02011-06-15 23:02:42 +00006865}
6866
6867/// Handle a delayed forbidden-type diagnostic.
6868static void handleDelayedForbiddenType(Sema &S, DelayedDiagnostic &diag,
6869 Decl *decl) {
John McCallc6af8c62015-10-28 05:03:19 +00006870 auto reason = UnavailableAttr::IR_None;
6871 if (decl && isForbiddenTypeAllowed(S, decl, diag, reason)) {
6872 assert(reason && "didn't set reason?");
6873 decl->addAttr(UnavailableAttr::CreateImplicit(S.Context, "", reason,
6874 diag.Loc));
John McCall31168b02011-06-15 23:02:42 +00006875 return;
6876 }
David Blaikiebbafb8a2012-03-11 07:00:24 +00006877 if (S.getLangOpts().ObjCAutoRefCount)
Fariborz Jahanianed1933b2011-10-03 22:11:57 +00006878 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(decl)) {
Benjamin Kramer474261a2012-06-02 10:20:41 +00006879 // FIXME: we may want to suppress diagnostics for all
Fariborz Jahanianed1933b2011-10-03 22:11:57 +00006880 // kind of forbidden type messages on unavailable functions.
6881 if (FD->hasAttr<UnavailableAttr>() &&
6882 diag.getForbiddenTypeDiagnostic() ==
6883 diag::err_arc_array_param_no_ownership) {
6884 diag.Triggered = true;
6885 return;
6886 }
6887 }
John McCall31168b02011-06-15 23:02:42 +00006888
6889 S.Diag(diag.Loc, diag.getForbiddenTypeDiagnostic())
6890 << diag.getForbiddenTypeOperand() << diag.getForbiddenTypeArgument();
6891 diag.Triggered = true;
6892}
6893
Manman Ren45b1ab12016-05-06 19:57:16 +00006894static const AvailabilityAttr *getAttrForPlatform(ASTContext &Context,
6895 const Decl *D) {
6896 // Check each AvailabilityAttr to find the one for this platform.
6897 for (const auto *A : D->attrs()) {
6898 if (const auto *Avail = dyn_cast<AvailabilityAttr>(A)) {
6899 // FIXME: this is copied from CheckAvailability. We should try to
6900 // de-duplicate.
6901
6902 // Check if this is an App Extension "platform", and if so chop off
6903 // the suffix for matching with the actual platform.
6904 StringRef ActualPlatform = Avail->getPlatform()->getName();
6905 StringRef RealizedPlatform = ActualPlatform;
6906 if (Context.getLangOpts().AppExt) {
6907 size_t suffix = RealizedPlatform.rfind("_app_extension");
6908 if (suffix != StringRef::npos)
6909 RealizedPlatform = RealizedPlatform.slice(0, suffix);
6910 }
6911
6912 StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
6913
6914 // Match the platform name.
6915 if (RealizedPlatform == TargetPlatform)
6916 return Avail;
6917 }
6918 }
6919 return nullptr;
6920}
6921
Erik Pilkington9f866a72017-07-18 20:32:07 +00006922/// The diagnostic we should emit for \c D, and the declaration that
6923/// originated it, or \c AR_Available.
6924///
6925/// \param D The declaration to check.
6926/// \param Message If non-null, this will be populated with the message from
6927/// the availability attribute that is selected.
6928static std::pair<AvailabilityResult, const NamedDecl *>
6929ShouldDiagnoseAvailabilityOfDecl(const NamedDecl *D, std::string *Message) {
6930 AvailabilityResult Result = D->getAvailability(Message);
6931
6932 // For typedefs, if the typedef declaration appears available look
6933 // to the underlying type to see if it is more restrictive.
6934 while (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
6935 if (Result == AR_Available) {
6936 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
6937 D = TT->getDecl();
6938 Result = D->getAvailability(Message);
6939 continue;
6940 }
6941 }
6942 break;
6943 }
6944
6945 // Forward class declarations get their attributes from their definition.
6946 if (const ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(D)) {
6947 if (IDecl->getDefinition()) {
6948 D = IDecl->getDefinition();
6949 Result = D->getAvailability(Message);
6950 }
6951 }
6952
6953 if (const auto *ECD = dyn_cast<EnumConstantDecl>(D))
6954 if (Result == AR_Available) {
6955 const DeclContext *DC = ECD->getDeclContext();
6956 if (const auto *TheEnumDecl = dyn_cast<EnumDecl>(DC)) {
6957 Result = TheEnumDecl->getAvailability(Message);
6958 D = TheEnumDecl;
6959 }
6960 }
6961
6962 return {Result, D};
6963}
6964
6965
Erik Pilkingtonf35114c2016-10-25 19:05:50 +00006966/// \brief whether we should emit a diagnostic for \c K and \c DeclVersion in
6967/// the context of \c Ctx. For example, we should emit an unavailable diagnostic
6968/// in a deprecated context, but not the other way around.
6969static bool ShouldDiagnoseAvailabilityInContext(Sema &S, AvailabilityResult K,
6970 VersionTuple DeclVersion,
6971 Decl *Ctx) {
6972 assert(K != AR_Available && "Expected an unavailable declaration here!");
6973
6974 // Checks if we should emit the availability diagnostic in the context of C.
6975 auto CheckContext = [&](const Decl *C) {
6976 if (K == AR_NotYetIntroduced) {
6977 if (const AvailabilityAttr *AA = getAttrForPlatform(S.Context, C))
6978 if (AA->getIntroduced() >= DeclVersion)
6979 return true;
6980 } else if (K == AR_Deprecated)
6981 if (C->isDeprecated())
6982 return true;
6983
6984 if (C->isUnavailable())
6985 return true;
6986 return false;
6987 };
6988
6989 // FIXME: This is a temporary workaround! Some existing Apple headers depends
6990 // on nested declarations in an @interface having the availability of the
6991 // interface when they really shouldn't: they are members of the enclosing
6992 // context, and can referenced from there.
6993 if (S.OriginalLexicalContext && cast<Decl>(S.OriginalLexicalContext) != Ctx) {
6994 auto *OrigCtx = cast<Decl>(S.OriginalLexicalContext);
6995 if (CheckContext(OrigCtx))
6996 return false;
6997
6998 // An implementation implicitly has the availability of the interface.
6999 if (auto *CatOrImpl = dyn_cast<ObjCImplDecl>(OrigCtx)) {
7000 if (const ObjCInterfaceDecl *Interface = CatOrImpl->getClassInterface())
7001 if (CheckContext(Interface))
7002 return false;
7003 }
7004 // A category implicitly has the availability of the interface.
7005 else if (auto *CatD = dyn_cast<ObjCCategoryDecl>(OrigCtx))
7006 if (const ObjCInterfaceDecl *Interface = CatD->getClassInterface())
7007 if (CheckContext(Interface))
7008 return false;
7009 }
7010
7011 do {
7012 if (CheckContext(Ctx))
7013 return false;
7014
7015 // An implementation implicitly has the availability of the interface.
7016 if (auto *CatOrImpl = dyn_cast<ObjCImplDecl>(Ctx)) {
7017 if (const ObjCInterfaceDecl *Interface = CatOrImpl->getClassInterface())
7018 if (CheckContext(Interface))
7019 return false;
7020 }
7021 // A category implicitly has the availability of the interface.
7022 else if (auto *CatD = dyn_cast<ObjCCategoryDecl>(Ctx))
7023 if (const ObjCInterfaceDecl *Interface = CatD->getClassInterface())
7024 if (CheckContext(Interface))
7025 return false;
7026 } while ((Ctx = cast_or_null<Decl>(Ctx->getDeclContext())));
7027
7028 return true;
7029}
7030
Alex Lorenzc9a369f2017-06-22 17:02:24 +00007031static bool
7032shouldDiagnoseAvailabilityByDefault(const ASTContext &Context,
7033 const VersionTuple &DeploymentVersion,
7034 const VersionTuple &DeclVersion) {
7035 const auto &Triple = Context.getTargetInfo().getTriple();
7036 VersionTuple ForceAvailabilityFromVersion;
7037 switch (Triple.getOS()) {
7038 case llvm::Triple::IOS:
7039 case llvm::Triple::TvOS:
7040 ForceAvailabilityFromVersion = VersionTuple(/*Major=*/11);
7041 break;
7042 case llvm::Triple::WatchOS:
7043 ForceAvailabilityFromVersion = VersionTuple(/*Major=*/4);
7044 break;
7045 case llvm::Triple::Darwin:
7046 case llvm::Triple::MacOSX:
7047 ForceAvailabilityFromVersion = VersionTuple(/*Major=*/10, /*Minor=*/13);
7048 break;
7049 default:
7050 // New targets should always warn about availability.
7051 return Triple.getVendor() == llvm::Triple::Apple;
7052 }
7053 return DeploymentVersion >= ForceAvailabilityFromVersion ||
7054 DeclVersion >= ForceAvailabilityFromVersion;
7055}
7056
Erik Pilkington4042f3c2017-07-05 17:08:56 +00007057static NamedDecl *findEnclosingDeclToAnnotate(Decl *OrigCtx) {
7058 for (Decl *Ctx = OrigCtx; Ctx;
7059 Ctx = cast_or_null<Decl>(Ctx->getDeclContext())) {
7060 if (isa<TagDecl>(Ctx) || isa<FunctionDecl>(Ctx) || isa<ObjCMethodDecl>(Ctx))
7061 return cast<NamedDecl>(Ctx);
7062 if (auto *CD = dyn_cast<ObjCContainerDecl>(Ctx)) {
7063 if (auto *Imp = dyn_cast<ObjCImplDecl>(Ctx))
7064 return Imp->getClassInterface();
7065 return CD;
7066 }
7067 }
7068
7069 return dyn_cast<NamedDecl>(OrigCtx);
7070}
7071
Alex Lorenz727c21e2017-07-26 13:58:02 +00007072namespace {
7073
7074struct AttributeInsertion {
7075 StringRef Prefix;
7076 SourceLocation Loc;
7077 StringRef Suffix;
7078
7079 static AttributeInsertion createInsertionAfter(const NamedDecl *D) {
7080 return {" ", D->getLocEnd(), ""};
7081 }
7082 static AttributeInsertion createInsertionAfter(SourceLocation Loc) {
7083 return {" ", Loc, ""};
7084 }
7085 static AttributeInsertion createInsertionBefore(const NamedDecl *D) {
7086 return {"", D->getLocStart(), "\n"};
7087 }
7088};
7089
7090} // end anonymous namespace
7091
7092/// Returns a source location in which it's appropriate to insert a new
7093/// attribute for the given declaration \D.
7094static Optional<AttributeInsertion>
7095createAttributeInsertion(const NamedDecl *D, const SourceManager &SM,
7096 const LangOptions &LangOpts) {
7097 if (isa<ObjCPropertyDecl>(D))
7098 return AttributeInsertion::createInsertionAfter(D);
7099 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
7100 if (MD->hasBody())
7101 return None;
7102 return AttributeInsertion::createInsertionAfter(D);
7103 }
7104 if (const auto *TD = dyn_cast<TagDecl>(D)) {
7105 SourceLocation Loc =
7106 Lexer::getLocForEndOfToken(TD->getInnerLocStart(), 0, SM, LangOpts);
7107 if (Loc.isInvalid())
7108 return None;
7109 // Insert after the 'struct'/whatever keyword.
7110 return AttributeInsertion::createInsertionAfter(Loc);
7111 }
7112 return AttributeInsertion::createInsertionBefore(D);
7113}
7114
Erik Pilkington4042f3c2017-07-05 17:08:56 +00007115/// Actually emit an availability diagnostic for a reference to an unavailable
7116/// decl.
7117///
7118/// \param Ctx The context that the reference occurred in
7119/// \param ReferringDecl The exact declaration that was referenced.
7120/// \param OffendingDecl A related decl to \c ReferringDecl that has an
7121/// availability attribute corrisponding to \c K attached to it. Note that this
7122/// may not be the same as ReferringDecl, i.e. if an EnumDecl is annotated and
7123/// we refer to a member EnumConstantDecl, ReferringDecl is the EnumConstantDecl
7124/// and OffendingDecl is the EnumDecl.
Erik Pilkington796a3e22016-08-05 22:59:03 +00007125static void DoEmitAvailabilityWarning(Sema &S, AvailabilityResult K,
Erik Pilkington4042f3c2017-07-05 17:08:56 +00007126 Decl *Ctx, const NamedDecl *ReferringDecl,
7127 const NamedDecl *OffendingDecl,
Aaron Ballmanfb237522014-10-15 15:37:51 +00007128 StringRef Message, SourceLocation Loc,
7129 const ObjCInterfaceDecl *UnknownObjCClass,
7130 const ObjCPropertyDecl *ObjCProperty,
7131 bool ObjCPropertyAccess) {
7132 // Diagnostics for deprecated or unavailable.
7133 unsigned diag, diag_message, diag_fwdclass_message;
John McCallb61e14e2015-10-27 04:54:50 +00007134 unsigned diag_available_here = diag::note_availability_specified_here;
Erik Pilkington4042f3c2017-07-05 17:08:56 +00007135 SourceLocation NoteLocation = OffendingDecl->getLocation();
Aaron Ballmanfb237522014-10-15 15:37:51 +00007136
7137 // Matches 'diag::note_property_attribute' options.
7138 unsigned property_note_select;
7139
7140 // Matches diag::note_availability_specified_here.
7141 unsigned available_here_select_kind;
7142
Erik Pilkingtonf35114c2016-10-25 19:05:50 +00007143 VersionTuple DeclVersion;
Erik Pilkington4042f3c2017-07-05 17:08:56 +00007144 if (const AvailabilityAttr *AA = getAttrForPlatform(S.Context, OffendingDecl))
Erik Pilkingtonf35114c2016-10-25 19:05:50 +00007145 DeclVersion = AA->getIntroduced();
7146
7147 if (!ShouldDiagnoseAvailabilityInContext(S, K, DeclVersion, Ctx))
7148 return;
7149
Erik Pilkington8b352c42017-08-14 19:49:12 +00007150 // The declaration can have multiple availability attributes, we are looking
7151 // at one of them.
7152 const AvailabilityAttr *A = getAttrForPlatform(S.Context, OffendingDecl);
7153 if (A && A->isInherited()) {
7154 for (const Decl *Redecl = OffendingDecl->getMostRecentDecl(); Redecl;
7155 Redecl = Redecl->getPreviousDecl()) {
7156 const AvailabilityAttr *AForRedecl =
7157 getAttrForPlatform(S.Context, Redecl);
7158 if (AForRedecl && !AForRedecl->isInherited()) {
7159 // If D is a declaration with inherited attributes, the note should
7160 // point to the declaration with actual attributes.
7161 NoteLocation = Redecl->getLocation();
7162 break;
7163 }
7164 }
7165 }
7166
Aaron Ballmanfb237522014-10-15 15:37:51 +00007167 switch (K) {
Erik Pilkington8b352c42017-08-14 19:49:12 +00007168 case AR_NotYetIntroduced: {
7169 // We would like to emit the diagnostic even if -Wunguarded-availability is
7170 // not specified for deployment targets >= to iOS 11 or equivalent or
7171 // for declarations that were introduced in iOS 11 (macOS 10.13, ...) or
7172 // later.
7173 const AvailabilityAttr *AA =
7174 getAttrForPlatform(S.getASTContext(), OffendingDecl);
7175 VersionTuple Introduced = AA->getIntroduced();
7176
7177 bool UseNewWarning = shouldDiagnoseAvailabilityByDefault(
7178 S.Context, S.Context.getTargetInfo().getPlatformMinVersion(),
7179 Introduced);
7180 unsigned Warning = UseNewWarning ? diag::warn_unguarded_availability_new
7181 : diag::warn_unguarded_availability;
7182
7183 S.Diag(Loc, Warning)
7184 << OffendingDecl
7185 << AvailabilityAttr::getPrettyPlatformName(
7186 S.getASTContext().getTargetInfo().getPlatformName())
7187 << Introduced.getAsString();
7188
7189 S.Diag(OffendingDecl->getLocation(), diag::note_availability_specified_here)
7190 << OffendingDecl << /* partial */ 3;
7191
7192 if (const auto *Enclosing = findEnclosingDeclToAnnotate(Ctx)) {
7193 if (auto *TD = dyn_cast<TagDecl>(Enclosing))
7194 if (TD->getDeclName().isEmpty()) {
7195 S.Diag(TD->getLocation(),
7196 diag::note_decl_unguarded_availability_silence)
7197 << /*Anonymous*/ 1 << TD->getKindName();
7198 return;
7199 }
7200 auto FixitNoteDiag =
7201 S.Diag(Enclosing->getLocation(),
7202 diag::note_decl_unguarded_availability_silence)
7203 << /*Named*/ 0 << Enclosing;
7204 // Don't offer a fixit for declarations with availability attributes.
7205 if (Enclosing->hasAttr<AvailabilityAttr>())
7206 return;
7207 if (!S.getPreprocessor().isMacroDefined("API_AVAILABLE"))
7208 return;
7209 Optional<AttributeInsertion> Insertion = createAttributeInsertion(
7210 Enclosing, S.getSourceManager(), S.getLangOpts());
7211 if (!Insertion)
7212 return;
7213 std::string PlatformName =
7214 AvailabilityAttr::getPlatformNameSourceSpelling(
7215 S.getASTContext().getTargetInfo().getPlatformName())
7216 .lower();
7217 std::string Introduced =
7218 OffendingDecl->getVersionIntroduced().getAsString();
7219 FixitNoteDiag << FixItHint::CreateInsertion(
7220 Insertion->Loc,
7221 (llvm::Twine(Insertion->Prefix) + "API_AVAILABLE(" + PlatformName +
7222 "(" + Introduced + "))" + Insertion->Suffix)
7223 .str());
7224 }
7225 return;
7226 }
Erik Pilkington796a3e22016-08-05 22:59:03 +00007227 case AR_Deprecated:
Aaron Ballmanfb237522014-10-15 15:37:51 +00007228 diag = !ObjCPropertyAccess ? diag::warn_deprecated
7229 : diag::warn_property_method_deprecated;
7230 diag_message = diag::warn_deprecated_message;
7231 diag_fwdclass_message = diag::warn_deprecated_fwdclass_message;
7232 property_note_select = /* deprecated */ 0;
7233 available_here_select_kind = /* deprecated */ 2;
Erich Keaneb11ebc52017-09-27 03:20:13 +00007234 if (const auto *Attr = OffendingDecl->getAttr<DeprecatedAttr>())
7235 NoteLocation = Attr->getLocation();
Aaron Ballmanfb237522014-10-15 15:37:51 +00007236 break;
7237
Erik Pilkington796a3e22016-08-05 22:59:03 +00007238 case AR_Unavailable:
Aaron Ballmanfb237522014-10-15 15:37:51 +00007239 diag = !ObjCPropertyAccess ? diag::err_unavailable
7240 : diag::err_property_method_unavailable;
7241 diag_message = diag::err_unavailable_message;
7242 diag_fwdclass_message = diag::warn_unavailable_fwdclass_message;
7243 property_note_select = /* unavailable */ 1;
7244 available_here_select_kind = /* unavailable */ 0;
John McCallb61e14e2015-10-27 04:54:50 +00007245
Erich Keaneb11ebc52017-09-27 03:20:13 +00007246 if (auto Attr = OffendingDecl->getAttr<UnavailableAttr>()) {
7247 if (Attr->isImplicit() && Attr->getImplicitReason()) {
John McCallc6af8c62015-10-28 05:03:19 +00007248 // Most of these failures are due to extra restrictions in ARC;
7249 // reflect that in the primary diagnostic when applicable.
7250 auto flagARCError = [&] {
7251 if (S.getLangOpts().ObjCAutoRefCount &&
Erik Pilkington4042f3c2017-07-05 17:08:56 +00007252 S.getSourceManager().isInSystemHeader(
7253 OffendingDecl->getLocation()))
John McCallc6af8c62015-10-28 05:03:19 +00007254 diag = diag::err_unavailable_in_arc;
7255 };
7256
Erich Keaneb11ebc52017-09-27 03:20:13 +00007257 switch (Attr->getImplicitReason()) {
John McCallc6af8c62015-10-28 05:03:19 +00007258 case UnavailableAttr::IR_None: break;
7259
7260 case UnavailableAttr::IR_ARCForbiddenType:
7261 flagARCError();
7262 diag_available_here = diag::note_arc_forbidden_type;
7263 break;
7264
7265 case UnavailableAttr::IR_ForbiddenWeak:
7266 if (S.getLangOpts().ObjCWeakRuntime)
7267 diag_available_here = diag::note_arc_weak_disabled;
7268 else
7269 diag_available_here = diag::note_arc_weak_no_runtime;
7270 break;
7271
7272 case UnavailableAttr::IR_ARCForbiddenConversion:
7273 flagARCError();
7274 diag_available_here = diag::note_performs_forbidden_arc_conversion;
7275 break;
7276
7277 case UnavailableAttr::IR_ARCInitReturnsUnrelated:
7278 flagARCError();
7279 diag_available_here = diag::note_arc_init_returns_unrelated;
7280 break;
7281
7282 case UnavailableAttr::IR_ARCFieldWithOwnership:
7283 flagARCError();
7284 diag_available_here = diag::note_arc_field_with_ownership;
7285 break;
7286 }
7287 }
John McCallb61e14e2015-10-27 04:54:50 +00007288 }
Aaron Ballmanfb237522014-10-15 15:37:51 +00007289 break;
7290
Erik Pilkington796a3e22016-08-05 22:59:03 +00007291 case AR_Available:
7292 llvm_unreachable("Warning for availability of available declaration?");
Aaron Ballmanfb237522014-10-15 15:37:51 +00007293 }
7294
Manman Renc7890fe2016-03-16 18:50:49 +00007295 CharSourceRange UseRange;
7296 StringRef Replacement;
Erik Pilkington796a3e22016-08-05 22:59:03 +00007297 if (K == AR_Deprecated) {
Erich Keaneb11ebc52017-09-27 03:20:13 +00007298 if (auto Attr = OffendingDecl->getAttr<DeprecatedAttr>())
7299 Replacement = Attr->getReplacement();
7300 if (auto Attr = getAttrForPlatform(S.Context, OffendingDecl))
7301 Replacement = Attr->getReplacement();
Manman Renc7890fe2016-03-16 18:50:49 +00007302
7303 if (!Replacement.empty())
7304 UseRange =
7305 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
7306 }
7307
Aaron Ballmanfb237522014-10-15 15:37:51 +00007308 if (!Message.empty()) {
Erik Pilkington4042f3c2017-07-05 17:08:56 +00007309 S.Diag(Loc, diag_message) << ReferringDecl << Message
Manman Renc7890fe2016-03-16 18:50:49 +00007310 << (UseRange.isValid() ?
7311 FixItHint::CreateReplacement(UseRange, Replacement) : FixItHint());
Aaron Ballmanfb237522014-10-15 15:37:51 +00007312 if (ObjCProperty)
7313 S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute)
7314 << ObjCProperty->getDeclName() << property_note_select;
7315 } else if (!UnknownObjCClass) {
Erik Pilkington4042f3c2017-07-05 17:08:56 +00007316 S.Diag(Loc, diag) << ReferringDecl
Manman Renc7890fe2016-03-16 18:50:49 +00007317 << (UseRange.isValid() ?
7318 FixItHint::CreateReplacement(UseRange, Replacement) : FixItHint());
Aaron Ballmanfb237522014-10-15 15:37:51 +00007319 if (ObjCProperty)
7320 S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute)
7321 << ObjCProperty->getDeclName() << property_note_select;
7322 } else {
Erik Pilkington4042f3c2017-07-05 17:08:56 +00007323 S.Diag(Loc, diag_fwdclass_message) << ReferringDecl
Manman Renc7890fe2016-03-16 18:50:49 +00007324 << (UseRange.isValid() ?
7325 FixItHint::CreateReplacement(UseRange, Replacement) : FixItHint());
Aaron Ballmanfb237522014-10-15 15:37:51 +00007326 S.Diag(UnknownObjCClass->getLocation(), diag::note_forward_class);
7327 }
7328
Erik Pilkington8b352c42017-08-14 19:49:12 +00007329 S.Diag(NoteLocation, diag_available_here)
7330 << OffendingDecl << available_here_select_kind;
Aaron Ballmanfb237522014-10-15 15:37:51 +00007331}
7332
7333static void handleDelayedAvailabilityCheck(Sema &S, DelayedDiagnostic &DD,
7334 Decl *Ctx) {
Erik Pilkingtona8003972016-10-28 21:39:27 +00007335 assert(DD.Kind == DelayedDiagnostic::Availability &&
7336 "Expected an availability diagnostic here");
7337
Aaron Ballmanfb237522014-10-15 15:37:51 +00007338 DD.Triggered = true;
Nico Weber0055a192015-03-19 19:18:22 +00007339 DoEmitAvailabilityWarning(
Erik Pilkington4042f3c2017-07-05 17:08:56 +00007340 S, DD.getAvailabilityResult(), Ctx, DD.getAvailabilityReferringDecl(),
7341 DD.getAvailabilityOffendingDecl(), DD.getAvailabilityMessage(), DD.Loc,
7342 DD.getUnknownObjCClass(), DD.getObjCProperty(), false);
Aaron Ballmanfb237522014-10-15 15:37:51 +00007343}
7344
John McCall2ec85372012-05-07 06:16:41 +00007345void Sema::PopParsingDeclaration(ParsingDeclState state, Decl *decl) {
7346 assert(DelayedDiagnostics.getCurrentPool());
John McCall6347b682012-05-07 06:16:58 +00007347 DelayedDiagnosticPool &poppedPool = *DelayedDiagnostics.getCurrentPool();
John McCall2ec85372012-05-07 06:16:41 +00007348 DelayedDiagnostics.popWithoutEmitting(state);
John McCallc1465822011-02-14 07:13:47 +00007349
John McCall2ec85372012-05-07 06:16:41 +00007350 // When delaying diagnostics to run in the context of a parsed
7351 // declaration, we only want to actually emit anything if parsing
7352 // succeeds.
7353 if (!decl) return;
John McCallc1465822011-02-14 07:13:47 +00007354
John McCall2ec85372012-05-07 06:16:41 +00007355 // We emit all the active diagnostics in this pool or any of its
7356 // parents. In general, we'll get one pool for the decl spec
7357 // and a child pool for each declarator; in a decl group like:
7358 // deprecated_typedef foo, *bar, baz();
7359 // only the declarator pops will be passed decls. This is correct;
7360 // we really do need to consider delayed diagnostics from the decl spec
7361 // for each of the different declarations.
John McCall6347b682012-05-07 06:16:58 +00007362 const DelayedDiagnosticPool *pool = &poppedPool;
John McCall2ec85372012-05-07 06:16:41 +00007363 do {
John McCall6347b682012-05-07 06:16:58 +00007364 for (DelayedDiagnosticPool::pool_iterator
John McCall2ec85372012-05-07 06:16:41 +00007365 i = pool->pool_begin(), e = pool->pool_end(); i != e; ++i) {
7366 // This const_cast is a bit lame. Really, Triggered should be mutable.
7367 DelayedDiagnostic &diag = const_cast<DelayedDiagnostic&>(*i);
John McCallc1465822011-02-14 07:13:47 +00007368 if (diag.Triggered)
John McCall86121512010-01-27 03:50:35 +00007369 continue;
7370
John McCallc1465822011-02-14 07:13:47 +00007371 switch (diag.Kind) {
Erik Pilkingtona8003972016-10-28 21:39:27 +00007372 case DelayedDiagnostic::Availability:
Ted Kremenekb79ee572013-12-18 23:30:06 +00007373 // Don't bother giving deprecation/unavailable diagnostics if
7374 // the decl is invalid.
John McCall18a962b2012-01-26 20:04:03 +00007375 if (!decl->isInvalidDecl())
Aaron Ballmanfb237522014-10-15 15:37:51 +00007376 handleDelayedAvailabilityCheck(*this, diag, decl);
John McCall86121512010-01-27 03:50:35 +00007377 break;
7378
7379 case DelayedDiagnostic::Access:
John McCall2ec85372012-05-07 06:16:41 +00007380 HandleDelayedAccessCheck(diag, decl);
John McCall86121512010-01-27 03:50:35 +00007381 break;
John McCall31168b02011-06-15 23:02:42 +00007382
7383 case DelayedDiagnostic::ForbiddenType:
John McCall2ec85372012-05-07 06:16:41 +00007384 handleDelayedForbiddenType(*this, diag, decl);
John McCall31168b02011-06-15 23:02:42 +00007385 break;
John McCall86121512010-01-27 03:50:35 +00007386 }
7387 }
John McCall2ec85372012-05-07 06:16:41 +00007388 } while ((pool = pool->getParent()));
John McCall28a6aea2009-11-04 02:18:39 +00007389}
7390
John McCall6347b682012-05-07 06:16:58 +00007391/// Given a set of delayed diagnostics, re-emit them as if they had
7392/// been delayed in the current context instead of in the given pool.
7393/// Essentially, this just moves them to the current pool.
7394void Sema::redelayDiagnostics(DelayedDiagnosticPool &pool) {
7395 DelayedDiagnosticPool *curPool = DelayedDiagnostics.getCurrentPool();
7396 assert(curPool && "re-emitting in undelayed context not supported");
7397 curPool->steal(pool);
7398}
7399
Erik Pilkington9f866a72017-07-18 20:32:07 +00007400static void EmitAvailabilityWarning(Sema &S, AvailabilityResult AR,
7401 const NamedDecl *ReferringDecl,
7402 const NamedDecl *OffendingDecl,
7403 StringRef Message, SourceLocation Loc,
7404 const ObjCInterfaceDecl *UnknownObjCClass,
7405 const ObjCPropertyDecl *ObjCProperty,
7406 bool ObjCPropertyAccess) {
John McCall28a6aea2009-11-04 02:18:39 +00007407 // Delay if we're currently parsing a declaration.
Erik Pilkington9f866a72017-07-18 20:32:07 +00007408 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
7409 S.DelayedDiagnostics.add(
Erik Pilkington4042f3c2017-07-05 17:08:56 +00007410 DelayedDiagnostic::makeAvailability(
7411 AR, Loc, ReferringDecl, OffendingDecl, UnknownObjCClass,
7412 ObjCProperty, Message, ObjCPropertyAccess));
John McCall28a6aea2009-11-04 02:18:39 +00007413 return;
7414 }
7415
Erik Pilkington9f866a72017-07-18 20:32:07 +00007416 Decl *Ctx = cast<Decl>(S.getCurLexicalContext());
7417 DoEmitAvailabilityWarning(S, AR, Ctx, ReferringDecl, OffendingDecl,
Erik Pilkington4042f3c2017-07-05 17:08:56 +00007418 Message, Loc, UnknownObjCClass, ObjCProperty,
7419 ObjCPropertyAccess);
John McCall28a6aea2009-11-04 02:18:39 +00007420}
Erik Pilkington48c7cc92016-07-29 17:37:38 +00007421
Erik Pilkington5cd57172016-08-16 17:44:11 +00007422namespace {
7423
Alex Lorenz9c5c2bf2017-05-05 16:42:44 +00007424/// Returns true if the given statement can be a body-like child of \p Parent.
7425bool isBodyLikeChildStmt(const Stmt *S, const Stmt *Parent) {
7426 switch (Parent->getStmtClass()) {
7427 case Stmt::IfStmtClass:
7428 return cast<IfStmt>(Parent)->getThen() == S ||
7429 cast<IfStmt>(Parent)->getElse() == S;
7430 case Stmt::WhileStmtClass:
7431 return cast<WhileStmt>(Parent)->getBody() == S;
7432 case Stmt::DoStmtClass:
7433 return cast<DoStmt>(Parent)->getBody() == S;
7434 case Stmt::ForStmtClass:
7435 return cast<ForStmt>(Parent)->getBody() == S;
7436 case Stmt::CXXForRangeStmtClass:
7437 return cast<CXXForRangeStmt>(Parent)->getBody() == S;
7438 case Stmt::ObjCForCollectionStmtClass:
7439 return cast<ObjCForCollectionStmt>(Parent)->getBody() == S;
7440 case Stmt::CaseStmtClass:
7441 case Stmt::DefaultStmtClass:
7442 return cast<SwitchCase>(Parent)->getSubStmt() == S;
7443 default:
7444 return false;
7445 }
7446}
7447
7448class StmtUSEFinder : public RecursiveASTVisitor<StmtUSEFinder> {
7449 const Stmt *Target;
7450
7451public:
7452 bool VisitStmt(Stmt *S) { return S != Target; }
7453
7454 /// Returns true if the given statement is present in the given declaration.
7455 static bool isContained(const Stmt *Target, const Decl *D) {
7456 StmtUSEFinder Visitor;
7457 Visitor.Target = Target;
7458 return !Visitor.TraverseDecl(const_cast<Decl *>(D));
7459 }
7460};
7461
7462/// Traverses the AST and finds the last statement that used a given
7463/// declaration.
7464class LastDeclUSEFinder : public RecursiveASTVisitor<LastDeclUSEFinder> {
7465 const Decl *D;
7466
7467public:
7468 bool VisitDeclRefExpr(DeclRefExpr *DRE) {
7469 if (DRE->getDecl() == D)
7470 return false;
7471 return true;
7472 }
7473
7474 static const Stmt *findLastStmtThatUsesDecl(const Decl *D,
7475 const CompoundStmt *Scope) {
7476 LastDeclUSEFinder Visitor;
7477 Visitor.D = D;
7478 for (auto I = Scope->body_rbegin(), E = Scope->body_rend(); I != E; ++I) {
7479 const Stmt *S = *I;
7480 if (!Visitor.TraverseStmt(const_cast<Stmt *>(S)))
7481 return S;
7482 }
7483 return nullptr;
7484 }
7485};
7486
Erik Pilkington5cd57172016-08-16 17:44:11 +00007487/// \brief This class implements -Wunguarded-availability.
7488///
7489/// This is done with a traversal of the AST of a function that makes reference
7490/// to a partially available declaration. Whenever we encounter an \c if of the
7491/// form: \c if(@available(...)), we use the version from the condition to visit
7492/// the then statement.
7493class DiagnoseUnguardedAvailability
7494 : public RecursiveASTVisitor<DiagnoseUnguardedAvailability> {
7495 typedef RecursiveASTVisitor<DiagnoseUnguardedAvailability> Base;
7496
7497 Sema &SemaRef;
Erik Pilkingtonf35114c2016-10-25 19:05:50 +00007498 Decl *Ctx;
Erik Pilkington5cd57172016-08-16 17:44:11 +00007499
7500 /// Stack of potentially nested 'if (@available(...))'s.
7501 SmallVector<VersionTuple, 8> AvailabilityStack;
Alex Lorenz9c5c2bf2017-05-05 16:42:44 +00007502 SmallVector<const Stmt *, 16> StmtStack;
Erik Pilkington5cd57172016-08-16 17:44:11 +00007503
7504 void DiagnoseDeclAvailability(NamedDecl *D, SourceRange Range);
7505
7506public:
Erik Pilkingtonf35114c2016-10-25 19:05:50 +00007507 DiagnoseUnguardedAvailability(Sema &SemaRef, Decl *Ctx)
7508 : SemaRef(SemaRef), Ctx(Ctx) {
7509 AvailabilityStack.push_back(
7510 SemaRef.Context.getTargetInfo().getPlatformMinVersion());
Erik Pilkington5cd57172016-08-16 17:44:11 +00007511 }
7512
Alex Lorenz6f911122017-05-16 13:58:53 +00007513 bool TraverseDecl(Decl *D) {
7514 // Avoid visiting nested functions to prevent duplicate warnings.
7515 if (!D || isa<FunctionDecl>(D))
7516 return true;
7517 return Base::TraverseDecl(D);
7518 }
7519
Alex Lorenz9c5c2bf2017-05-05 16:42:44 +00007520 bool TraverseStmt(Stmt *S) {
7521 if (!S)
7522 return true;
7523 StmtStack.push_back(S);
7524 bool Result = Base::TraverseStmt(S);
7525 StmtStack.pop_back();
7526 return Result;
7527 }
7528
Erik Pilkington5cd57172016-08-16 17:44:11 +00007529 void IssueDiagnostics(Stmt *S) { TraverseStmt(S); }
7530
7531 bool TraverseIfStmt(IfStmt *If);
7532
Alex Lorenz6f911122017-05-16 13:58:53 +00007533 bool TraverseLambdaExpr(LambdaExpr *E) { return true; }
7534
Erik Pilkingtonba87c622017-08-18 20:20:56 +00007535 // for 'case X:' statements, don't bother looking at the 'X'; it can't lead
7536 // to any useful diagnostics.
7537 bool TraverseCaseStmt(CaseStmt *CS) { return TraverseStmt(CS->getSubStmt()); }
7538
Erik Pilkington6ac77a62017-05-22 15:41:12 +00007539 bool VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *PRE) {
7540 if (PRE->isClassReceiver())
7541 DiagnoseDeclAvailability(PRE->getClassReceiver(), PRE->getReceiverLocation());
7542 return true;
7543 }
7544
Erik Pilkington5cd57172016-08-16 17:44:11 +00007545 bool VisitObjCMessageExpr(ObjCMessageExpr *Msg) {
7546 if (ObjCMethodDecl *D = Msg->getMethodDecl())
7547 DiagnoseDeclAvailability(
7548 D, SourceRange(Msg->getSelectorStartLoc(), Msg->getLocEnd()));
7549 return true;
7550 }
7551
7552 bool VisitDeclRefExpr(DeclRefExpr *DRE) {
7553 DiagnoseDeclAvailability(DRE->getDecl(),
7554 SourceRange(DRE->getLocStart(), DRE->getLocEnd()));
7555 return true;
7556 }
7557
7558 bool VisitMemberExpr(MemberExpr *ME) {
7559 DiagnoseDeclAvailability(ME->getMemberDecl(),
7560 SourceRange(ME->getLocStart(), ME->getLocEnd()));
7561 return true;
7562 }
7563
Alex Lorenz0a484ba2017-05-24 15:15:29 +00007564 bool VisitObjCAvailabilityCheckExpr(ObjCAvailabilityCheckExpr *E) {
7565 SemaRef.Diag(E->getLocStart(), diag::warn_at_available_unchecked_use)
7566 << (!SemaRef.getLangOpts().ObjC1);
7567 return true;
7568 }
7569
Erik Pilkington5cd57172016-08-16 17:44:11 +00007570 bool VisitTypeLoc(TypeLoc Ty);
7571};
7572
7573void DiagnoseUnguardedAvailability::DiagnoseDeclAvailability(
7574 NamedDecl *D, SourceRange Range) {
Erik Pilkington4042f3c2017-07-05 17:08:56 +00007575 AvailabilityResult Result;
7576 const NamedDecl *OffendingDecl;
7577 std::tie(Result, OffendingDecl) =
Erik Pilkington9f866a72017-07-18 20:32:07 +00007578 ShouldDiagnoseAvailabilityOfDecl(D, nullptr);
Erik Pilkington4042f3c2017-07-05 17:08:56 +00007579 if (Result != AR_Available) {
Erik Pilkington5cd57172016-08-16 17:44:11 +00007580 // All other diagnostic kinds have already been handled in
7581 // DiagnoseAvailabilityOfDecl.
7582 if (Result != AR_NotYetIntroduced)
7583 return;
7584
Erik Pilkington4042f3c2017-07-05 17:08:56 +00007585 const AvailabilityAttr *AA =
7586 getAttrForPlatform(SemaRef.getASTContext(), OffendingDecl);
Erik Pilkington5cd57172016-08-16 17:44:11 +00007587 VersionTuple Introduced = AA->getIntroduced();
7588
Erik Pilkington4042f3c2017-07-05 17:08:56 +00007589 if (AvailabilityStack.back() >= Introduced)
Erik Pilkingtonf35114c2016-10-25 19:05:50 +00007590 return;
7591
7592 // If the context of this function is less available than D, we should not
7593 // emit a diagnostic.
7594 if (!ShouldDiagnoseAvailabilityInContext(SemaRef, Result, Introduced, Ctx))
7595 return;
7596
Alex Lorenzc9a369f2017-06-22 17:02:24 +00007597 // We would like to emit the diagnostic even if -Wunguarded-availability is
7598 // not specified for deployment targets >= to iOS 11 or equivalent or
7599 // for declarations that were introduced in iOS 11 (macOS 10.13, ...) or
7600 // later.
7601 unsigned DiagKind =
7602 shouldDiagnoseAvailabilityByDefault(
7603 SemaRef.Context,
7604 SemaRef.Context.getTargetInfo().getPlatformMinVersion(), Introduced)
7605 ? diag::warn_unguarded_availability_new
7606 : diag::warn_unguarded_availability;
7607
7608 SemaRef.Diag(Range.getBegin(), DiagKind)
Erik Pilkington5cd57172016-08-16 17:44:11 +00007609 << Range << D
7610 << AvailabilityAttr::getPrettyPlatformName(
7611 SemaRef.getASTContext().getTargetInfo().getPlatformName())
7612 << Introduced.getAsString();
7613
Erik Pilkington4042f3c2017-07-05 17:08:56 +00007614 SemaRef.Diag(OffendingDecl->getLocation(),
7615 diag::note_availability_specified_here)
7616 << OffendingDecl << /* partial */ 3;
Erik Pilkington5cd57172016-08-16 17:44:11 +00007617
Alex Lorenz9c5c2bf2017-05-05 16:42:44 +00007618 auto FixitDiag =
7619 SemaRef.Diag(Range.getBegin(), diag::note_unguarded_available_silence)
7620 << Range << D
7621 << (SemaRef.getLangOpts().ObjC1 ? /*@available*/ 0
7622 : /*__builtin_available*/ 1);
7623
7624 // Find the statement which should be enclosed in the if @available check.
7625 if (StmtStack.empty())
7626 return;
7627 const Stmt *StmtOfUse = StmtStack.back();
7628 const CompoundStmt *Scope = nullptr;
7629 for (const Stmt *S : llvm::reverse(StmtStack)) {
7630 if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
7631 Scope = CS;
7632 break;
7633 }
7634 if (isBodyLikeChildStmt(StmtOfUse, S)) {
7635 // The declaration won't be seen outside of the statement, so we don't
7636 // have to wrap the uses of any declared variables in if (@available).
7637 // Therefore we can avoid setting Scope here.
7638 break;
7639 }
7640 StmtOfUse = S;
7641 }
7642 const Stmt *LastStmtOfUse = nullptr;
7643 if (isa<DeclStmt>(StmtOfUse) && Scope) {
7644 for (const Decl *D : cast<DeclStmt>(StmtOfUse)->decls()) {
7645 if (StmtUSEFinder::isContained(StmtStack.back(), D)) {
7646 LastStmtOfUse = LastDeclUSEFinder::findLastStmtThatUsesDecl(D, Scope);
7647 break;
7648 }
7649 }
7650 }
7651
7652 const SourceManager &SM = SemaRef.getSourceManager();
7653 SourceLocation IfInsertionLoc =
7654 SM.getExpansionLoc(StmtOfUse->getLocStart());
7655 SourceLocation StmtEndLoc =
7656 SM.getExpansionRange(
7657 (LastStmtOfUse ? LastStmtOfUse : StmtOfUse)->getLocEnd())
7658 .second;
7659 if (SM.getFileID(IfInsertionLoc) != SM.getFileID(StmtEndLoc))
7660 return;
7661
7662 StringRef Indentation = Lexer::getIndentationForLine(IfInsertionLoc, SM);
7663 const char *ExtraIndentation = " ";
7664 std::string FixItString;
7665 llvm::raw_string_ostream FixItOS(FixItString);
7666 FixItOS << "if (" << (SemaRef.getLangOpts().ObjC1 ? "@available"
7667 : "__builtin_available")
Alex Lorenze1fb64e2017-05-09 15:34:46 +00007668 << "("
7669 << AvailabilityAttr::getPlatformNameSourceSpelling(
7670 SemaRef.getASTContext().getTargetInfo().getPlatformName())
Alex Lorenz9c5c2bf2017-05-05 16:42:44 +00007671 << " " << Introduced.getAsString() << ", *)) {\n"
7672 << Indentation << ExtraIndentation;
7673 FixitDiag << FixItHint::CreateInsertion(IfInsertionLoc, FixItOS.str());
7674 SourceLocation ElseInsertionLoc = Lexer::findLocationAfterToken(
7675 StmtEndLoc, tok::semi, SM, SemaRef.getLangOpts(),
7676 /*SkipTrailingWhitespaceAndNewLine=*/false);
7677 if (ElseInsertionLoc.isInvalid())
7678 ElseInsertionLoc =
7679 Lexer::getLocForEndOfToken(StmtEndLoc, 0, SM, SemaRef.getLangOpts());
7680 FixItOS.str().clear();
7681 FixItOS << "\n"
7682 << Indentation << "} else {\n"
7683 << Indentation << ExtraIndentation
7684 << "// Fallback on earlier versions\n"
7685 << Indentation << "}";
7686 FixitDiag << FixItHint::CreateInsertion(ElseInsertionLoc, FixItOS.str());
Erik Pilkington5cd57172016-08-16 17:44:11 +00007687 }
7688}
7689
7690bool DiagnoseUnguardedAvailability::VisitTypeLoc(TypeLoc Ty) {
7691 const Type *TyPtr = Ty.getTypePtr();
7692 SourceRange Range{Ty.getBeginLoc(), Ty.getEndLoc()};
7693
Erik Pilkington6ac77a62017-05-22 15:41:12 +00007694 if (Range.isInvalid())
7695 return true;
7696
Erik Pilkington5cd57172016-08-16 17:44:11 +00007697 if (const TagType *TT = dyn_cast<TagType>(TyPtr)) {
7698 TagDecl *TD = TT->getDecl();
7699 DiagnoseDeclAvailability(TD, Range);
7700
7701 } else if (const TypedefType *TD = dyn_cast<TypedefType>(TyPtr)) {
7702 TypedefNameDecl *D = TD->getDecl();
7703 DiagnoseDeclAvailability(D, Range);
7704
7705 } else if (const auto *ObjCO = dyn_cast<ObjCObjectType>(TyPtr)) {
7706 if (NamedDecl *D = ObjCO->getInterface())
7707 DiagnoseDeclAvailability(D, Range);
7708 }
7709
7710 return true;
7711}
7712
7713bool DiagnoseUnguardedAvailability::TraverseIfStmt(IfStmt *If) {
7714 VersionTuple CondVersion;
7715 if (auto *E = dyn_cast<ObjCAvailabilityCheckExpr>(If->getCond())) {
7716 CondVersion = E->getVersion();
7717
7718 // If we're using the '*' case here or if this check is redundant, then we
7719 // use the enclosing version to check both branches.
7720 if (CondVersion.empty() || CondVersion <= AvailabilityStack.back())
Alex Lorenz98f9fcd2017-08-17 14:22:27 +00007721 return TraverseStmt(If->getThen()) && TraverseStmt(If->getElse());
Erik Pilkington5cd57172016-08-16 17:44:11 +00007722 } else {
7723 // This isn't an availability checking 'if', we can just continue.
7724 return Base::TraverseIfStmt(If);
7725 }
7726
7727 AvailabilityStack.push_back(CondVersion);
7728 bool ShouldContinue = TraverseStmt(If->getThen());
7729 AvailabilityStack.pop_back();
7730
7731 return ShouldContinue && TraverseStmt(If->getElse());
7732}
7733
7734} // end anonymous namespace
7735
7736void Sema::DiagnoseUnguardedAvailabilityViolations(Decl *D) {
7737 Stmt *Body = nullptr;
7738
7739 if (auto *FD = D->getAsFunction()) {
7740 // FIXME: We only examine the pattern decl for availability violations now,
7741 // but we should also examine instantiated templates.
7742 if (FD->isTemplateInstantiation())
7743 return;
7744
7745 Body = FD->getBody();
7746 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(D))
7747 Body = MD->getBody();
Alex Lorenz28559ce2017-04-26 14:20:02 +00007748 else if (auto *BD = dyn_cast<BlockDecl>(D))
7749 Body = BD->getBody();
Erik Pilkington5cd57172016-08-16 17:44:11 +00007750
7751 assert(Body && "Need a body here!");
7752
Erik Pilkingtonf35114c2016-10-25 19:05:50 +00007753 DiagnoseUnguardedAvailability(*this, D).IssueDiagnostics(Body);
Erik Pilkington5cd57172016-08-16 17:44:11 +00007754}
Erik Pilkington9f866a72017-07-18 20:32:07 +00007755
7756void Sema::DiagnoseAvailabilityOfDecl(NamedDecl *D, SourceLocation Loc,
7757 const ObjCInterfaceDecl *UnknownObjCClass,
7758 bool ObjCPropertyAccess,
7759 bool AvoidPartialAvailabilityChecks) {
7760 std::string Message;
7761 AvailabilityResult Result;
7762 const NamedDecl* OffendingDecl;
7763 // See if this declaration is unavailable, deprecated, or partial.
7764 std::tie(Result, OffendingDecl) = ShouldDiagnoseAvailabilityOfDecl(D, &Message);
7765 if (Result == AR_Available)
7766 return;
7767
7768 if (Result == AR_NotYetIntroduced) {
7769 if (AvoidPartialAvailabilityChecks)
7770 return;
7771
7772 // We need to know the @available context in the current function to
7773 // diagnose this use, let DiagnoseUnguardedAvailabilityViolations do that
7774 // when we're done parsing the current function.
7775 if (getCurFunctionOrMethodDecl()) {
7776 getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
7777 return;
7778 } else if (getCurBlock() || getCurLambda()) {
7779 getCurFunction()->HasPotentialAvailabilityViolations = true;
7780 return;
7781 }
7782 }
7783
7784 const ObjCPropertyDecl *ObjCPDecl = nullptr;
7785 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
7786 if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
7787 AvailabilityResult PDeclResult = PD->getAvailability(nullptr);
7788 if (PDeclResult == Result)
7789 ObjCPDecl = PD;
7790 }
7791 }
7792
7793 EmitAvailabilityWarning(*this, Result, D, OffendingDecl, Message, Loc,
7794 UnknownObjCClass, ObjCPDecl, ObjCPropertyAccess);
7795}