blob: ff63d7b1ce681ed07e274becd00cc6d16e0803b4 [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"
Chris Lattner30ba6742009-08-10 19:03:04 +000035#include "llvm/ADT/StringExtras.h"
Hal Finkelee90a222014-09-26 05:04:30 +000036#include "llvm/Support/MathExtras.h"
Eugene Zelenko1ced5092016-02-12 22:53:10 +000037
Chris Lattner2c6fcf52008-06-26 18:38:35 +000038using namespace clang;
John McCallb45a1e72010-08-26 02:13:20 +000039using namespace sema;
Chris Lattner2c6fcf52008-06-26 18:38:35 +000040
Aaron Ballmandf8fe4c2013-11-24 21:35:16 +000041namespace AttributeLangSupport {
NAKAMURA Takumi01d27f92013-11-25 00:52:29 +000042 enum LANG {
Aaron Ballmandf8fe4c2013-11-24 21:35:16 +000043 C,
44 Cpp,
45 ObjC
46 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +000047} // end namespace AttributeLangSupport
Aaron Ballmandf8fe4c2013-11-24 21:35:16 +000048
Chris Lattner58418ff2008-06-29 00:16:31 +000049//===----------------------------------------------------------------------===//
50// Helper functions
51//===----------------------------------------------------------------------===//
52
Ted Kremenek527042b2009-08-14 20:49:40 +000053/// isFunctionOrMethod - Return true if the given decl has function
Daniel Dunbar70e3eba2008-10-19 02:04:16 +000054/// type (function or function-typed variable) or an Objective-C
55/// method.
Chandler Carruthff4c4f02011-07-01 23:49:12 +000056static bool isFunctionOrMethod(const Decl *D) {
Craig Topperc3ec1492014-05-26 06:22:03 +000057 return (D->getFunctionType() != nullptr) || isa<ObjCMethodDecl>(D);
Fariborz Jahanian4447e172009-05-15 23:15:03 +000058}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000059
David Majnemer06864812015-04-07 06:01:53 +000060/// \brief Return true if the given decl has function type (function or
61/// function-typed variable) or an Objective-C method or a block.
62static bool isFunctionOrMethodOrBlock(const Decl *D) {
63 return isFunctionOrMethod(D) || isa<BlockDecl>(D);
64}
Fariborz Jahanian4447e172009-05-15 23:15:03 +000065
John McCall3882ace2011-01-05 12:14:39 +000066/// Return true if the given decl has a declarator that should have
67/// been processed by Sema::GetTypeForDeclarator.
Chandler Carruthff4c4f02011-07-01 23:49:12 +000068static bool hasDeclarator(const Decl *D) {
John McCall31168b02011-06-15 23:02:42 +000069 // In some sense, TypedefDecl really *ought* to be a DeclaratorDecl.
Chandler Carruthff4c4f02011-07-01 23:49:12 +000070 return isa<DeclaratorDecl>(D) || isa<BlockDecl>(D) || isa<TypedefNameDecl>(D) ||
71 isa<ObjCPropertyDecl>(D);
John McCall3882ace2011-01-05 12:14:39 +000072}
73
Daniel Dunbar70e3eba2008-10-19 02:04:16 +000074/// hasFunctionProto - Return true if the given decl has a argument
75/// information. This decl should have already passed
Fariborz Jahanian4447e172009-05-15 23:15:03 +000076/// isFunctionOrMethod or isFunctionOrMethodOrBlock.
Chandler Carruthff4c4f02011-07-01 23:49:12 +000077static bool hasFunctionProto(const Decl *D) {
Aaron Ballman12b9f652014-01-16 13:55:42 +000078 if (const FunctionType *FnTy = D->getFunctionType())
Douglas Gregordeaad8c2009-02-26 23:50:07 +000079 return isa<FunctionProtoType>(FnTy);
Aaron Ballman12b9f652014-01-16 13:55:42 +000080 return isa<ObjCMethodDecl>(D) || isa<BlockDecl>(D);
Daniel Dunbar70e3eba2008-10-19 02:04:16 +000081}
82
Alp Toker601b22c2014-01-21 23:35:24 +000083/// getFunctionOrMethodNumParams - Return number of function or method
84/// parameters. It is an error to call this on a K&R function (use
Daniel Dunbar70e3eba2008-10-19 02:04:16 +000085/// hasFunctionProto first).
Alp Toker601b22c2014-01-21 23:35:24 +000086static unsigned getFunctionOrMethodNumParams(const Decl *D) {
Aaron Ballman12b9f652014-01-16 13:55:42 +000087 if (const FunctionType *FnTy = D->getFunctionType())
Alp Toker9cacbab2014-01-20 20:26:09 +000088 return cast<FunctionProtoType>(FnTy)->getNumParams();
Chandler Carruthff4c4f02011-07-01 23:49:12 +000089 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
Fariborz Jahanian960910a2009-05-19 17:08:59 +000090 return BD->getNumParams();
Chandler Carruthff4c4f02011-07-01 23:49:12 +000091 return cast<ObjCMethodDecl>(D)->param_size();
Daniel Dunbarc136e0c2008-09-26 04:12:28 +000092}
93
Alp Toker601b22c2014-01-21 23:35:24 +000094static QualType getFunctionOrMethodParamType(const Decl *D, unsigned Idx) {
Aaron Ballman12b9f652014-01-16 13:55:42 +000095 if (const FunctionType *FnTy = D->getFunctionType())
Alp Toker9cacbab2014-01-20 20:26:09 +000096 return cast<FunctionProtoType>(FnTy)->getParamType(Idx);
Chandler Carruthff4c4f02011-07-01 23:49:12 +000097 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
Fariborz Jahanian960910a2009-05-19 17:08:59 +000098 return BD->getParamDecl(Idx)->getType();
Mike Stumpd3bb5572009-07-24 19:02:52 +000099
Alp Toker03376dc2014-07-07 09:02:20 +0000100 return cast<ObjCMethodDecl>(D)->parameters()[Idx]->getType();
Daniel Dunbarc136e0c2008-09-26 04:12:28 +0000101}
102
Aaron Ballman4bfa0de2014-08-01 12:58:11 +0000103static SourceRange getFunctionOrMethodParamRange(const Decl *D, unsigned Idx) {
104 if (const auto *FD = dyn_cast<FunctionDecl>(D))
105 return FD->getParamDecl(Idx)->getSourceRange();
Aaron Ballmane13d0092014-08-01 17:02:34 +0000106 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
Aaron Ballman4bfa0de2014-08-01 12:58:11 +0000107 return MD->parameters()[Idx]->getSourceRange();
Aaron Ballmane13d0092014-08-01 17:02:34 +0000108 if (const auto *BD = dyn_cast<BlockDecl>(D))
Aaron Ballman4bfa0de2014-08-01 12:58:11 +0000109 return BD->getParamDecl(Idx)->getSourceRange();
110 return SourceRange();
111}
112
Chandler Carruthff4c4f02011-07-01 23:49:12 +0000113static QualType getFunctionOrMethodResultType(const Decl *D) {
Aaron Ballman12b9f652014-01-16 13:55:42 +0000114 if (const FunctionType *FnTy = D->getFunctionType())
Aaron Ballman6288d062014-07-11 16:31:29 +0000115 return cast<FunctionType>(FnTy)->getReturnType();
Alp Toker314cc812014-01-25 16:55:45 +0000116 return cast<ObjCMethodDecl>(D)->getReturnType();
Fariborz Jahanianf1c25022009-05-20 17:41:43 +0000117}
118
Aaron Ballman4bfa0de2014-08-01 12:58:11 +0000119static SourceRange getFunctionOrMethodResultSourceRange(const Decl *D) {
120 if (const auto *FD = dyn_cast<FunctionDecl>(D))
121 return FD->getReturnTypeSourceRange();
Aaron Ballmane13d0092014-08-01 17:02:34 +0000122 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
Aaron Ballman4bfa0de2014-08-01 12:58:11 +0000123 return MD->getReturnTypeSourceRange();
124 return SourceRange();
125}
126
Chandler Carruthff4c4f02011-07-01 23:49:12 +0000127static bool isFunctionOrMethodVariadic(const Decl *D) {
Aaron Ballman12b9f652014-01-16 13:55:42 +0000128 if (const FunctionType *FnTy = D->getFunctionType()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000129 const FunctionProtoType *proto = cast<FunctionProtoType>(FnTy);
Daniel Dunbarc136e0c2008-09-26 04:12:28 +0000130 return proto->isVariadic();
Daniel Dunbarc136e0c2008-09-26 04:12:28 +0000131 }
Aaron Ballmane13d0092014-08-01 17:02:34 +0000132 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
133 return BD->isVariadic();
134
135 return cast<ObjCMethodDecl>(D)->isVariadic();
Daniel Dunbarc136e0c2008-09-26 04:12:28 +0000136}
137
Chandler Carruthff4c4f02011-07-01 23:49:12 +0000138static bool isInstanceMethod(const Decl *D) {
139 if (const CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D))
Chandler Carruth743682b2010-11-16 08:35:43 +0000140 return MethodDecl->isInstance();
141 return false;
142}
143
Chris Lattner2c6fcf52008-06-26 18:38:35 +0000144static inline bool isNSStringType(QualType T, ASTContext &Ctx) {
John McCall9dd450b2009-09-21 23:43:11 +0000145 const ObjCObjectPointerType *PT = T->getAs<ObjCObjectPointerType>();
Chris Lattner574dee62008-07-26 22:17:49 +0000146 if (!PT)
Chris Lattner2c6fcf52008-06-26 18:38:35 +0000147 return false;
Mike Stumpd3bb5572009-07-24 19:02:52 +0000148
John McCall96fa4842010-05-17 21:00:27 +0000149 ObjCInterfaceDecl *Cls = PT->getObjectType()->getInterface();
150 if (!Cls)
Chris Lattner2c6fcf52008-06-26 18:38:35 +0000151 return false;
Mike Stumpd3bb5572009-07-24 19:02:52 +0000152
John McCall96fa4842010-05-17 21:00:27 +0000153 IdentifierInfo* ClsName = Cls->getIdentifier();
Mike Stumpd3bb5572009-07-24 19:02:52 +0000154
Chris Lattner2c6fcf52008-06-26 18:38:35 +0000155 // FIXME: Should we walk the chain of classes?
156 return ClsName == &Ctx.Idents.get("NSString") ||
157 ClsName == &Ctx.Idents.get("NSMutableString");
158}
159
Daniel Dunbar980c6692008-09-26 03:32:58 +0000160static inline bool isCFStringType(QualType T, ASTContext &Ctx) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000161 const PointerType *PT = T->getAs<PointerType>();
Daniel Dunbar980c6692008-09-26 03:32:58 +0000162 if (!PT)
163 return false;
164
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000165 const RecordType *RT = PT->getPointeeType()->getAs<RecordType>();
Daniel Dunbar980c6692008-09-26 03:32:58 +0000166 if (!RT)
167 return false;
Mike Stumpd3bb5572009-07-24 19:02:52 +0000168
Daniel Dunbar980c6692008-09-26 03:32:58 +0000169 const RecordDecl *RD = RT->getDecl();
Abramo Bagnara6150c882010-05-11 21:36:43 +0000170 if (RD->getTagKind() != TTK_Struct)
Daniel Dunbar980c6692008-09-26 03:32:58 +0000171 return false;
172
173 return RD->getIdentifier() == &Ctx.Idents.get("__CFString");
174}
175
Richard Smithb87c4652013-10-31 21:23:20 +0000176static unsigned getNumAttributeArgs(const AttributeList &Attr) {
177 // FIXME: Include the type in the argument list.
178 return Attr.getNumArgs() + Attr.hasParsedType();
179}
180
Aaron Ballman8ed8dbd2014-07-31 16:37:04 +0000181template <typename Compare>
182static bool checkAttributeNumArgsImpl(Sema &S, const AttributeList &Attr,
183 unsigned Num, unsigned Diag,
184 Compare Comp) {
185 if (Comp(getNumAttributeArgs(Attr), Num)) {
186 S.Diag(Attr.getLoc(), Diag) << Attr.getName() << Num;
Chandler Carruthfcc48d92011-07-11 23:30:35 +0000187 return false;
188 }
189
190 return true;
191}
192
Aaron Ballman8ed8dbd2014-07-31 16:37:04 +0000193/// \brief Check if the attribute has exactly as many args as Num. May
194/// output an error.
195static bool checkAttributeNumArgs(Sema &S, const AttributeList &Attr,
196 unsigned Num) {
197 return checkAttributeNumArgsImpl(S, Attr, Num,
198 diag::err_attribute_wrong_number_arguments,
199 std::not_equal_to<unsigned>());
200}
201
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000202/// \brief Check if the attribute has at least as many args as Num. May
203/// output an error.
204static bool checkAttributeAtLeastNumArgs(Sema &S, const AttributeList &Attr,
Richard Smithb87c4652013-10-31 21:23:20 +0000205 unsigned Num) {
Aaron Ballman8ed8dbd2014-07-31 16:37:04 +0000206 return checkAttributeNumArgsImpl(S, Attr, Num,
207 diag::err_attribute_too_few_arguments,
208 std::less<unsigned>());
209}
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000210
Aaron Ballman8ed8dbd2014-07-31 16:37:04 +0000211/// \brief Check if the attribute has at most as many args as Num. May
212/// output an error.
213static bool checkAttributeAtMostNumArgs(Sema &S, const AttributeList &Attr,
214 unsigned Num) {
215 return checkAttributeNumArgsImpl(S, Attr, Num,
216 diag::err_attribute_too_many_arguments,
217 std::greater<unsigned>());
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000218}
219
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +0000220/// \brief If Expr is a valid integer constant, get the value of the integer
221/// expression and return success or failure. May output an error.
222static bool checkUInt32Argument(Sema &S, const AttributeList &Attr,
223 const Expr *Expr, uint32_t &Val,
224 unsigned Idx = UINT_MAX) {
225 llvm::APSInt I(32);
226 if (Expr->isTypeDependent() || Expr->isValueDependent() ||
227 !Expr->isIntegerConstantExpr(I, S.Context)) {
228 if (Idx != UINT_MAX)
229 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
230 << Attr.getName() << Idx << AANT_ArgumentIntegerConstant
231 << Expr->getSourceRange();
232 else
233 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
234 << Attr.getName() << AANT_ArgumentIntegerConstant
235 << Expr->getSourceRange();
236 return false;
237 }
Aaron Ballmanadfdde52014-07-22 14:09:34 +0000238
239 if (!I.isIntN(32)) {
Aaron Ballman31f42312014-07-24 14:51:23 +0000240 S.Diag(Expr->getExprLoc(), diag::err_ice_too_large)
241 << I.toString(10, false) << 32 << /* Unsigned */ 1;
Aaron Ballmanadfdde52014-07-22 14:09:34 +0000242 return false;
243 }
244
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +0000245 Val = (uint32_t)I.getZExtValue();
246 return true;
247}
248
Aaron Ballmanfb763042013-12-02 18:05:46 +0000249/// \brief Diagnose mutually exclusive attributes when present on a given
250/// declaration. Returns true if diagnosed.
251template <typename AttrTy>
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +0000252static bool checkAttrMutualExclusion(Sema &S, Decl *D, SourceRange Range,
253 IdentifierInfo *Ident) {
Aaron Ballman2cfbc002014-01-03 16:23:46 +0000254 if (AttrTy *A = D->getAttr<AttrTy>()) {
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +0000255 S.Diag(Range.getBegin(), diag::err_attributes_are_not_compatible) << Ident
256 << A;
257 S.Diag(A->getLocation(), diag::note_conflicting_attribute);
Aaron Ballmanfb763042013-12-02 18:05:46 +0000258 return true;
259 }
260 return false;
261}
262
Alp Toker601b22c2014-01-21 23:35:24 +0000263/// \brief Check if IdxExpr is a valid parameter index for a function or
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000264/// instance method D. May output an error.
265///
266/// \returns true if IdxExpr is a valid index.
Alp Toker601b22c2014-01-21 23:35:24 +0000267static bool checkFunctionOrMethodParameterIndex(Sema &S, const Decl *D,
268 const AttributeList &Attr,
269 unsigned AttrArgNum,
270 const Expr *IdxExpr,
271 uint64_t &Idx) {
David Majnemer06864812015-04-07 06:01:53 +0000272 assert(isFunctionOrMethodOrBlock(D));
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000273
274 // In C++ the implicit 'this' function parameter also counts.
275 // Parameters are counted from one.
Aaron Ballmanbe50eb82013-07-30 00:48:57 +0000276 bool HP = hasFunctionProto(D);
277 bool HasImplicitThisParam = isInstanceMethod(D);
278 bool IV = HP && isFunctionOrMethodVariadic(D);
Alp Toker601b22c2014-01-21 23:35:24 +0000279 unsigned NumParams =
280 (HP ? getFunctionOrMethodNumParams(D) : 0) + HasImplicitThisParam;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000281
282 llvm::APSInt IdxInt;
283 if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent() ||
284 !IdxExpr->isIntegerConstantExpr(IdxInt, S.Context)) {
Aaron Ballmanfaed0fa2013-12-26 16:30:30 +0000285 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
286 << Attr.getName() << AttrArgNum << AANT_ArgumentIntegerConstant
287 << IdxExpr->getSourceRange();
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000288 return false;
289 }
290
291 Idx = IdxInt.getLimitedValue();
Alp Toker601b22c2014-01-21 23:35:24 +0000292 if (Idx < 1 || (!IV && Idx > NumParams)) {
Aaron Ballmanfaed0fa2013-12-26 16:30:30 +0000293 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
294 << Attr.getName() << AttrArgNum << IdxExpr->getSourceRange();
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000295 return false;
296 }
297 Idx--; // Convert to zero-based.
298 if (HasImplicitThisParam) {
299 if (Idx == 0) {
Aaron Ballmanfaed0fa2013-12-26 16:30:30 +0000300 S.Diag(Attr.getLoc(),
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000301 diag::err_attribute_invalid_implicit_this_argument)
Aaron Ballmanfaed0fa2013-12-26 16:30:30 +0000302 << Attr.getName() << IdxExpr->getSourceRange();
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000303 return false;
304 }
305 --Idx;
306 }
307
308 return true;
309}
310
Aaron Ballman3b1dde62013-09-13 19:35:18 +0000311/// \brief Check if the argument \p ArgNum of \p Attr is a ASCII string literal.
312/// If not emit an error and return false. If the argument is an identifier it
313/// will emit an error with a fixit hint and treat it as if it was a string
314/// literal.
Tim Northover6a6b63b2013-10-01 14:34:18 +0000315bool Sema::checkStringLiteralArgumentAttr(const AttributeList &Attr,
316 unsigned ArgNum, StringRef &Str,
Tim Northovera484bc02013-10-01 14:34:25 +0000317 SourceLocation *ArgLocation) {
Aaron Ballman3b1dde62013-09-13 19:35:18 +0000318 // Look for identifiers. If we have one emit a hint to fix it to a literal.
319 if (Attr.isArgIdent(ArgNum)) {
320 IdentifierLoc *Loc = Attr.getArgAsIdent(ArgNum);
Tim Northover6a6b63b2013-10-01 14:34:18 +0000321 Diag(Loc->Loc, diag::err_attribute_argument_type)
Aaron Ballman3b1dde62013-09-13 19:35:18 +0000322 << Attr.getName() << AANT_ArgumentString
323 << FixItHint::CreateInsertion(Loc->Loc, "\"")
Craig Topper07fa1762015-11-15 02:31:46 +0000324 << FixItHint::CreateInsertion(getLocForEndOfToken(Loc->Loc), "\"");
Aaron Ballman3b1dde62013-09-13 19:35:18 +0000325 Str = Loc->Ident->getName();
326 if (ArgLocation)
327 *ArgLocation = Loc->Loc;
328 return true;
329 }
330
331 // Now check for an actual string literal.
332 Expr *ArgExpr = Attr.getArgAsExpr(ArgNum);
333 StringLiteral *Literal = dyn_cast<StringLiteral>(ArgExpr->IgnoreParenCasts());
334 if (ArgLocation)
335 *ArgLocation = ArgExpr->getLocStart();
336
337 if (!Literal || !Literal->isAscii()) {
Tim Northover6a6b63b2013-10-01 14:34:18 +0000338 Diag(ArgExpr->getLocStart(), diag::err_attribute_argument_type)
Aaron Ballman3b1dde62013-09-13 19:35:18 +0000339 << Attr.getName() << AANT_ArgumentString;
340 return false;
341 }
342
343 Str = Literal->getString();
344 return true;
345}
346
Aaron Ballman6f9165a2013-11-27 15:24:06 +0000347/// \brief Applies the given attribute to the Decl without performing any
348/// additional semantic checking.
349template <typename AttrType>
350static void handleSimpleAttribute(Sema &S, Decl *D,
351 const AttributeList &Attr) {
352 D->addAttr(::new (S.Context) AttrType(Attr.getRange(), S.Context,
353 Attr.getAttributeSpellingListIndex()));
354}
355
Justin Lebar3eaaf862016-01-13 01:07:35 +0000356template <typename AttrType>
357static void handleSimpleAttributeWithExclusions(Sema &S, Decl *D,
358 const AttributeList &Attr) {
359 handleSimpleAttribute<AttrType>(S, D, Attr);
360}
361
362/// \brief Applies the given attribute to the Decl so long as the Decl doesn't
363/// already have one of the given incompatible attributes.
364template <typename AttrType, typename IncompatibleAttrType,
365 typename... IncompatibleAttrTypes>
366static void handleSimpleAttributeWithExclusions(Sema &S, Decl *D,
367 const AttributeList &Attr) {
368 if (checkAttrMutualExclusion<IncompatibleAttrType>(S, D, Attr.getRange(),
369 Attr.getName()))
370 return;
371 handleSimpleAttributeWithExclusions<AttrType, IncompatibleAttrTypes...>(S, D,
372 Attr);
373}
374
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000375/// \brief Check if the passed-in expression is of type int or bool.
376static bool isIntOrBool(Expr *Exp) {
377 QualType QT = Exp->getType();
378 return QT->isBooleanType() || QT->isIntegerType();
379}
380
DeLesley Hutchinse09be232012-04-23 18:39:55 +0000381
382// Check to see if the type is a smart pointer of some kind. We assume
383// it's a smart pointer if it defines both operator-> and operator*.
DeLesley Hutchins90ff4682012-05-02 22:18:42 +0000384static bool threadSafetyCheckIsSmartPointer(Sema &S, const RecordType* RT) {
Richard Smithcf4bdde2015-02-21 02:45:19 +0000385 DeclContextLookupResult Res1 = RT->getDecl()->lookup(
386 S.Context.DeclarationNames.getCXXOperatorName(OO_Star));
David Blaikieff7d47a2012-12-19 00:45:41 +0000387 if (Res1.empty())
DeLesley Hutchins90ff4682012-05-02 22:18:42 +0000388 return false;
DeLesley Hutchinse09be232012-04-23 18:39:55 +0000389
Richard Smithcf4bdde2015-02-21 02:45:19 +0000390 DeclContextLookupResult Res2 = RT->getDecl()->lookup(
391 S.Context.DeclarationNames.getCXXOperatorName(OO_Arrow));
David Blaikieff7d47a2012-12-19 00:45:41 +0000392 if (Res2.empty())
DeLesley Hutchins90ff4682012-05-02 22:18:42 +0000393 return false;
394
395 return true;
DeLesley Hutchinse09be232012-04-23 18:39:55 +0000396}
397
Caitlin Sadowskiaac4d212011-07-28 17:21:07 +0000398/// \brief Check if passed in Decl is a pointer type.
399/// Note that this function may produce an error message.
400/// \return true if the Decl is a pointer type; false otherwise
DeLesley Hutchins8d11c792012-04-19 16:10:44 +0000401static bool threadSafetyCheckIsPointer(Sema &S, const Decl *D,
402 const AttributeList &Attr) {
Aaron Ballman553e6812013-12-26 14:54:11 +0000403 const ValueDecl *vd = cast<ValueDecl>(D);
404 QualType QT = vd->getType();
405 if (QT->isAnyPointerType())
406 return true;
407
408 if (const RecordType *RT = QT->getAs<RecordType>()) {
409 // If it's an incomplete type, it could be a smart pointer; skip it.
410 // (We don't want to force template instantiation if we can avoid it,
411 // since that would alter the order in which templates are instantiated.)
412 if (RT->isIncompleteType())
Caitlin Sadowskiaac4d212011-07-28 17:21:07 +0000413 return true;
DeLesley Hutchinse09be232012-04-23 18:39:55 +0000414
Aaron Ballman553e6812013-12-26 14:54:11 +0000415 if (threadSafetyCheckIsSmartPointer(S, RT))
416 return true;
Caitlin Sadowskiaac4d212011-07-28 17:21:07 +0000417 }
Aaron Ballman553e6812013-12-26 14:54:11 +0000418
419 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_decl_not_pointer)
Aaron Ballman68289452013-12-26 15:06:01 +0000420 << Attr.getName() << QT;
Caitlin Sadowskiaac4d212011-07-28 17:21:07 +0000421 return false;
422}
423
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000424/// \brief Checks that the passed in QualType either is of RecordType or points
425/// to RecordType. Returns the relevant RecordType, null if it does not exit.
Benjamin Kramer56b675f2011-08-19 04:18:11 +0000426static const RecordType *getRecordType(QualType QT) {
427 if (const RecordType *RT = QT->getAs<RecordType>())
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000428 return RT;
Benjamin Kramer56b675f2011-08-19 04:18:11 +0000429
430 // Now check if we point to record type.
431 if (const PointerType *PT = QT->getAs<PointerType>())
432 return PT->getPointeeType()->getAs<RecordType>();
433
Craig Topperc3ec1492014-05-26 06:22:03 +0000434 return nullptr;
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000435}
436
Aaron Ballman76050722014-04-04 15:13:57 +0000437static bool checkRecordTypeForCapability(Sema &S, QualType Ty) {
DeLesley Hutchins481d5ab2012-04-06 20:02:30 +0000438 const RecordType *RT = getRecordType(Ty);
Michael Hana9171bc2012-08-03 17:40:43 +0000439
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000440 if (!RT)
441 return false;
DeLesley Hutchins90ff4682012-05-02 22:18:42 +0000442
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000443 // Don't check for the capability if the class hasn't been defined yet.
DeLesley Hutchins3509f292012-02-16 17:15:51 +0000444 if (RT->isIncompleteType())
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000445 return true;
DeLesley Hutchins90ff4682012-05-02 22:18:42 +0000446
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000447 // Allow smart pointers to be used as capability objects.
DeLesley Hutchins90ff4682012-05-02 22:18:42 +0000448 // FIXME -- Check the type that the smart pointer points to.
449 if (threadSafetyCheckIsSmartPointer(S, RT))
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000450 return true;
DeLesley Hutchins90ff4682012-05-02 22:18:42 +0000451
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000452 // Check if the record itself has a capability.
DeLesley Hutchins5ff430c2012-05-04 16:28:38 +0000453 RecordDecl *RD = RT->getDecl();
Aaron Ballmanefe348e2014-02-18 17:36:50 +0000454 if (RD->hasAttr<CapabilityAttr>())
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000455 return true;
DeLesley Hutchins5ff430c2012-05-04 16:28:38 +0000456
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000457 // Else check if any base classes have a capability.
DeLesley Hutchins5ff430c2012-05-04 16:28:38 +0000458 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
459 CXXBasePaths BPaths(false, false);
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +0000460 if (CRD->lookupInBases([](const CXXBaseSpecifier *BS, CXXBasePath &) {
461 const auto *Type = BS->getType()->getAs<RecordType>();
462 return Type->getDecl()->hasAttr<CapabilityAttr>();
463 }, BPaths))
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000464 return true;
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000465 }
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000466 return false;
467}
468
Aaron Ballman76050722014-04-04 15:13:57 +0000469static bool checkTypedefTypeForCapability(QualType Ty) {
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000470 const auto *TD = Ty->getAs<TypedefType>();
471 if (!TD)
472 return false;
473
474 TypedefNameDecl *TN = TD->getDecl();
475 if (!TN)
476 return false;
477
478 return TN->hasAttr<CapabilityAttr>();
479}
480
Aaron Ballman76050722014-04-04 15:13:57 +0000481static bool typeHasCapability(Sema &S, QualType Ty) {
482 if (checkTypedefTypeForCapability(Ty))
483 return true;
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000484
Aaron Ballman76050722014-04-04 15:13:57 +0000485 if (checkRecordTypeForCapability(S, Ty))
486 return true;
DeLesley Hutchins5ff430c2012-05-04 16:28:38 +0000487
Aaron Ballman76050722014-04-04 15:13:57 +0000488 return false;
489}
490
491static bool isCapabilityExpr(Sema &S, const Expr *Ex) {
492 // Capability expressions are simple expressions involving the boolean logic
493 // operators &&, || or !, a simple DeclRefExpr, CastExpr or a ParenExpr. Once
494 // a DeclRefExpr is found, its type should be checked to determine whether it
495 // is a capability or not.
496
497 if (const auto *E = dyn_cast<DeclRefExpr>(Ex))
498 return typeHasCapability(S, E->getType());
499 else if (const auto *E = dyn_cast<CastExpr>(Ex))
500 return isCapabilityExpr(S, E->getSubExpr());
501 else if (const auto *E = dyn_cast<ParenExpr>(Ex))
502 return isCapabilityExpr(S, E->getSubExpr());
503 else if (const auto *E = dyn_cast<UnaryOperator>(Ex)) {
504 if (E->getOpcode() == UO_LNot)
505 return isCapabilityExpr(S, E->getSubExpr());
506 return false;
507 } else if (const auto *E = dyn_cast<BinaryOperator>(Ex)) {
508 if (E->getOpcode() == BO_LAnd || E->getOpcode() == BO_LOr)
509 return isCapabilityExpr(S, E->getLHS()) &&
510 isCapabilityExpr(S, E->getRHS());
511 return false;
512 }
513
514 return false;
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000515}
516
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000517/// \brief Checks that all attribute arguments, starting from Sidx, resolve to
518/// a capability object.
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000519/// \param Sidx The attribute argument index to start checking with.
520/// \param ParamIdxOk Whether an argument can be indexing into a function
521/// parameter list.
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000522static void checkAttrArgsAreCapabilityObjs(Sema &S, Decl *D,
523 const AttributeList &Attr,
524 SmallVectorImpl<Expr *> &Args,
525 int Sidx = 0,
526 bool ParamIdxOk = false) {
527 for (unsigned Idx = Sidx; Idx < Attr.getNumArgs(); ++Idx) {
Aaron Ballman00e99962013-08-31 01:11:41 +0000528 Expr *ArgExp = Attr.getArgAsExpr(Idx);
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000529
Caitlin Sadowski990d5712011-09-08 17:42:31 +0000530 if (ArgExp->isTypeDependent()) {
DeLesley Hutchins8d11c792012-04-19 16:10:44 +0000531 // FIXME -- need to check this again on template instantiation
Caitlin Sadowski990d5712011-09-08 17:42:31 +0000532 Args.push_back(ArgExp);
533 continue;
534 }
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000535
DeLesley Hutchins70b5e8e2012-04-23 16:45:01 +0000536 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(ArgExp)) {
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000537 if (StrLit->getLength() == 0 ||
Benjamin Kramerca9fe142013-09-13 16:30:12 +0000538 (StrLit->isAscii() && StrLit->getString() == StringRef("*"))) {
DeLesley Hutchins3c3d57b2012-08-31 21:57:32 +0000539 // Pass empty strings to the analyzer without warnings.
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000540 // Treat "*" as the universal lock.
DeLesley Hutchins3c3d57b2012-08-31 21:57:32 +0000541 Args.push_back(ArgExp);
DeLesley Hutchins70b5e8e2012-04-23 16:45:01 +0000542 continue;
DeLesley Hutchins3c3d57b2012-08-31 21:57:32 +0000543 }
DeLesley Hutchins70b5e8e2012-04-23 16:45:01 +0000544
DeLesley Hutchins8d11c792012-04-19 16:10:44 +0000545 // We allow constant strings to be used as a placeholder for expressions
546 // that are not valid C++ syntax, but warn that they are ignored.
547 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_ignored) <<
548 Attr.getName();
DeLesley Hutchins3c3d57b2012-08-31 21:57:32 +0000549 Args.push_back(ArgExp);
DeLesley Hutchins8d11c792012-04-19 16:10:44 +0000550 continue;
551 }
552
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000553 QualType ArgTy = ArgExp->getType();
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000554
DeLesley Hutchins70b5e8e2012-04-23 16:45:01 +0000555 // A pointer to member expression of the form &MyClass::mu is treated
556 // specially -- we need to look at the type of the member.
557 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(ArgExp))
558 if (UOp->getOpcode() == UO_AddrOf)
559 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(UOp->getSubExpr()))
560 if (DRE->getDecl()->isCXXInstanceMember())
561 ArgTy = DRE->getDecl()->getType();
562
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000563 // First see if we can just cast to record type, or pointer to record type.
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000564 const RecordType *RT = getRecordType(ArgTy);
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000565
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000566 // Now check if we index into a record type function param.
567 if(!RT && ParamIdxOk) {
568 FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000569 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(ArgExp);
570 if(FD && IL) {
571 unsigned int NumParams = FD->getNumParams();
572 llvm::APInt ArgValue = IL->getValue();
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000573 uint64_t ParamIdxFromOne = ArgValue.getZExtValue();
574 uint64_t ParamIdxFromZero = ParamIdxFromOne - 1;
575 if(!ArgValue.isStrictlyPositive() || ParamIdxFromOne > NumParams) {
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000576 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_range)
577 << Attr.getName() << Idx + 1 << NumParams;
DeLesley Hutchins8d11c792012-04-19 16:10:44 +0000578 continue;
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000579 }
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000580 ArgTy = FD->getParamDecl(ParamIdxFromZero)->getType();
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000581 }
582 }
583
Aaron Ballman76050722014-04-04 15:13:57 +0000584 // If the type does not have a capability, see if the components of the
585 // expression have capabilities. This allows for writing C code where the
586 // capability may be on the type, and the expression is a capability
587 // boolean logic expression. Eg) requires_capability(A || B && !C)
588 if (!typeHasCapability(S, ArgTy) && !isCapabilityExpr(S, ArgExp))
589 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_argument_not_lockable)
590 << Attr.getName() << ArgTy;
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000591
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000592 Args.push_back(ArgExp);
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000593 }
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000594}
595
Chris Lattner58418ff2008-06-29 00:16:31 +0000596//===----------------------------------------------------------------------===//
Chris Lattner58418ff2008-06-29 00:16:31 +0000597// Attribute Implementations
598//===----------------------------------------------------------------------===//
599
Michael Hana9171bc2012-08-03 17:40:43 +0000600static void handlePtGuardedVarAttr(Sema &S, Decl *D,
Michael Han99315932013-01-24 16:46:58 +0000601 const AttributeList &Attr) {
Michael Han3be3b442012-07-23 18:48:41 +0000602 if (!threadSafetyCheckIsPointer(S, D, Attr))
603 return;
604
Michael Han99315932013-01-24 16:46:58 +0000605 D->addAttr(::new (S.Context)
606 PtGuardedVarAttr(Attr.getRange(), S.Context,
607 Attr.getAttributeSpellingListIndex()));
Michael Han3be3b442012-07-23 18:48:41 +0000608}
609
Michael Hana9171bc2012-08-03 17:40:43 +0000610static bool checkGuardedByAttrCommon(Sema &S, Decl *D,
611 const AttributeList &Attr,
Michael Han3be3b442012-07-23 18:48:41 +0000612 Expr* &Arg) {
DeLesley Hutchins8d11c792012-04-19 16:10:44 +0000613 SmallVector<Expr*, 1> Args;
614 // check that all arguments are lockable objects
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000615 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
DeLesley Hutchins8d11c792012-04-19 16:10:44 +0000616 unsigned Size = Args.size();
617 if (Size != 1)
Michael Han3be3b442012-07-23 18:48:41 +0000618 return false;
Michael Hana9171bc2012-08-03 17:40:43 +0000619
Michael Han3be3b442012-07-23 18:48:41 +0000620 Arg = Args[0];
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000621
Michael Han3be3b442012-07-23 18:48:41 +0000622 return true;
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000623}
624
Michael Han3be3b442012-07-23 18:48:41 +0000625static void handleGuardedByAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000626 Expr *Arg = nullptr;
Michael Han3be3b442012-07-23 18:48:41 +0000627 if (!checkGuardedByAttrCommon(S, D, Attr, Arg))
628 return;
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000629
Aaron Ballman36a53502014-01-16 13:03:14 +0000630 D->addAttr(::new (S.Context) GuardedByAttr(Attr.getRange(), S.Context, Arg,
631 Attr.getAttributeSpellingListIndex()));
Michael Han3be3b442012-07-23 18:48:41 +0000632}
633
Michael Hana9171bc2012-08-03 17:40:43 +0000634static void handlePtGuardedByAttr(Sema &S, Decl *D,
Michael Han3be3b442012-07-23 18:48:41 +0000635 const AttributeList &Attr) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000636 Expr *Arg = nullptr;
Michael Han3be3b442012-07-23 18:48:41 +0000637 if (!checkGuardedByAttrCommon(S, D, Attr, Arg))
638 return;
639
640 if (!threadSafetyCheckIsPointer(S, D, Attr))
641 return;
642
643 D->addAttr(::new (S.Context) PtGuardedByAttr(Attr.getRange(),
Aaron Ballman36a53502014-01-16 13:03:14 +0000644 S.Context, Arg,
645 Attr.getAttributeSpellingListIndex()));
Michael Han3be3b442012-07-23 18:48:41 +0000646}
647
Michael Hana9171bc2012-08-03 17:40:43 +0000648static bool checkAcquireOrderAttrCommon(Sema &S, Decl *D,
649 const AttributeList &Attr,
Craig Topper5603df42013-07-05 19:34:19 +0000650 SmallVectorImpl<Expr *> &Args) {
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000651 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
Michael Han3be3b442012-07-23 18:48:41 +0000652 return false;
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000653
DeLesley Hutchins8d11c792012-04-19 16:10:44 +0000654 // Check that this attribute only applies to lockable types.
Aaron Ballmane61b8b82013-12-02 15:02:49 +0000655 QualType QT = cast<ValueDecl>(D)->getType();
DeLesley Hutchins2b504dc2015-09-29 16:24:18 +0000656 if (!QT->isDependentType() && !typeHasCapability(S, QT)) {
657 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_decl_not_lockable)
658 << Attr.getName();
659 return false;
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000660 }
661
DeLesley Hutchins8d11c792012-04-19 16:10:44 +0000662 // Check that all arguments are lockable objects.
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000663 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000664 if (Args.empty())
Michael Han3be3b442012-07-23 18:48:41 +0000665 return false;
Michael Hana9171bc2012-08-03 17:40:43 +0000666
Michael Han3be3b442012-07-23 18:48:41 +0000667 return true;
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000668}
669
Michael Hana9171bc2012-08-03 17:40:43 +0000670static void handleAcquiredAfterAttr(Sema &S, Decl *D,
Michael Han3be3b442012-07-23 18:48:41 +0000671 const AttributeList &Attr) {
672 SmallVector<Expr*, 1> Args;
673 if (!checkAcquireOrderAttrCommon(S, D, Attr, Args))
674 return;
675
676 Expr **StartArg = &Args[0];
Michael Han99315932013-01-24 16:46:58 +0000677 D->addAttr(::new (S.Context)
678 AcquiredAfterAttr(Attr.getRange(), S.Context,
679 StartArg, Args.size(),
680 Attr.getAttributeSpellingListIndex()));
Michael Han3be3b442012-07-23 18:48:41 +0000681}
682
Michael Hana9171bc2012-08-03 17:40:43 +0000683static void handleAcquiredBeforeAttr(Sema &S, Decl *D,
Michael Han3be3b442012-07-23 18:48:41 +0000684 const AttributeList &Attr) {
685 SmallVector<Expr*, 1> Args;
686 if (!checkAcquireOrderAttrCommon(S, D, Attr, Args))
687 return;
688
689 Expr **StartArg = &Args[0];
Michael Han99315932013-01-24 16:46:58 +0000690 D->addAttr(::new (S.Context)
691 AcquiredBeforeAttr(Attr.getRange(), S.Context,
692 StartArg, Args.size(),
693 Attr.getAttributeSpellingListIndex()));
Michael Han3be3b442012-07-23 18:48:41 +0000694}
695
Michael Hana9171bc2012-08-03 17:40:43 +0000696static bool checkLockFunAttrCommon(Sema &S, Decl *D,
697 const AttributeList &Attr,
Craig Topper5603df42013-07-05 19:34:19 +0000698 SmallVectorImpl<Expr *> &Args) {
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000699 // zero or more arguments ok
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000700 // check that all arguments are lockable objects
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000701 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 0, /*ParamIdxOk=*/true);
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000702
Michael Han3be3b442012-07-23 18:48:41 +0000703 return true;
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000704}
705
DeLesley Hutchinsb6824312013-05-17 23:02:59 +0000706static void handleAssertSharedLockAttr(Sema &S, Decl *D,
707 const AttributeList &Attr) {
708 SmallVector<Expr*, 1> Args;
709 if (!checkLockFunAttrCommon(S, D, Attr, Args))
710 return;
711
712 unsigned Size = Args.size();
Craig Topperc3ec1492014-05-26 06:22:03 +0000713 Expr **StartArg = Size == 0 ? nullptr : &Args[0];
DeLesley Hutchinsb6824312013-05-17 23:02:59 +0000714 D->addAttr(::new (S.Context)
715 AssertSharedLockAttr(Attr.getRange(), S.Context, StartArg, Size,
716 Attr.getAttributeSpellingListIndex()));
717}
718
719static void handleAssertExclusiveLockAttr(Sema &S, Decl *D,
720 const AttributeList &Attr) {
721 SmallVector<Expr*, 1> Args;
722 if (!checkLockFunAttrCommon(S, D, Attr, Args))
723 return;
724
725 unsigned Size = Args.size();
Craig Topperc3ec1492014-05-26 06:22:03 +0000726 Expr **StartArg = Size == 0 ? nullptr : &Args[0];
DeLesley Hutchinsb6824312013-05-17 23:02:59 +0000727 D->addAttr(::new (S.Context)
728 AssertExclusiveLockAttr(Attr.getRange(), S.Context,
729 StartArg, Size,
730 Attr.getAttributeSpellingListIndex()));
731}
732
733
Michael Hana9171bc2012-08-03 17:40:43 +0000734static bool checkTryLockFunAttrCommon(Sema &S, Decl *D,
735 const AttributeList &Attr,
Craig Topper5603df42013-07-05 19:34:19 +0000736 SmallVectorImpl<Expr *> &Args) {
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000737 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
Michael Han3be3b442012-07-23 18:48:41 +0000738 return false;
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000739
Aaron Ballman00e99962013-08-31 01:11:41 +0000740 if (!isIntOrBool(Attr.getArgAsExpr(0))) {
Aaron Ballman29982272013-07-23 14:03:57 +0000741 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
Aaron Ballman3bf758c2013-07-30 01:31:03 +0000742 << Attr.getName() << 1 << AANT_ArgumentIntOrBool;
Michael Han3be3b442012-07-23 18:48:41 +0000743 return false;
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000744 }
745
746 // check that all arguments are lockable objects
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000747 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 1);
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
Michael Hana9171bc2012-08-03 17:40:43 +0000752static void handleSharedTrylockFunctionAttr(Sema &S, Decl *D,
Michael Han3be3b442012-07-23 18:48:41 +0000753 const AttributeList &Attr) {
754 SmallVector<Expr*, 2> Args;
755 if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
756 return;
757
Michael Han99315932013-01-24 16:46:58 +0000758 D->addAttr(::new (S.Context)
759 SharedTrylockFunctionAttr(Attr.getRange(), S.Context,
Aaron Ballman00e99962013-08-31 01:11:41 +0000760 Attr.getArgAsExpr(0),
761 Args.data(), Args.size(),
Michael Han99315932013-01-24 16:46:58 +0000762 Attr.getAttributeSpellingListIndex()));
Michael Han3be3b442012-07-23 18:48:41 +0000763}
764
Michael Hana9171bc2012-08-03 17:40:43 +0000765static void handleExclusiveTrylockFunctionAttr(Sema &S, Decl *D,
Michael Han3be3b442012-07-23 18:48:41 +0000766 const AttributeList &Attr) {
767 SmallVector<Expr*, 2> Args;
768 if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
769 return;
770
Nico Weber462fd1e2015-01-07 23:50:05 +0000771 D->addAttr(::new (S.Context) ExclusiveTrylockFunctionAttr(
772 Attr.getRange(), S.Context, Attr.getArgAsExpr(0), Args.data(),
773 Args.size(), Attr.getAttributeSpellingListIndex()));
Michael Han3be3b442012-07-23 18:48:41 +0000774}
775
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000776static void handleLockReturnedAttr(Sema &S, Decl *D,
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000777 const AttributeList &Attr) {
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000778 // check that the argument is lockable object
DeLesley Hutchinsd96b46a2012-05-02 17:38:37 +0000779 SmallVector<Expr*, 1> Args;
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000780 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
DeLesley Hutchinsd96b46a2012-05-02 17:38:37 +0000781 unsigned Size = Args.size();
782 if (Size == 0)
783 return;
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000784
Michael Han99315932013-01-24 16:46:58 +0000785 D->addAttr(::new (S.Context)
786 LockReturnedAttr(Attr.getRange(), S.Context, Args[0],
787 Attr.getAttributeSpellingListIndex()));
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000788}
789
790static void handleLocksExcludedAttr(Sema &S, Decl *D,
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000791 const AttributeList &Attr) {
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000792 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000793 return;
794
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000795 // check that all arguments are lockable objects
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000796 SmallVector<Expr*, 1> Args;
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000797 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000798 unsigned Size = Args.size();
DeLesley Hutchins8d11c792012-04-19 16:10:44 +0000799 if (Size == 0)
800 return;
801 Expr **StartArg = &Args[0];
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000802
Michael Han99315932013-01-24 16:46:58 +0000803 D->addAttr(::new (S.Context)
804 LocksExcludedAttr(Attr.getRange(), S.Context, StartArg, Size,
805 Attr.getAttributeSpellingListIndex()));
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000806}
807
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000808static void handleEnableIfAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Saleem Abdulrasool046ba5b2016-02-18 06:49:31 +0000809 S.Diag(Attr.getLoc(), diag::ext_clang_enable_if);
810
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000811 Expr *Cond = Attr.getArgAsExpr(0);
812 if (!Cond->isTypeDependent()) {
813 ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
814 if (Converted.isInvalid())
815 return;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000816 Cond = Converted.get();
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000817 }
818
819 StringRef Msg;
820 if (!S.checkStringLiteralArgumentAttr(Attr, 1, Msg))
821 return;
822
823 SmallVector<PartialDiagnosticAt, 8> Diags;
824 if (!Cond->isValueDependent() &&
825 !Expr::isPotentialConstantExprUnevaluated(Cond, cast<FunctionDecl>(D),
826 Diags)) {
827 S.Diag(Attr.getLoc(), diag::err_enable_if_never_constant_expr);
828 for (int I = 0, N = Diags.size(); I != N; ++I)
829 S.Diag(Diags[I].first, Diags[I].second);
830 return;
831 }
832
833 D->addAttr(::new (S.Context)
834 EnableIfAttr(Attr.getRange(), S.Context, Cond, Msg,
835 Attr.getAttributeSpellingListIndex()));
836}
837
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000838static void handlePassObjectSizeAttr(Sema &S, Decl *D,
839 const AttributeList &Attr) {
840 if (D->hasAttr<PassObjectSizeAttr>()) {
841 S.Diag(D->getLocStart(), diag::err_attribute_only_once_per_parameter)
842 << Attr.getName();
843 return;
844 }
845
846 Expr *E = Attr.getArgAsExpr(0);
847 uint32_t Type;
848 if (!checkUInt32Argument(S, Attr, E, Type, /*Idx=*/1))
849 return;
850
851 // pass_object_size's argument is passed in as the second argument of
852 // __builtin_object_size. So, it has the same constraints as that second
853 // argument; namely, it must be in the range [0, 3].
854 if (Type > 3) {
855 S.Diag(E->getLocStart(), diag::err_attribute_argument_outof_range)
856 << Attr.getName() << 0 << 3 << E->getSourceRange();
857 return;
858 }
859
860 // pass_object_size is only supported on constant pointer parameters; as a
861 // kindness to users, we allow the parameter to be non-const for declarations.
862 // At this point, we have no clue if `D` belongs to a function declaration or
863 // definition, so we defer the constness check until later.
864 if (!cast<ParmVarDecl>(D)->getType()->isPointerType()) {
865 S.Diag(D->getLocStart(), diag::err_attribute_pointers_only)
866 << Attr.getName() << 1;
867 return;
868 }
869
870 D->addAttr(::new (S.Context)
871 PassObjectSizeAttr(Attr.getRange(), S.Context, (int)Type,
872 Attr.getAttributeSpellingListIndex()));
873}
874
DeLesley Hutchins5a715c42013-08-30 22:56:34 +0000875static void handleConsumableAttr(Sema &S, Decl *D, const AttributeList &Attr) {
David Blaikie16f76d22013-09-06 01:28:43 +0000876 ConsumableAttr::ConsumedState DefaultState;
877
878 if (Attr.isArgIdent(0)) {
Aaron Ballman682ee422013-09-11 19:47:58 +0000879 IdentifierLoc *IL = Attr.getArgAsIdent(0);
880 if (!ConsumableAttr::ConvertStrToConsumedState(IL->Ident->getName(),
881 DefaultState)) {
882 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported)
883 << Attr.getName() << IL->Ident;
David Blaikie16f76d22013-09-06 01:28:43 +0000884 return;
885 }
David Blaikie16f76d22013-09-06 01:28:43 +0000886 } else {
887 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
888 << Attr.getName() << AANT_ArgumentIdentifier;
889 return;
890 }
DeLesley Hutchins48a31762013-08-12 21:20:55 +0000891
892 D->addAttr(::new (S.Context)
David Blaikie16f76d22013-09-06 01:28:43 +0000893 ConsumableAttr(Attr.getRange(), S.Context, DefaultState,
DeLesley Hutchins5a715c42013-08-30 22:56:34 +0000894 Attr.getAttributeSpellingListIndex()));
895}
896
897static bool checkForConsumableClass(Sema &S, const CXXMethodDecl *MD,
898 const AttributeList &Attr) {
899 ASTContext &CurrContext = S.getASTContext();
900 QualType ThisType = MD->getThisType(CurrContext)->getPointeeType();
901
902 if (const CXXRecordDecl *RD = ThisType->getAsCXXRecordDecl()) {
903 if (!RD->hasAttr<ConsumableAttr>()) {
904 S.Diag(Attr.getLoc(), diag::warn_attr_on_unconsumable_class) <<
905 RD->getNameAsString();
906
907 return false;
908 }
909 }
910
911 return true;
912}
913
DeLesley Hutchins210791a2013-10-04 21:28:06 +0000914static void handleCallableWhenAttr(Sema &S, Decl *D,
915 const AttributeList &Attr) {
Aaron Ballmandbd586f2013-10-14 23:26:04 +0000916 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
917 return;
DeLesley Hutchins48a31762013-08-12 21:20:55 +0000918
DeLesley Hutchins5a715c42013-08-30 22:56:34 +0000919 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr))
920 return;
921
DeLesley Hutchins210791a2013-10-04 21:28:06 +0000922 SmallVector<CallableWhenAttr::ConsumedState, 3> States;
923 for (unsigned ArgIndex = 0; ArgIndex < Attr.getNumArgs(); ++ArgIndex) {
924 CallableWhenAttr::ConsumedState CallableState;
925
Aaron Ballman4c9b7dc2013-10-05 22:45:34 +0000926 StringRef StateString;
927 SourceLocation Loc;
Aaron Ballman55ef1512014-12-19 16:42:04 +0000928 if (Attr.isArgIdent(ArgIndex)) {
929 IdentifierLoc *Ident = Attr.getArgAsIdent(ArgIndex);
930 StateString = Ident->Ident->getName();
931 Loc = Ident->Loc;
932 } else {
933 if (!S.checkStringLiteralArgumentAttr(Attr, ArgIndex, StateString, &Loc))
934 return;
935 }
Aaron Ballman4c9b7dc2013-10-05 22:45:34 +0000936
937 if (!CallableWhenAttr::ConvertStrToConsumedState(StateString,
DeLesley Hutchins69391772013-10-17 23:23:53 +0000938 CallableState)) {
Aaron Ballman4c9b7dc2013-10-05 22:45:34 +0000939 S.Diag(Loc, diag::warn_attribute_type_not_supported)
940 << Attr.getName() << StateString;
DeLesley Hutchins210791a2013-10-04 21:28:06 +0000941 return;
942 }
Aaron Ballman4c9b7dc2013-10-05 22:45:34 +0000943
944 States.push_back(CallableState);
DeLesley Hutchins210791a2013-10-04 21:28:06 +0000945 }
946
DeLesley Hutchins48a31762013-08-12 21:20:55 +0000947 D->addAttr(::new (S.Context)
DeLesley Hutchins210791a2013-10-04 21:28:06 +0000948 CallableWhenAttr(Attr.getRange(), S.Context, States.data(),
949 States.size(), Attr.getAttributeSpellingListIndex()));
DeLesley Hutchins48a31762013-08-12 21:20:55 +0000950}
951
DeLesley Hutchins69391772013-10-17 23:23:53 +0000952static void handleParamTypestateAttr(Sema &S, Decl *D,
953 const AttributeList &Attr) {
DeLesley Hutchins69391772013-10-17 23:23:53 +0000954 ParamTypestateAttr::ConsumedState ParamState;
955
956 if (Attr.isArgIdent(0)) {
957 IdentifierLoc *Ident = Attr.getArgAsIdent(0);
958 StringRef StateString = Ident->Ident->getName();
959
960 if (!ParamTypestateAttr::ConvertStrToConsumedState(StateString,
961 ParamState)) {
962 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
963 << Attr.getName() << StateString;
964 return;
965 }
966 } else {
967 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
968 Attr.getName() << AANT_ArgumentIdentifier;
969 return;
970 }
971
972 // FIXME: This check is currently being done in the analysis. It can be
973 // enabled here only after the parser propagates attributes at
974 // template specialization definition, not declaration.
975 //QualType ReturnType = cast<ParmVarDecl>(D)->getType();
976 //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
977 //
978 //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
979 // S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
980 // ReturnType.getAsString();
981 // return;
982 //}
983
984 D->addAttr(::new (S.Context)
985 ParamTypestateAttr(Attr.getRange(), S.Context, ParamState,
986 Attr.getAttributeSpellingListIndex()));
987}
988
DeLesley Hutchinsfc368252013-09-03 20:11:38 +0000989static void handleReturnTypestateAttr(Sema &S, Decl *D,
990 const AttributeList &Attr) {
DeLesley Hutchinsfc368252013-09-03 20:11:38 +0000991 ReturnTypestateAttr::ConsumedState ReturnState;
992
993 if (Attr.isArgIdent(0)) {
Aaron Ballman682ee422013-09-11 19:47:58 +0000994 IdentifierLoc *IL = Attr.getArgAsIdent(0);
995 if (!ReturnTypestateAttr::ConvertStrToConsumedState(IL->Ident->getName(),
996 ReturnState)) {
997 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported)
998 << Attr.getName() << IL->Ident;
DeLesley Hutchinsfc368252013-09-03 20:11:38 +0000999 return;
1000 }
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001001 } else {
1002 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
1003 Attr.getName() << AANT_ArgumentIdentifier;
1004 return;
1005 }
1006
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001007 // FIXME: This check is currently being done in the analysis. It can be
1008 // enabled here only after the parser propagates attributes at
1009 // template specialization definition, not declaration.
1010 //QualType ReturnType;
1011 //
DeLesley Hutchins36ea1dd2013-10-17 22:53:04 +00001012 //if (const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D)) {
1013 // ReturnType = Param->getType();
1014 //
1015 //} else if (const CXXConstructorDecl *Constructor =
1016 // dyn_cast<CXXConstructorDecl>(D)) {
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001017 // ReturnType = Constructor->getThisType(S.getASTContext())->getPointeeType();
1018 //
1019 //} else {
1020 //
1021 // ReturnType = cast<FunctionDecl>(D)->getCallResultType();
1022 //}
1023 //
1024 //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
1025 //
1026 //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
1027 // S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
1028 // ReturnType.getAsString();
1029 // return;
1030 //}
1031
1032 D->addAttr(::new (S.Context)
1033 ReturnTypestateAttr(Attr.getRange(), S.Context, ReturnState,
1034 Attr.getAttributeSpellingListIndex()));
1035}
1036
DeLesley Hutchins33a29342013-10-11 23:03:26 +00001037static void handleSetTypestateAttr(Sema &S, Decl *D, const AttributeList &Attr) {
DeLesley Hutchins33a29342013-10-11 23:03:26 +00001038 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr))
1039 return;
1040
1041 SetTypestateAttr::ConsumedState NewState;
DeLesley Hutchins33a29342013-10-11 23:03:26 +00001042 if (Attr.isArgIdent(0)) {
Aaron Ballman91c98e12013-10-14 23:22:37 +00001043 IdentifierLoc *Ident = Attr.getArgAsIdent(0);
1044 StringRef Param = Ident->Ident->getName();
1045 if (!SetTypestateAttr::ConvertStrToConsumedState(Param, NewState)) {
1046 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
1047 << Attr.getName() << Param;
DeLesley Hutchins33a29342013-10-11 23:03:26 +00001048 return;
1049 }
DeLesley Hutchins33a29342013-10-11 23:03:26 +00001050 } else {
1051 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
1052 Attr.getName() << AANT_ArgumentIdentifier;
1053 return;
1054 }
1055
1056 D->addAttr(::new (S.Context)
1057 SetTypestateAttr(Attr.getRange(), S.Context, NewState,
1058 Attr.getAttributeSpellingListIndex()));
1059}
1060
Chris Wailes9385f9f2013-10-29 20:28:41 +00001061static void handleTestTypestateAttr(Sema &S, Decl *D,
1062 const AttributeList &Attr) {
DeLesley Hutchins33a29342013-10-11 23:03:26 +00001063 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr))
1064 return;
1065
Chris Wailes9385f9f2013-10-29 20:28:41 +00001066 TestTypestateAttr::ConsumedState TestState;
DeLesley Hutchins33a29342013-10-11 23:03:26 +00001067 if (Attr.isArgIdent(0)) {
Aaron Ballman91c98e12013-10-14 23:22:37 +00001068 IdentifierLoc *Ident = Attr.getArgAsIdent(0);
1069 StringRef Param = Ident->Ident->getName();
Chris Wailes9385f9f2013-10-29 20:28:41 +00001070 if (!TestTypestateAttr::ConvertStrToConsumedState(Param, TestState)) {
Aaron Ballman91c98e12013-10-14 23:22:37 +00001071 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
1072 << Attr.getName() << Param;
DeLesley Hutchins33a29342013-10-11 23:03:26 +00001073 return;
1074 }
DeLesley Hutchins33a29342013-10-11 23:03:26 +00001075 } else {
1076 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
1077 Attr.getName() << AANT_ArgumentIdentifier;
1078 return;
1079 }
1080
1081 D->addAttr(::new (S.Context)
Chris Wailes9385f9f2013-10-29 20:28:41 +00001082 TestTypestateAttr(Attr.getRange(), S.Context, TestState,
DeLesley Hutchins33a29342013-10-11 23:03:26 +00001083 Attr.getAttributeSpellingListIndex()));
1084}
1085
Chandler Carruthedc2c642011-07-02 00:01:44 +00001086static void handleExtVectorTypeAttr(Sema &S, Scope *scope, Decl *D,
1087 const AttributeList &Attr) {
Richard Smith1f5a4322013-01-13 02:11:23 +00001088 // Remember this typedef decl, we will need it later for diagnostics.
Aaron Ballman74eeeae2013-11-27 13:27:02 +00001089 S.ExtVectorDecls.push_back(cast<TypedefNameDecl>(D));
Chris Lattner2c6fcf52008-06-26 18:38:35 +00001090}
1091
Chandler Carruthedc2c642011-07-02 00:01:44 +00001092static void handlePackedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00001093 if (TagDecl *TD = dyn_cast<TagDecl>(D))
Aaron Ballman36a53502014-01-16 13:03:14 +00001094 TD->addAttr(::new (S.Context) PackedAttr(Attr.getRange(), S.Context,
1095 Attr.getAttributeSpellingListIndex()));
Chandler Carruthff4c4f02011-07-01 23:49:12 +00001096 else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Alexey Bataev830dfcc2015-12-03 09:34:49 +00001097 // Report warning about changed offset in the newer compiler versions.
Eli Friedmanc087c3f2012-11-07 00:35:20 +00001098 if (!FD->getType()->isDependentType() &&
Alexey Bataev830dfcc2015-12-03 09:34:49 +00001099 !FD->getType()->isIncompleteType() && FD->isBitField() &&
Chris Lattnerb632a6e2008-06-29 00:43:07 +00001100 S.Context.getTypeAlign(FD->getType()) <= 8)
Alexey Bataev830dfcc2015-12-03 09:34:49 +00001101 S.Diag(Attr.getLoc(), diag::warn_attribute_packed_for_bitfield);
1102
1103 FD->addAttr(::new (S.Context) PackedAttr(
1104 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
Chris Lattner2c6fcf52008-06-26 18:38:35 +00001105 } else
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001106 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
Chris Lattner2c6fcf52008-06-26 18:38:35 +00001107}
1108
Ted Kremenek7fd17232011-09-29 07:02:25 +00001109static bool checkIBOutletCommon(Sema &S, Decl *D, const AttributeList &Attr) {
1110 // The IBOutlet/IBOutletCollection attributes only apply to instance
1111 // variables or properties of Objective-C classes. The outlet must also
1112 // have an object reference type.
1113 if (const ObjCIvarDecl *VD = dyn_cast<ObjCIvarDecl>(D)) {
1114 if (!VD->getType()->getAs<ObjCObjectPointerType>()) {
Ted Kremenek5d6044e2011-11-01 18:08:35 +00001115 S.Diag(Attr.getLoc(), diag::warn_iboutlet_object_type)
Ted Kremenek7fd17232011-09-29 07:02:25 +00001116 << Attr.getName() << VD->getType() << 0;
1117 return false;
1118 }
1119 }
1120 else if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) {
1121 if (!PD->getType()->getAs<ObjCObjectPointerType>()) {
Douglas Gregor5c3cc422012-03-14 16:55:17 +00001122 S.Diag(Attr.getLoc(), diag::warn_iboutlet_object_type)
Ted Kremenek7fd17232011-09-29 07:02:25 +00001123 << Attr.getName() << PD->getType() << 1;
1124 return false;
1125 }
1126 }
1127 else {
1128 S.Diag(Attr.getLoc(), diag::warn_attribute_iboutlet) << Attr.getName();
1129 return false;
1130 }
Douglas Gregor5c3cc422012-03-14 16:55:17 +00001131
Ted Kremenek7fd17232011-09-29 07:02:25 +00001132 return true;
1133}
1134
Chandler Carruthedc2c642011-07-02 00:01:44 +00001135static void handleIBOutlet(Sema &S, Decl *D, const AttributeList &Attr) {
Ted Kremenek7fd17232011-09-29 07:02:25 +00001136 if (!checkIBOutletCommon(S, D, Attr))
Ted Kremenek1f672822010-02-18 03:08:58 +00001137 return;
Ted Kremenek1f672822010-02-18 03:08:58 +00001138
Michael Han99315932013-01-24 16:46:58 +00001139 D->addAttr(::new (S.Context)
1140 IBOutletAttr(Attr.getRange(), S.Context,
1141 Attr.getAttributeSpellingListIndex()));
Ted Kremenek8e3704d2008-07-15 22:26:48 +00001142}
1143
Chandler Carruthedc2c642011-07-02 00:01:44 +00001144static void handleIBOutletCollection(Sema &S, Decl *D,
1145 const AttributeList &Attr) {
Ted Kremenek26bde772010-05-19 17:38:06 +00001146
1147 // The iboutletcollection attribute can have zero or one arguments.
Aaron Ballman00e99962013-08-31 01:11:41 +00001148 if (Attr.getNumArgs() > 1) {
Aaron Ballmanb7243382013-07-23 19:30:11 +00001149 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
1150 << Attr.getName() << 1;
Ted Kremenek26bde772010-05-19 17:38:06 +00001151 return;
1152 }
1153
Ted Kremenek7fd17232011-09-29 07:02:25 +00001154 if (!checkIBOutletCommon(S, D, Attr))
Ted Kremenek26bde772010-05-19 17:38:06 +00001155 return;
Ted Kremenek7fd17232011-09-29 07:02:25 +00001156
Richard Smithb1f9a282013-10-31 01:56:18 +00001157 ParsedType PT;
1158
1159 if (Attr.hasParsedType())
1160 PT = Attr.getTypeArg();
1161 else {
1162 PT = S.getTypeName(S.Context.Idents.get("NSObject"), Attr.getLoc(),
1163 S.getScopeForContext(D->getDeclContext()->getParent()));
1164 if (!PT) {
1165 S.Diag(Attr.getLoc(), diag::err_iboutletcollection_type) << "NSObject";
1166 return;
1167 }
Aaron Ballman00e99962013-08-31 01:11:41 +00001168 }
Richard Smithb1f9a282013-10-31 01:56:18 +00001169
Craig Topperc3ec1492014-05-26 06:22:03 +00001170 TypeSourceInfo *QTLoc = nullptr;
Richard Smithb87c4652013-10-31 21:23:20 +00001171 QualType QT = S.GetTypeFromParser(PT, &QTLoc);
1172 if (!QTLoc)
1173 QTLoc = S.Context.getTrivialTypeSourceInfo(QT, Attr.getLoc());
Richard Smithb1f9a282013-10-31 01:56:18 +00001174
Fariborz Jahanianb5d59b62010-08-17 20:23:12 +00001175 // Diagnose use of non-object type in iboutletcollection attribute.
1176 // FIXME. Gnu attribute extension ignores use of builtin types in
1177 // attributes. So, __attribute__((iboutletcollection(char))) will be
1178 // treated as __attribute__((iboutletcollection())).
Fariborz Jahanian2f31b332011-10-18 19:54:31 +00001179 if (!QT->isObjCIdType() && !QT->isObjCObjectType()) {
Richard Smithb1f9a282013-10-31 01:56:18 +00001180 S.Diag(Attr.getLoc(),
1181 QT->isBuiltinType() ? diag::err_iboutletcollection_builtintype
1182 : diag::err_iboutletcollection_type) << QT;
Fariborz Jahanianb5d59b62010-08-17 20:23:12 +00001183 return;
1184 }
Richard Smithb1f9a282013-10-31 01:56:18 +00001185
Michael Han99315932013-01-24 16:46:58 +00001186 D->addAttr(::new (S.Context)
Richard Smithb87c4652013-10-31 21:23:20 +00001187 IBOutletCollectionAttr(Attr.getRange(), S.Context, QTLoc,
Michael Han99315932013-01-24 16:46:58 +00001188 Attr.getAttributeSpellingListIndex()));
Ted Kremenek26bde772010-05-19 17:38:06 +00001189}
1190
Hal Finkelee90a222014-09-26 05:04:30 +00001191bool Sema::isValidPointerAttrType(QualType T, bool RefOkay) {
1192 if (RefOkay) {
1193 if (T->isReferenceType())
1194 return true;
1195 } else {
1196 T = T.getNonReferenceType();
1197 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001198
Hal Finkelee90a222014-09-26 05:04:30 +00001199 // The nonnull attribute, and other similar attributes, can be applied to a
1200 // transparent union that contains a pointer type.
Richard Smith588bd9b2014-08-27 04:59:42 +00001201 if (const RecordType *UT = T->getAsUnionType()) {
Fariborz Jahanianf4aa2792011-06-27 21:12:03 +00001202 if (UT && UT->getDecl()->hasAttr<TransparentUnionAttr>()) {
1203 RecordDecl *UD = UT->getDecl();
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001204 for (const auto *I : UD->fields()) {
1205 QualType QT = I->getType();
Richard Smith588bd9b2014-08-27 04:59:42 +00001206 if (QT->isAnyPointerType() || QT->isBlockPointerType())
1207 return true;
Fariborz Jahanianf4aa2792011-06-27 21:12:03 +00001208 }
1209 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001210 }
1211
1212 return T->isAnyPointerType() || T->isBlockPointerType();
Fariborz Jahanianf4aa2792011-06-27 21:12:03 +00001213}
1214
Ted Kremenek9aedc152014-01-17 06:24:56 +00001215static bool attrNonNullArgCheck(Sema &S, QualType T, const AttributeList &Attr,
Aaron Ballman4bfa0de2014-08-01 12:58:11 +00001216 SourceRange AttrParmRange,
Hal Finkelee90a222014-09-26 05:04:30 +00001217 SourceRange TypeRange,
Aaron Ballman4bfa0de2014-08-01 12:58:11 +00001218 bool isReturnValue = false) {
Hal Finkelee90a222014-09-26 05:04:30 +00001219 if (!S.isValidPointerAttrType(T)) {
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001220 if (isReturnValue)
1221 S.Diag(Attr.getLoc(), diag::warn_attribute_return_pointers_only)
1222 << Attr.getName() << AttrParmRange << TypeRange;
1223 else
1224 S.Diag(Attr.getLoc(), diag::warn_attribute_pointers_only)
1225 << Attr.getName() << AttrParmRange << TypeRange << 0;
Ted Kremenek9aedc152014-01-17 06:24:56 +00001226 return false;
1227 }
1228 return true;
1229}
1230
Chandler Carruthedc2c642011-07-02 00:01:44 +00001231static void handleNonNullAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballmanbe50eb82013-07-30 00:48:57 +00001232 SmallVector<unsigned, 8> NonNullArgs;
Richard Smith588bd9b2014-08-27 04:59:42 +00001233 for (unsigned I = 0; I < Attr.getNumArgs(); ++I) {
1234 Expr *Ex = Attr.getArgAsExpr(I);
Aaron Ballmanbe50eb82013-07-30 00:48:57 +00001235 uint64_t Idx;
Richard Smith588bd9b2014-08-27 04:59:42 +00001236 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, I + 1, Ex, Idx))
Ted Kremenek2d63bc12008-07-21 21:53:04 +00001237 return;
Ted Kremenek2d63bc12008-07-21 21:53:04 +00001238
1239 // Is the function argument a pointer type?
Richard Smith588bd9b2014-08-27 04:59:42 +00001240 if (Idx < getFunctionOrMethodNumParams(D) &&
1241 !attrNonNullArgCheck(S, getFunctionOrMethodParamType(D, Idx), Attr,
Aaron Ballman4bfa0de2014-08-01 12:58:11 +00001242 Ex->getSourceRange(),
1243 getFunctionOrMethodParamRange(D, Idx)))
Ted Kremenekc4f6d902008-09-01 19:57:52 +00001244 continue;
Mike Stumpd3bb5572009-07-24 19:02:52 +00001245
Aaron Ballmanbe50eb82013-07-30 00:48:57 +00001246 NonNullArgs.push_back(Idx);
Ted Kremenek2d63bc12008-07-21 21:53:04 +00001247 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00001248
1249 // If no arguments were specified to __attribute__((nonnull)) then all pointer
Richard Smith588bd9b2014-08-27 04:59:42 +00001250 // arguments have a nonnull attribute; warn if there aren't any. Skip this
1251 // check if the attribute came from a macro expansion or a template
1252 // instantiation.
1253 if (NonNullArgs.empty() && Attr.getLoc().isFileID() &&
1254 S.ActiveTemplateInstantiations.empty()) {
1255 bool AnyPointers = isFunctionOrMethodVariadic(D);
1256 for (unsigned I = 0, E = getFunctionOrMethodNumParams(D);
1257 I != E && !AnyPointers; ++I) {
1258 QualType T = getFunctionOrMethodParamType(D, I);
Hal Finkelee90a222014-09-26 05:04:30 +00001259 if (T->isDependentType() || S.isValidPointerAttrType(T))
Richard Smith588bd9b2014-08-27 04:59:42 +00001260 AnyPointers = true;
Ted Kremenek5fa50522008-11-18 06:52:58 +00001261 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00001262
Richard Smith588bd9b2014-08-27 04:59:42 +00001263 if (!AnyPointers)
1264 S.Diag(Attr.getLoc(), diag::warn_attribute_nonnull_no_pointers);
Ted Kremenek2d63bc12008-07-21 21:53:04 +00001265 }
Ted Kremenekc4f6d902008-09-01 19:57:52 +00001266
Richard Smith588bd9b2014-08-27 04:59:42 +00001267 unsigned *Start = NonNullArgs.data();
1268 unsigned Size = NonNullArgs.size();
1269 llvm::array_pod_sort(Start, Start + Size);
Michael Han99315932013-01-24 16:46:58 +00001270 D->addAttr(::new (S.Context)
Richard Smith588bd9b2014-08-27 04:59:42 +00001271 NonNullAttr(Attr.getRange(), S.Context, Start, Size,
Michael Han99315932013-01-24 16:46:58 +00001272 Attr.getAttributeSpellingListIndex()));
Ted Kremenek2d63bc12008-07-21 21:53:04 +00001273}
1274
Jordan Rosec9399072014-02-11 17:27:59 +00001275static void handleNonNullAttrParameter(Sema &S, ParmVarDecl *D,
1276 const AttributeList &Attr) {
1277 if (Attr.getNumArgs() > 0) {
1278 if (D->getFunctionType()) {
1279 handleNonNullAttr(S, D, Attr);
1280 } else {
1281 S.Diag(Attr.getLoc(), diag::warn_attribute_nonnull_parm_no_args)
1282 << D->getSourceRange();
1283 }
1284 return;
1285 }
1286
1287 // Is the argument a pointer type?
Aaron Ballman4bfa0de2014-08-01 12:58:11 +00001288 if (!attrNonNullArgCheck(S, D->getType(), Attr, SourceRange(),
1289 D->getSourceRange()))
Jordan Rosec9399072014-02-11 17:27:59 +00001290 return;
1291
1292 D->addAttr(::new (S.Context)
Craig Topperc3ec1492014-05-26 06:22:03 +00001293 NonNullAttr(Attr.getRange(), S.Context, nullptr, 0,
Jordan Rosec9399072014-02-11 17:27:59 +00001294 Attr.getAttributeSpellingListIndex()));
1295}
1296
Ted Kremenekdbf62e32014-01-20 05:50:47 +00001297static void handleReturnsNonNullAttr(Sema &S, Decl *D,
1298 const AttributeList &Attr) {
Aaron Ballmanfc1951c2014-01-20 14:19:44 +00001299 QualType ResultType = getFunctionOrMethodResultType(D);
Aaron Ballman4bfa0de2014-08-01 12:58:11 +00001300 SourceRange SR = getFunctionOrMethodResultSourceRange(D);
1301 if (!attrNonNullArgCheck(S, ResultType, Attr, SourceRange(), SR,
Ted Kremenekdbf62e32014-01-20 05:50:47 +00001302 /* isReturnValue */ true))
1303 return;
1304
1305 D->addAttr(::new (S.Context)
1306 ReturnsNonNullAttr(Attr.getRange(), S.Context,
1307 Attr.getAttributeSpellingListIndex()));
1308}
1309
Hal Finkelee90a222014-09-26 05:04:30 +00001310static void handleAssumeAlignedAttr(Sema &S, Decl *D,
1311 const AttributeList &Attr) {
1312 Expr *E = Attr.getArgAsExpr(0),
1313 *OE = Attr.getNumArgs() > 1 ? Attr.getArgAsExpr(1) : nullptr;
1314 S.AddAssumeAlignedAttr(Attr.getRange(), D, E, OE,
1315 Attr.getAttributeSpellingListIndex());
1316}
1317
1318void Sema::AddAssumeAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
1319 Expr *OE, unsigned SpellingListIndex) {
1320 QualType ResultType = getFunctionOrMethodResultType(D);
1321 SourceRange SR = getFunctionOrMethodResultSourceRange(D);
1322
1323 AssumeAlignedAttr TmpAttr(AttrRange, Context, E, OE, SpellingListIndex);
1324 SourceLocation AttrLoc = AttrRange.getBegin();
1325
1326 if (!isValidPointerAttrType(ResultType, /* RefOkay */ true)) {
1327 Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only)
1328 << &TmpAttr << AttrRange << SR;
1329 return;
1330 }
1331
1332 if (!E->isValueDependent()) {
1333 llvm::APSInt I(64);
1334 if (!E->isIntegerConstantExpr(I, Context)) {
1335 if (OE)
1336 Diag(AttrLoc, diag::err_attribute_argument_n_type)
1337 << &TmpAttr << 1 << AANT_ArgumentIntegerConstant
1338 << E->getSourceRange();
1339 else
1340 Diag(AttrLoc, diag::err_attribute_argument_type)
1341 << &TmpAttr << AANT_ArgumentIntegerConstant
1342 << E->getSourceRange();
1343 return;
1344 }
1345
1346 if (!I.isPowerOf2()) {
1347 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
1348 << E->getSourceRange();
1349 return;
1350 }
1351 }
1352
1353 if (OE) {
1354 if (!OE->isValueDependent()) {
1355 llvm::APSInt I(64);
1356 if (!OE->isIntegerConstantExpr(I, Context)) {
1357 Diag(AttrLoc, diag::err_attribute_argument_n_type)
1358 << &TmpAttr << 2 << AANT_ArgumentIntegerConstant
1359 << OE->getSourceRange();
1360 return;
1361 }
1362 }
1363 }
1364
1365 D->addAttr(::new (Context)
1366 AssumeAlignedAttr(AttrRange, Context, E, OE, SpellingListIndex));
1367}
1368
Aaron Ballman8b5e7ba2015-10-08 19:24:08 +00001369/// Normalize the attribute, __foo__ becomes foo.
1370/// Returns true if normalization was applied.
1371static bool normalizeName(StringRef &AttrName) {
Aaron Ballman62692362015-10-09 13:53:24 +00001372 if (AttrName.size() > 4 && AttrName.startswith("__") &&
1373 AttrName.endswith("__")) {
Aaron Ballman8b5e7ba2015-10-08 19:24:08 +00001374 AttrName = AttrName.drop_front(2).drop_back(2);
1375 return true;
1376 }
1377 return false;
1378}
1379
Chandler Carruthedc2c642011-07-02 00:01:44 +00001380static void handleOwnershipAttr(Sema &S, Decl *D, const AttributeList &AL) {
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001381 // This attribute must be applied to a function declaration. The first
1382 // argument to the attribute must be an identifier, the name of the resource,
1383 // for example: malloc. The following arguments must be argument indexes, the
1384 // arguments must be of integer type for Returns, otherwise of pointer type.
Ted Kremenekd21139a2010-07-31 01:52:11 +00001385 // The difference between Holds and Takes is that a pointer may still be used
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001386 // after being held. free() should be __attribute((ownership_takes)), whereas
Jordy Rose5af0e3c2010-08-12 08:54:03 +00001387 // a list append function may well be __attribute((ownership_holds)).
Ted Kremenekd21139a2010-07-31 01:52:11 +00001388
Aaron Ballman00e99962013-08-31 01:11:41 +00001389 if (!AL.isArgIdent(0)) {
Aaron Ballman29982272013-07-23 14:03:57 +00001390 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001391 << AL.getName() << 1 << AANT_ArgumentIdentifier;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001392 return;
1393 }
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001394
Richard Smith852e9ce2013-11-27 01:46:48 +00001395 // Figure out our Kind.
1396 OwnershipAttr::OwnershipKind K =
Craig Topperc3ec1492014-05-26 06:22:03 +00001397 OwnershipAttr(AL.getLoc(), S.Context, nullptr, nullptr, 0,
Richard Smith852e9ce2013-11-27 01:46:48 +00001398 AL.getAttributeSpellingListIndex()).getOwnKind();
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001399
Richard Smith852e9ce2013-11-27 01:46:48 +00001400 // Check arguments.
1401 switch (K) {
1402 case OwnershipAttr::Takes:
1403 case OwnershipAttr::Holds:
1404 if (AL.getNumArgs() < 2) {
Aaron Ballman05e420a2014-01-02 21:26:14 +00001405 S.Diag(AL.getLoc(), diag::err_attribute_too_few_arguments)
1406 << AL.getName() << 2;
Richard Smith852e9ce2013-11-27 01:46:48 +00001407 return;
1408 }
1409 break;
1410 case OwnershipAttr::Returns:
Aaron Ballman00e99962013-08-31 01:11:41 +00001411 if (AL.getNumArgs() > 2) {
Aaron Ballman05e420a2014-01-02 21:26:14 +00001412 S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments)
1413 << AL.getName() << 1;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001414 return;
1415 }
Jordy Rose5af0e3c2010-08-12 08:54:03 +00001416 break;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001417 }
1418
Richard Smith852e9ce2013-11-27 01:46:48 +00001419 IdentifierInfo *Module = AL.getArgAsIdent(0)->Ident;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001420
Richard Smith852e9ce2013-11-27 01:46:48 +00001421 StringRef ModuleName = Module->getName();
Aaron Ballman8b5e7ba2015-10-08 19:24:08 +00001422 if (normalizeName(ModuleName)) {
Richard Smith852e9ce2013-11-27 01:46:48 +00001423 Module = &S.PP.getIdentifierTable().get(ModuleName);
1424 }
Ted Kremenekd21139a2010-07-31 01:52:11 +00001425
Aaron Ballmanbe50eb82013-07-30 00:48:57 +00001426 SmallVector<unsigned, 8> OwnershipArgs;
Aaron Ballman00e99962013-08-31 01:11:41 +00001427 for (unsigned i = 1; i < AL.getNumArgs(); ++i) {
1428 Expr *Ex = AL.getArgAsExpr(i);
Aaron Ballmanbe50eb82013-07-30 00:48:57 +00001429 uint64_t Idx;
Alp Toker601b22c2014-01-21 23:35:24 +00001430 if (!checkFunctionOrMethodParameterIndex(S, D, AL, i, Ex, Idx))
Aaron Ballmanbe50eb82013-07-30 00:48:57 +00001431 return;
Chandler Carruth743682b2010-11-16 08:35:43 +00001432
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001433 // Is the function argument a pointer type?
Alp Toker601b22c2014-01-21 23:35:24 +00001434 QualType T = getFunctionOrMethodParamType(D, Idx);
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001435 int Err = -1; // No error
Ted Kremenekd21139a2010-07-31 01:52:11 +00001436 switch (K) {
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001437 case OwnershipAttr::Takes:
1438 case OwnershipAttr::Holds:
1439 if (!T->isAnyPointerType() && !T->isBlockPointerType())
1440 Err = 0;
1441 break;
1442 case OwnershipAttr::Returns:
1443 if (!T->isIntegerType())
1444 Err = 1;
1445 break;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001446 }
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001447 if (-1 != Err) {
Fariborz Jahanian8a5e9472013-09-19 16:37:20 +00001448 S.Diag(AL.getLoc(), diag::err_ownership_type) << AL.getName() << Err
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001449 << Ex->getSourceRange();
1450 return;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001451 }
Ted Kremenekd21139a2010-07-31 01:52:11 +00001452
1453 // Check we don't have a conflict with another ownership attribute.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001454 for (const auto *I : D->specific_attrs<OwnershipAttr>()) {
Aaron Ballmanef7aef82014-07-31 20:44:26 +00001455 // Cannot have two ownership attributes of different kinds for the same
1456 // index.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001457 if (I->getOwnKind() != K && I->args_end() !=
1458 std::find(I->args_begin(), I->args_end(), Idx)) {
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001459 S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001460 << AL.getName() << I;
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001461 return;
Aaron Ballmanef7aef82014-07-31 20:44:26 +00001462 } else if (K == OwnershipAttr::Returns &&
1463 I->getOwnKind() == OwnershipAttr::Returns) {
1464 // A returns attribute conflicts with any other returns attribute using
1465 // a different index. Note, diagnostic reporting is 1-based, but stored
1466 // argument indexes are 0-based.
1467 if (std::find(I->args_begin(), I->args_end(), Idx) == I->args_end()) {
1468 S.Diag(I->getLocation(), diag::err_ownership_returns_index_mismatch)
1469 << *(I->args_begin()) + 1;
1470 if (I->args_size())
1471 S.Diag(AL.getLoc(), diag::note_ownership_returns_index_mismatch)
1472 << (unsigned)Idx + 1 << Ex->getSourceRange();
1473 return;
1474 }
Ted Kremenekd21139a2010-07-31 01:52:11 +00001475 }
1476 }
Aaron Ballmanbe50eb82013-07-30 00:48:57 +00001477 OwnershipArgs.push_back(Idx);
Ted Kremenekd21139a2010-07-31 01:52:11 +00001478 }
1479
1480 unsigned* start = OwnershipArgs.data();
1481 unsigned size = OwnershipArgs.size();
1482 llvm::array_pod_sort(start, start + size);
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001483
Michael Han99315932013-01-24 16:46:58 +00001484 D->addAttr(::new (S.Context)
Richard Smith852e9ce2013-11-27 01:46:48 +00001485 OwnershipAttr(AL.getLoc(), S.Context, Module, start, size,
Michael Han99315932013-01-24 16:46:58 +00001486 AL.getAttributeSpellingListIndex()));
Ted Kremenekd21139a2010-07-31 01:52:11 +00001487}
1488
Chandler Carruthedc2c642011-07-02 00:01:44 +00001489static void handleWeakRefAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Rafael Espindolac18086a2010-02-23 22:00:30 +00001490 // Check the attribute arguments.
1491 if (Attr.getNumArgs() > 1) {
Aaron Ballmanb7243382013-07-23 19:30:11 +00001492 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
1493 << Attr.getName() << 1;
Rafael Espindolac18086a2010-02-23 22:00:30 +00001494 return;
1495 }
1496
Chandler Carruthff4c4f02011-07-01 23:49:12 +00001497 NamedDecl *nd = cast<NamedDecl>(D);
John McCall7a198ce2011-02-08 22:35:49 +00001498
Rafael Espindolac18086a2010-02-23 22:00:30 +00001499 // gcc rejects
1500 // class c {
1501 // static int a __attribute__((weakref ("v2")));
1502 // static int b() __attribute__((weakref ("f3")));
1503 // };
1504 // and ignores the attributes of
1505 // void f(void) {
1506 // static int a __attribute__((weakref ("v2")));
1507 // }
1508 // we reject them
Chandler Carruthff4c4f02011-07-01 23:49:12 +00001509 const DeclContext *Ctx = D->getDeclContext()->getRedeclContext();
Sebastian Redl50c68252010-08-31 00:36:30 +00001510 if (!Ctx->isFileContext()) {
Aaron Ballman9f6fec42014-01-02 23:02:01 +00001511 S.Diag(Attr.getLoc(), diag::err_attribute_weakref_not_global_context)
1512 << nd;
Sebastian Redl50c68252010-08-31 00:36:30 +00001513 return;
Rafael Espindolac18086a2010-02-23 22:00:30 +00001514 }
1515
1516 // The GCC manual says
1517 //
1518 // At present, a declaration to which `weakref' is attached can only
1519 // be `static'.
1520 //
1521 // It also says
1522 //
1523 // Without a TARGET,
1524 // given as an argument to `weakref' or to `alias', `weakref' is
1525 // equivalent to `weak'.
1526 //
1527 // gcc 4.4.1 will accept
1528 // int a7 __attribute__((weakref));
1529 // as
1530 // int a7 __attribute__((weak));
1531 // This looks like a bug in gcc. We reject that for now. We should revisit
1532 // it if this behaviour is actually used.
1533
Rafael Espindolac18086a2010-02-23 22:00:30 +00001534 // GCC rejects
1535 // static ((alias ("y"), weakref)).
1536 // Should we? How to check that weakref is before or after alias?
1537
Aaron Ballmanfebff0c2013-09-09 23:40:31 +00001538 // FIXME: it would be good for us to keep the WeakRefAttr as-written instead
1539 // of transforming it into an AliasAttr. The WeakRefAttr never uses the
1540 // StringRef parameter it was given anyway.
Aaron Ballman3b1dde62013-09-13 19:35:18 +00001541 StringRef Str;
Tim Northover6a6b63b2013-10-01 14:34:18 +00001542 if (Attr.getNumArgs() && S.checkStringLiteralArgumentAttr(Attr, 0, Str))
Rafael Espindolac18086a2010-02-23 22:00:30 +00001543 // GCC will accept anything as the argument of weakref. Should we
1544 // check for an existing decl?
Aaron Ballman3b1dde62013-09-13 19:35:18 +00001545 D->addAttr(::new (S.Context) AliasAttr(Attr.getRange(), S.Context, Str,
1546 Attr.getAttributeSpellingListIndex()));
Rafael Espindolac18086a2010-02-23 22:00:30 +00001547
Michael Han99315932013-01-24 16:46:58 +00001548 D->addAttr(::new (S.Context)
1549 WeakRefAttr(Attr.getRange(), S.Context,
1550 Attr.getAttributeSpellingListIndex()));
Rafael Espindolac18086a2010-02-23 22:00:30 +00001551}
1552
Dmitry Polukhin85eda122016-04-11 07:48:59 +00001553static void handleIFuncAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1554 StringRef Str;
1555 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str))
1556 return;
1557
1558 // Aliases should be on declarations, not definitions.
1559 const auto *FD = cast<FunctionDecl>(D);
1560 if (FD->isThisDeclarationADefinition()) {
1561 S.Diag(Attr.getLoc(), diag::err_alias_is_definition) << FD << 1;
1562 return;
1563 }
1564 // FIXME: it should be handled as a target specific attribute.
1565 if (S.Context.getTargetInfo().getTriple().getObjectFormat() !=
1566 llvm::Triple::ELF) {
1567 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
1568 return;
1569 }
1570
1571 D->addAttr(::new (S.Context) IFuncAttr(Attr.getRange(), S.Context, Str,
1572 Attr.getAttributeSpellingListIndex()));
1573}
1574
Benjamin Kramer6ee15622013-09-13 15:35:43 +00001575static void handleAliasAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1576 StringRef Str;
Tim Northover6a6b63b2013-10-01 14:34:18 +00001577 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str))
Benjamin Kramer6ee15622013-09-13 15:35:43 +00001578 return;
1579
Douglas Gregore8bbc122011-09-02 00:18:52 +00001580 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Rafael Espindola0017c5f2010-12-07 15:23:23 +00001581 S.Diag(Attr.getLoc(), diag::err_alias_not_supported_on_darwin);
1582 return;
1583 }
Justin Lebara8f0254b2016-01-23 21:28:10 +00001584 if (S.Context.getTargetInfo().getTriple().isNVPTX()) {
1585 S.Diag(Attr.getLoc(), diag::err_alias_not_supported_on_nvptx);
1586 }
Rafael Espindola0017c5f2010-12-07 15:23:23 +00001587
David Majnemer2dc81462015-01-19 09:00:28 +00001588 // Aliases should be on declarations, not definitions.
1589 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
1590 if (FD->isThisDeclarationADefinition()) {
Dmitry Polukhin85eda122016-04-11 07:48:59 +00001591 S.Diag(Attr.getLoc(), diag::err_alias_is_definition) << FD << 0;
David Majnemer2dc81462015-01-19 09:00:28 +00001592 return;
1593 }
1594 } else {
1595 const auto *VD = cast<VarDecl>(D);
1596 if (VD->isThisDeclarationADefinition() && VD->isExternallyVisible()) {
Dmitry Polukhin85eda122016-04-11 07:48:59 +00001597 S.Diag(Attr.getLoc(), diag::err_alias_is_definition) << VD << 0;
David Majnemer2dc81462015-01-19 09:00:28 +00001598 return;
1599 }
1600 }
1601
Chris Lattner2c6fcf52008-06-26 18:38:35 +00001602 // FIXME: check if target symbol exists in current file
Mike Stumpd3bb5572009-07-24 19:02:52 +00001603
Benjamin Kramer6ee15622013-09-13 15:35:43 +00001604 D->addAttr(::new (S.Context) AliasAttr(Attr.getRange(), S.Context, Str,
Michael Han99315932013-01-24 16:46:58 +00001605 Attr.getAttributeSpellingListIndex()));
Chris Lattner2c6fcf52008-06-26 18:38:35 +00001606}
1607
Benjamin Kramer29c2b432012-05-12 21:10:52 +00001608static void handleColdAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00001609 if (checkAttrMutualExclusion<HotAttr>(S, D, Attr.getRange(), Attr.getName()))
Benjamin Kramer29c2b432012-05-12 21:10:52 +00001610 return;
Benjamin Kramer29c2b432012-05-12 21:10:52 +00001611
Michael Han99315932013-01-24 16:46:58 +00001612 D->addAttr(::new (S.Context) ColdAttr(Attr.getRange(), S.Context,
1613 Attr.getAttributeSpellingListIndex()));
Benjamin Kramer29c2b432012-05-12 21:10:52 +00001614}
1615
1616static void handleHotAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00001617 if (checkAttrMutualExclusion<ColdAttr>(S, D, Attr.getRange(), Attr.getName()))
Benjamin Kramer29c2b432012-05-12 21:10:52 +00001618 return;
Benjamin Kramer29c2b432012-05-12 21:10:52 +00001619
Michael Han99315932013-01-24 16:46:58 +00001620 D->addAttr(::new (S.Context) HotAttr(Attr.getRange(), S.Context,
1621 Attr.getAttributeSpellingListIndex()));
Benjamin Kramer29c2b432012-05-12 21:10:52 +00001622}
1623
Hans Wennborgd3b01bc2012-06-23 11:51:46 +00001624static void handleTLSModelAttr(Sema &S, Decl *D,
1625 const AttributeList &Attr) {
Benjamin Kramer6ee15622013-09-13 15:35:43 +00001626 StringRef Model;
1627 SourceLocation LiteralLoc;
Hans Wennborgd3b01bc2012-06-23 11:51:46 +00001628 // Check that it is a string.
Tim Northover6a6b63b2013-10-01 14:34:18 +00001629 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Model, &LiteralLoc))
Hans Wennborgd3b01bc2012-06-23 11:51:46 +00001630 return;
Hans Wennborgd3b01bc2012-06-23 11:51:46 +00001631
Hans Wennborgd3b01bc2012-06-23 11:51:46 +00001632 // Check that the value.
Hans Wennborgd3b01bc2012-06-23 11:51:46 +00001633 if (Model != "global-dynamic" && Model != "local-dynamic"
1634 && Model != "initial-exec" && Model != "local-exec") {
Benjamin Kramer6ee15622013-09-13 15:35:43 +00001635 S.Diag(LiteralLoc, diag::err_attr_tlsmodel_arg);
Hans Wennborgd3b01bc2012-06-23 11:51:46 +00001636 return;
1637 }
1638
Michael Han99315932013-01-24 16:46:58 +00001639 D->addAttr(::new (S.Context)
1640 TLSModelAttr(Attr.getRange(), S.Context, Model,
1641 Attr.getAttributeSpellingListIndex()));
Hans Wennborgd3b01bc2012-06-23 11:51:46 +00001642}
1643
David Majnemer631a90b2015-02-04 07:23:21 +00001644static void handleRestrictAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1645 QualType ResultType = getFunctionOrMethodResultType(D);
1646 if (ResultType->isAnyPointerType() || ResultType->isBlockPointerType()) {
1647 D->addAttr(::new (S.Context) RestrictAttr(
1648 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
1649 return;
Ryan Flynn1f1fdc02009-08-09 20:07:29 +00001650 }
1651
David Majnemer631a90b2015-02-04 07:23:21 +00001652 S.Diag(Attr.getLoc(), diag::warn_attribute_return_pointers_only)
1653 << Attr.getName() << getFunctionOrMethodResultSourceRange(D);
Ryan Flynn1f1fdc02009-08-09 20:07:29 +00001654}
1655
Chandler Carruthedc2c642011-07-02 00:01:44 +00001656static void handleCommonAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Eli Friedman6fc7ad12013-06-20 22:55:04 +00001657 if (S.LangOpts.CPlusPlus) {
Aaron Ballman3db89662013-11-24 21:48:06 +00001658 S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang)
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00001659 << Attr.getName() << AttributeLangSupport::Cpp;
Eli Friedman6fc7ad12013-06-20 22:55:04 +00001660 return;
1661 }
1662
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00001663 if (CommonAttr *CA = S.mergeCommonAttr(D, Attr.getRange(), Attr.getName(),
1664 Attr.getAttributeSpellingListIndex()))
1665 D->addAttr(CA);
Eric Christopher8a2ee392010-12-02 02:45:55 +00001666}
1667
Charles Davis0e379112016-08-08 21:19:08 +00001668static void handleNakedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1669 if (checkAttrMutualExclusion<DisableTailCallsAttr>(S, D, Attr.getRange(),
1670 Attr.getName()))
1671 return;
1672
1673 D->addAttr(::new (S.Context) NakedAttr(Attr.getRange(), S.Context,
1674 Attr.getAttributeSpellingListIndex()));
1675}
1676
Chandler Carruthedc2c642011-07-02 00:01:44 +00001677static void handleNoReturnAttr(Sema &S, Decl *D, const AttributeList &attr) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00001678 if (hasDeclarator(D)) return;
John McCall3882ace2011-01-05 12:14:39 +00001679
1680 if (S.CheckNoReturnAttr(attr)) return;
1681
Chandler Carruthff4c4f02011-07-01 23:49:12 +00001682 if (!isa<ObjCMethodDecl>(D)) {
John McCall3882ace2011-01-05 12:14:39 +00001683 S.Diag(attr.getLoc(), diag::warn_attribute_wrong_decl_type)
John McCall5fca7ea2011-03-02 12:29:23 +00001684 << attr.getName() << ExpectedFunctionOrMethod;
John McCall3882ace2011-01-05 12:14:39 +00001685 return;
1686 }
1687
Michael Han99315932013-01-24 16:46:58 +00001688 D->addAttr(::new (S.Context)
1689 NoReturnAttr(attr.getRange(), S.Context,
1690 attr.getAttributeSpellingListIndex()));
John McCall3882ace2011-01-05 12:14:39 +00001691}
1692
1693bool Sema::CheckNoReturnAttr(const AttributeList &attr) {
Aaron Ballman00e99962013-08-31 01:11:41 +00001694 if (!checkAttributeNumArgs(*this, attr, 0)) {
John McCall3882ace2011-01-05 12:14:39 +00001695 attr.setInvalid();
1696 return true;
1697 }
1698
1699 return false;
Ted Kremenek40f4ee72009-04-10 00:01:14 +00001700}
1701
Chandler Carruthedc2c642011-07-02 00:01:44 +00001702static void handleAnalyzerNoReturnAttr(Sema &S, Decl *D,
1703 const AttributeList &Attr) {
Ted Kremenek5295ce82010-08-19 00:51:58 +00001704
1705 // The checking path for 'noreturn' and 'analyzer_noreturn' are different
1706 // because 'analyzer_noreturn' does not impact the type.
David Majnemer06864812015-04-07 06:01:53 +00001707 if (!isFunctionOrMethodOrBlock(D)) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00001708 ValueDecl *VD = dyn_cast<ValueDecl>(D);
Craig Topperc3ec1492014-05-26 06:22:03 +00001709 if (!VD || (!VD->getType()->isBlockPointerType() &&
1710 !VD->getType()->isFunctionPointerType())) {
Ted Kremenek5295ce82010-08-19 00:51:58 +00001711 S.Diag(Attr.getLoc(),
Richard Smith89645bc2013-01-02 12:01:23 +00001712 Attr.isCXX11Attribute() ? diag::err_attribute_wrong_decl_type
Craig Topper8f7f3ea2015-11-17 05:40:05 +00001713 : diag::warn_attribute_wrong_decl_type)
John McCall5fca7ea2011-03-02 12:29:23 +00001714 << Attr.getName() << ExpectedFunctionMethodOrBlock;
Ted Kremenek5295ce82010-08-19 00:51:58 +00001715 return;
1716 }
1717 }
1718
Michael Han99315932013-01-24 16:46:58 +00001719 D->addAttr(::new (S.Context)
1720 AnalyzerNoReturnAttr(Attr.getRange(), S.Context,
1721 Attr.getAttributeSpellingListIndex()));
Chris Lattner2c6fcf52008-06-26 18:38:35 +00001722}
1723
John Thompsoncdb847ba2010-08-09 21:53:52 +00001724// PS3 PPU-specific.
Chandler Carruthedc2c642011-07-02 00:01:44 +00001725static void handleVecReturnAttr(Sema &S, Decl *D, const AttributeList &Attr) {
John Thompsoncdb847ba2010-08-09 21:53:52 +00001726/*
1727 Returning a Vector Class in Registers
1728
Eric Christopherbc638a82010-12-01 22:13:54 +00001729 According to the PPU ABI specifications, a class with a single member of
1730 vector type is returned in memory when used as the return value of a function.
1731 This results in inefficient code when implementing vector classes. To return
1732 the value in a single vector register, add the vecreturn attribute to the
1733 class definition. This attribute is also applicable to struct types.
John Thompsoncdb847ba2010-08-09 21:53:52 +00001734
1735 Example:
1736
1737 struct Vector
1738 {
1739 __vector float xyzw;
1740 } __attribute__((vecreturn));
1741
1742 Vector Add(Vector lhs, Vector rhs)
1743 {
1744 Vector result;
1745 result.xyzw = vec_add(lhs.xyzw, rhs.xyzw);
1746 return result; // This will be returned in a register
1747 }
1748*/
Aaron Ballman3e424b52013-12-26 18:30:57 +00001749 if (VecReturnAttr *A = D->getAttr<VecReturnAttr>()) {
1750 S.Diag(Attr.getLoc(), diag::err_repeat_attribute) << A;
John Thompsoncdb847ba2010-08-09 21:53:52 +00001751 return;
1752 }
1753
Chandler Carruthff4c4f02011-07-01 23:49:12 +00001754 RecordDecl *record = cast<RecordDecl>(D);
John Thompson9a587aaa2010-09-18 01:12:07 +00001755 int count = 0;
1756
1757 if (!isa<CXXRecordDecl>(record)) {
1758 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
1759 return;
1760 }
1761
1762 if (!cast<CXXRecordDecl>(record)->isPOD()) {
1763 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_pod_record);
1764 return;
1765 }
1766
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001767 for (const auto *I : record->fields()) {
1768 if ((count == 1) || !I->getType()->isVectorType()) {
John Thompson9a587aaa2010-09-18 01:12:07 +00001769 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
1770 return;
1771 }
1772 count++;
1773 }
1774
Michael Han99315932013-01-24 16:46:58 +00001775 D->addAttr(::new (S.Context)
1776 VecReturnAttr(Attr.getRange(), S.Context,
1777 Attr.getAttributeSpellingListIndex()));
John Thompsoncdb847ba2010-08-09 21:53:52 +00001778}
1779
Richard Smithe233fbf2013-01-28 22:42:45 +00001780static void handleDependencyAttr(Sema &S, Scope *Scope, Decl *D,
1781 const AttributeList &Attr) {
1782 if (isa<ParmVarDecl>(D)) {
1783 // [[carries_dependency]] can only be applied to a parameter if it is a
1784 // parameter of a function declaration or lambda.
1785 if (!(Scope->getFlags() & clang::Scope::FunctionDeclarationScope)) {
1786 S.Diag(Attr.getLoc(),
1787 diag::err_carries_dependency_param_not_function_decl);
1788 return;
1789 }
Alexis Hunt96d5c762009-11-21 08:43:09 +00001790 }
Richard Smithe233fbf2013-01-28 22:42:45 +00001791
1792 D->addAttr(::new (S.Context) CarriesDependencyAttr(
1793 Attr.getRange(), S.Context,
1794 Attr.getAttributeSpellingListIndex()));
Alexis Hunt96d5c762009-11-21 08:43:09 +00001795}
1796
Akira Hatanakac8667622015-11-06 23:56:15 +00001797static void handleNotTailCalledAttr(Sema &S, Decl *D,
1798 const AttributeList &Attr) {
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00001799 if (checkAttrMutualExclusion<AlwaysInlineAttr>(S, D, Attr.getRange(),
1800 Attr.getName()))
Akira Hatanakac8667622015-11-06 23:56:15 +00001801 return;
1802
1803 D->addAttr(::new (S.Context) NotTailCalledAttr(
1804 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
1805}
1806
Akira Hatanaka7828b1e2015-11-13 00:42:21 +00001807static void handleDisableTailCallsAttr(Sema &S, Decl *D,
1808 const AttributeList &Attr) {
1809 if (checkAttrMutualExclusion<NakedAttr>(S, D, Attr.getRange(),
1810 Attr.getName()))
1811 return;
1812
1813 D->addAttr(::new (S.Context) DisableTailCallsAttr(
1814 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
1815}
1816
Chandler Carruthedc2c642011-07-02 00:01:44 +00001817static void handleUsedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00001818 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Rafael Espindola87198cd2013-08-16 23:18:50 +00001819 if (VD->hasLocalStorage()) {
Aaron Ballman88fe3222013-12-26 17:30:44 +00001820 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
Daniel Dunbarfee07a02009-02-13 19:23:53 +00001821 return;
1822 }
Chandler Carruthff4c4f02011-07-01 23:49:12 +00001823 } else if (!isFunctionOrMethod(D)) {
Daniel Dunbarfee07a02009-02-13 19:23:53 +00001824 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
John McCall5fca7ea2011-03-02 12:29:23 +00001825 << Attr.getName() << ExpectedVariableOrFunction;
Daniel Dunbarfee07a02009-02-13 19:23:53 +00001826 return;
1827 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00001828
Michael Han99315932013-01-24 16:46:58 +00001829 D->addAttr(::new (S.Context)
1830 UsedAttr(Attr.getRange(), S.Context,
1831 Attr.getAttributeSpellingListIndex()));
Daniel Dunbarfee07a02009-02-13 19:23:53 +00001832}
1833
Aaron Ballman0bcd6c12016-03-09 16:48:08 +00001834static void handleUnusedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1835 bool IsCXX1zAttr = Attr.isCXX11Attribute() && !Attr.getScopeName();
1836
1837 if (IsCXX1zAttr && isa<VarDecl>(D)) {
1838 // The C++1z spelling of this attribute cannot be applied to a static data
1839 // member per [dcl.attr.unused]p2.
1840 if (cast<VarDecl>(D)->isStaticDataMember()) {
1841 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1842 << Attr.getName() << ExpectedForMaybeUnused;
1843 return;
1844 }
1845 }
1846
1847 // If this is spelled as the standard C++1z attribute, but not in C++1z, warn
1848 // about using it as an extension.
1849 if (!S.getLangOpts().CPlusPlus1z && IsCXX1zAttr)
1850 S.Diag(Attr.getLoc(), diag::ext_cxx1z_attr) << Attr.getName();
1851
1852 D->addAttr(::new (S.Context) UnusedAttr(
1853 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
1854}
1855
Chandler Carruthedc2c642011-07-02 00:01:44 +00001856static void handleConstructorAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00001857 uint32_t priority = ConstructorAttr::DefaultPriority;
Aaron Ballman8ed8dbd2014-07-31 16:37:04 +00001858 if (Attr.getNumArgs() &&
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00001859 !checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), priority))
1860 return;
Mike Stumpd3bb5572009-07-24 19:02:52 +00001861
Michael Han99315932013-01-24 16:46:58 +00001862 D->addAttr(::new (S.Context)
1863 ConstructorAttr(Attr.getRange(), S.Context, priority,
1864 Attr.getAttributeSpellingListIndex()));
Daniel Dunbar032db472008-07-31 22:40:48 +00001865}
1866
Chandler Carruthedc2c642011-07-02 00:01:44 +00001867static void handleDestructorAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballmanf28e4992014-01-20 15:22:57 +00001868 uint32_t priority = DestructorAttr::DefaultPriority;
Aaron Ballman8ed8dbd2014-07-31 16:37:04 +00001869 if (Attr.getNumArgs() &&
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00001870 !checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), priority))
1871 return;
Mike Stumpd3bb5572009-07-24 19:02:52 +00001872
Michael Han99315932013-01-24 16:46:58 +00001873 D->addAttr(::new (S.Context)
1874 DestructorAttr(Attr.getRange(), S.Context, priority,
1875 Attr.getAttributeSpellingListIndex()));
Daniel Dunbar032db472008-07-31 22:40:48 +00001876}
1877
Benjamin Kramerf435ab42012-05-16 12:19:08 +00001878template <typename AttrTy>
Aaron Ballman8b8ebdd2013-07-18 13:13:52 +00001879static void handleAttrWithMessage(Sema &S, Decl *D,
1880 const AttributeList &Attr) {
Benjamin Kramerf435ab42012-05-16 12:19:08 +00001881 // Handle the case where the attribute has a text message.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001882 StringRef Str;
Aaron Ballman8ed8dbd2014-07-31 16:37:04 +00001883 if (Attr.getNumArgs() == 1 && !S.checkStringLiteralArgumentAttr(Attr, 0, Str))
Benjamin Kramer6ee15622013-09-13 15:35:43 +00001884 return;
Mike Stumpd3bb5572009-07-24 19:02:52 +00001885
Michael Han99315932013-01-24 16:46:58 +00001886 D->addAttr(::new (S.Context) AttrTy(Attr.getRange(), S.Context, Str,
1887 Attr.getAttributeSpellingListIndex()));
Fariborz Jahanian1470e932008-12-17 01:07:27 +00001888}
1889
Ted Kremenek438f8db2014-02-22 01:06:05 +00001890static void handleObjCSuppresProtocolAttr(Sema &S, Decl *D,
Ted Kremenek28eace62013-11-23 01:01:34 +00001891 const AttributeList &Attr) {
Ted Kremenek438f8db2014-02-22 01:06:05 +00001892 if (!cast<ObjCProtocolDecl>(D)->isThisDeclarationADefinition()) {
Ted Kremenek27cfe102014-02-21 22:49:04 +00001893 S.Diag(Attr.getLoc(), diag::err_objc_attr_protocol_requires_definition)
1894 << Attr.getName() << Attr.getRange();
1895 return;
1896 }
1897
Ted Kremenek28eace62013-11-23 01:01:34 +00001898 D->addAttr(::new (S.Context)
Ted Kremenekf41cf7f12013-12-10 19:43:48 +00001899 ObjCExplicitProtocolImplAttr(Attr.getRange(), S.Context,
1900 Attr.getAttributeSpellingListIndex()));
Ted Kremenek28eace62013-11-23 01:01:34 +00001901}
1902
Jordy Rose740b0c22012-05-08 03:27:22 +00001903static bool checkAvailabilityAttr(Sema &S, SourceRange Range,
1904 IdentifierInfo *Platform,
1905 VersionTuple Introduced,
1906 VersionTuple Deprecated,
1907 VersionTuple Obsoleted) {
Rafael Espindola2d243bf2012-05-06 19:56:25 +00001908 StringRef PlatformName
1909 = AvailabilityAttr::getPrettyPlatformName(Platform->getName());
1910 if (PlatformName.empty())
1911 PlatformName = Platform->getName();
1912
1913 // Ensure that Introduced <= Deprecated <= Obsoleted (although not all
1914 // of these steps are needed).
1915 if (!Introduced.empty() && !Deprecated.empty() &&
1916 !(Introduced <= Deprecated)) {
1917 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
1918 << 1 << PlatformName << Deprecated.getAsString()
1919 << 0 << Introduced.getAsString();
1920 return true;
1921 }
1922
1923 if (!Introduced.empty() && !Obsoleted.empty() &&
1924 !(Introduced <= Obsoleted)) {
1925 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
1926 << 2 << PlatformName << Obsoleted.getAsString()
1927 << 0 << Introduced.getAsString();
1928 return true;
1929 }
1930
1931 if (!Deprecated.empty() && !Obsoleted.empty() &&
1932 !(Deprecated <= Obsoleted)) {
1933 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
1934 << 2 << PlatformName << Obsoleted.getAsString()
1935 << 1 << Deprecated.getAsString();
1936 return true;
1937 }
1938
1939 return false;
1940}
1941
Douglas Gregor66a8ca02013-01-15 22:43:08 +00001942/// \brief Check whether the two versions match.
1943///
1944/// If either version tuple is empty, then they are assumed to match. If
1945/// \p BeforeIsOkay is true, then \p X can be less than or equal to \p Y.
1946static bool versionsMatch(const VersionTuple &X, const VersionTuple &Y,
1947 bool BeforeIsOkay) {
1948 if (X.empty() || Y.empty())
1949 return true;
1950
1951 if (X == Y)
1952 return true;
1953
1954 if (BeforeIsOkay && X < Y)
1955 return true;
1956
1957 return false;
1958}
1959
Rafael Espindolaa3aea432013-01-08 22:04:34 +00001960AvailabilityAttr *Sema::mergeAvailabilityAttr(NamedDecl *D, SourceRange Range,
Rafael Espindolae200f1c2012-05-13 03:25:18 +00001961 IdentifierInfo *Platform,
Manman Ren719a8642016-05-06 21:04:01 +00001962 bool Implicit,
Rafael Espindolae200f1c2012-05-13 03:25:18 +00001963 VersionTuple Introduced,
1964 VersionTuple Deprecated,
1965 VersionTuple Obsoleted,
1966 bool IsUnavailable,
Douglas Gregor66a8ca02013-01-15 22:43:08 +00001967 StringRef Message,
Manman Rend8039df2016-02-22 04:47:24 +00001968 bool IsStrict,
Manman Ren75bc6762016-03-21 17:30:55 +00001969 StringRef Replacement,
Douglas Gregord2a713e2015-09-30 21:27:42 +00001970 AvailabilityMergeKind AMK,
Michael Han99315932013-01-24 16:46:58 +00001971 unsigned AttrSpellingListIndex) {
Rafael Espindolac67f2232012-05-10 02:50:16 +00001972 VersionTuple MergedIntroduced = Introduced;
1973 VersionTuple MergedDeprecated = Deprecated;
1974 VersionTuple MergedObsoleted = Obsoleted;
Rafael Espindola2d243bf2012-05-06 19:56:25 +00001975 bool FoundAny = false;
Douglas Gregord2a713e2015-09-30 21:27:42 +00001976 bool OverrideOrImpl = false;
1977 switch (AMK) {
1978 case AMK_None:
1979 case AMK_Redeclaration:
1980 OverrideOrImpl = false;
1981 break;
1982
1983 case AMK_Override:
1984 case AMK_ProtocolImplementation:
1985 OverrideOrImpl = true;
1986 break;
1987 }
Rafael Espindola2d243bf2012-05-06 19:56:25 +00001988
Rafael Espindolac67f2232012-05-10 02:50:16 +00001989 if (D->hasAttrs()) {
1990 AttrVec &Attrs = D->getAttrs();
1991 for (unsigned i = 0, e = Attrs.size(); i != e;) {
1992 const AvailabilityAttr *OldAA = dyn_cast<AvailabilityAttr>(Attrs[i]);
1993 if (!OldAA) {
1994 ++i;
1995 continue;
1996 }
Rafael Espindola2d243bf2012-05-06 19:56:25 +00001997
Rafael Espindolac67f2232012-05-10 02:50:16 +00001998 IdentifierInfo *OldPlatform = OldAA->getPlatform();
1999 if (OldPlatform != Platform) {
2000 ++i;
2001 continue;
2002 }
2003
Tim Northover7a73cc72015-10-30 16:30:49 +00002004 // If there is an existing availability attribute for this platform that
2005 // is explicit and the new one is implicit use the explicit one and
2006 // discard the new implicit attribute.
Manman Ren719a8642016-05-06 21:04:01 +00002007 if (!OldAA->isImplicit() && Implicit) {
Tim Northover7a73cc72015-10-30 16:30:49 +00002008 return nullptr;
2009 }
2010
2011 // If there is an existing attribute for this platform that is implicit
2012 // and the new attribute is explicit then erase the old one and
2013 // continue processing the attributes.
Manman Ren719a8642016-05-06 21:04:01 +00002014 if (!Implicit && OldAA->isImplicit()) {
Tim Northover7a73cc72015-10-30 16:30:49 +00002015 Attrs.erase(Attrs.begin() + i);
2016 --e;
2017 continue;
2018 }
2019
Rafael Espindolac67f2232012-05-10 02:50:16 +00002020 FoundAny = true;
2021 VersionTuple OldIntroduced = OldAA->getIntroduced();
2022 VersionTuple OldDeprecated = OldAA->getDeprecated();
2023 VersionTuple OldObsoleted = OldAA->getObsoleted();
2024 bool OldIsUnavailable = OldAA->getUnavailable();
Rafael Espindolac67f2232012-05-10 02:50:16 +00002025
Douglas Gregord2a713e2015-09-30 21:27:42 +00002026 if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl) ||
2027 !versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl) ||
2028 !versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl) ||
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002029 !(OldIsUnavailable == IsUnavailable ||
Douglas Gregord2a713e2015-09-30 21:27:42 +00002030 (OverrideOrImpl && !OldIsUnavailable && IsUnavailable))) {
2031 if (OverrideOrImpl) {
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002032 int Which = -1;
2033 VersionTuple FirstVersion;
2034 VersionTuple SecondVersion;
Douglas Gregord2a713e2015-09-30 21:27:42 +00002035 if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl)) {
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002036 Which = 0;
2037 FirstVersion = OldIntroduced;
2038 SecondVersion = Introduced;
Douglas Gregord2a713e2015-09-30 21:27:42 +00002039 } else if (!versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl)) {
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002040 Which = 1;
2041 FirstVersion = Deprecated;
2042 SecondVersion = OldDeprecated;
Douglas Gregord2a713e2015-09-30 21:27:42 +00002043 } else if (!versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl)) {
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002044 Which = 2;
2045 FirstVersion = Obsoleted;
2046 SecondVersion = OldObsoleted;
2047 }
2048
2049 if (Which == -1) {
2050 Diag(OldAA->getLocation(),
2051 diag::warn_mismatched_availability_override_unavail)
Douglas Gregord2a713e2015-09-30 21:27:42 +00002052 << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
2053 << (AMK == AMK_Override);
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002054 } else {
2055 Diag(OldAA->getLocation(),
2056 diag::warn_mismatched_availability_override)
2057 << Which
2058 << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
Douglas Gregord2a713e2015-09-30 21:27:42 +00002059 << FirstVersion.getAsString() << SecondVersion.getAsString()
2060 << (AMK == AMK_Override);
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002061 }
Douglas Gregord2a713e2015-09-30 21:27:42 +00002062 if (AMK == AMK_Override)
2063 Diag(Range.getBegin(), diag::note_overridden_method);
2064 else
2065 Diag(Range.getBegin(), diag::note_protocol_method);
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002066 } else {
2067 Diag(OldAA->getLocation(), diag::warn_mismatched_availability);
2068 Diag(Range.getBegin(), diag::note_previous_attribute);
2069 }
2070
Rafael Espindolac67f2232012-05-10 02:50:16 +00002071 Attrs.erase(Attrs.begin() + i);
2072 --e;
2073 continue;
2074 }
2075
2076 VersionTuple MergedIntroduced2 = MergedIntroduced;
2077 VersionTuple MergedDeprecated2 = MergedDeprecated;
2078 VersionTuple MergedObsoleted2 = MergedObsoleted;
2079
2080 if (MergedIntroduced2.empty())
2081 MergedIntroduced2 = OldIntroduced;
2082 if (MergedDeprecated2.empty())
2083 MergedDeprecated2 = OldDeprecated;
2084 if (MergedObsoleted2.empty())
2085 MergedObsoleted2 = OldObsoleted;
2086
2087 if (checkAvailabilityAttr(*this, OldAA->getRange(), Platform,
2088 MergedIntroduced2, MergedDeprecated2,
2089 MergedObsoleted2)) {
2090 Attrs.erase(Attrs.begin() + i);
2091 --e;
2092 continue;
2093 }
2094
2095 MergedIntroduced = MergedIntroduced2;
2096 MergedDeprecated = MergedDeprecated2;
2097 MergedObsoleted = MergedObsoleted2;
2098 ++i;
Rafael Espindola2d243bf2012-05-06 19:56:25 +00002099 }
Rafael Espindola2d243bf2012-05-06 19:56:25 +00002100 }
2101
2102 if (FoundAny &&
2103 MergedIntroduced == Introduced &&
2104 MergedDeprecated == Deprecated &&
2105 MergedObsoleted == Obsoleted)
Craig Topperc3ec1492014-05-26 06:22:03 +00002106 return nullptr;
Rafael Espindola2d243bf2012-05-06 19:56:25 +00002107
Douglas Gregord2a713e2015-09-30 21:27:42 +00002108 // Only create a new attribute if !OverrideOrImpl, but we want to do
Ted Kremenekb5445722013-04-06 00:34:27 +00002109 // the checking.
Rafael Espindolac67f2232012-05-10 02:50:16 +00002110 if (!checkAvailabilityAttr(*this, Range, Platform, MergedIntroduced,
Ted Kremenekb5445722013-04-06 00:34:27 +00002111 MergedDeprecated, MergedObsoleted) &&
Douglas Gregord2a713e2015-09-30 21:27:42 +00002112 !OverrideOrImpl) {
Manman Ren719a8642016-05-06 21:04:01 +00002113 auto *Avail = ::new (Context) AvailabilityAttr(Range, Context, Platform,
Rafael Espindolae200f1c2012-05-13 03:25:18 +00002114 Introduced, Deprecated,
Michael Han99315932013-01-24 16:46:58 +00002115 Obsoleted, IsUnavailable, Message,
Manman Ren75bc6762016-03-21 17:30:55 +00002116 IsStrict, Replacement,
2117 AttrSpellingListIndex);
Manman Ren719a8642016-05-06 21:04:01 +00002118 Avail->setImplicit(Implicit);
2119 return Avail;
Rafael Espindola2d243bf2012-05-06 19:56:25 +00002120 }
Craig Topperc3ec1492014-05-26 06:22:03 +00002121 return nullptr;
Rafael Espindola2d243bf2012-05-06 19:56:25 +00002122}
2123
Chandler Carruthedc2c642011-07-02 00:01:44 +00002124static void handleAvailabilityAttr(Sema &S, Decl *D,
2125 const AttributeList &Attr) {
Aaron Ballman00e99962013-08-31 01:11:41 +00002126 if (!checkAttributeNumArgs(S, Attr, 1))
2127 return;
2128 IdentifierLoc *Platform = Attr.getArgAsIdent(0);
Michael Han99315932013-01-24 16:46:58 +00002129 unsigned Index = Attr.getAttributeSpellingListIndex();
2130
Aaron Ballman00e99962013-08-31 01:11:41 +00002131 IdentifierInfo *II = Platform->Ident;
2132 if (AvailabilityAttr::getPrettyPlatformName(II->getName()).empty())
2133 S.Diag(Platform->Loc, diag::warn_availability_unknown_platform)
2134 << Platform->Ident;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00002135
Rafael Espindolac231fab2013-01-08 21:30:32 +00002136 NamedDecl *ND = dyn_cast<NamedDecl>(D);
2137 if (!ND) {
2138 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
2139 return;
2140 }
2141
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00002142 AvailabilityChange Introduced = Attr.getAvailabilityIntroduced();
2143 AvailabilityChange Deprecated = Attr.getAvailabilityDeprecated();
2144 AvailabilityChange Obsoleted = Attr.getAvailabilityObsoleted();
Douglas Gregor7ab142b2011-03-26 03:35:55 +00002145 bool IsUnavailable = Attr.getUnavailableLoc().isValid();
Manman Rend8039df2016-02-22 04:47:24 +00002146 bool IsStrict = Attr.getStrictLoc().isValid();
Fariborz Jahanian88d510d2011-12-10 00:28:41 +00002147 StringRef Str;
Benjamin Kramera9dfa922013-09-13 17:31:48 +00002148 if (const StringLiteral *SE =
2149 dyn_cast_or_null<StringLiteral>(Attr.getMessageExpr()))
Fariborz Jahanian88d510d2011-12-10 00:28:41 +00002150 Str = SE->getString();
Manman Ren75bc6762016-03-21 17:30:55 +00002151 StringRef Replacement;
2152 if (const StringLiteral *SE =
2153 dyn_cast_or_null<StringLiteral>(Attr.getReplacementExpr()))
2154 Replacement = SE->getString();
Rafael Espindola2d243bf2012-05-06 19:56:25 +00002155
Aaron Ballman00e99962013-08-31 01:11:41 +00002156 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND, Attr.getRange(), II,
Manman Ren719a8642016-05-06 21:04:01 +00002157 false/*Implicit*/,
Rafael Espindolae200f1c2012-05-13 03:25:18 +00002158 Introduced.Version,
2159 Deprecated.Version,
2160 Obsoleted.Version,
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002161 IsUnavailable, Str,
Manman Ren75bc6762016-03-21 17:30:55 +00002162 IsStrict, Replacement,
Douglas Gregord2a713e2015-09-30 21:27:42 +00002163 Sema::AMK_None,
Michael Han99315932013-01-24 16:46:58 +00002164 Index);
Rafael Espindola19de5612013-01-12 06:42:30 +00002165 if (NewAttr)
Rafael Espindolae200f1c2012-05-13 03:25:18 +00002166 D->addAttr(NewAttr);
Tim Northover7a73cc72015-10-30 16:30:49 +00002167
2168 // Transcribe "ios" to "watchos" (and add a new attribute) if the versioning
2169 // matches before the start of the watchOS platform.
2170 if (S.Context.getTargetInfo().getTriple().isWatchOS()) {
2171 IdentifierInfo *NewII = nullptr;
2172 if (II->getName() == "ios")
2173 NewII = &S.Context.Idents.get("watchos");
2174 else if (II->getName() == "ios_app_extension")
2175 NewII = &S.Context.Idents.get("watchos_app_extension");
2176
2177 if (NewII) {
2178 auto adjustWatchOSVersion = [](VersionTuple Version) -> VersionTuple {
2179 if (Version.empty())
2180 return Version;
2181 auto Major = Version.getMajor();
2182 auto NewMajor = Major >= 9 ? Major - 7 : 0;
2183 if (NewMajor >= 2) {
2184 if (Version.getMinor().hasValue()) {
2185 if (Version.getSubminor().hasValue())
2186 return VersionTuple(NewMajor, Version.getMinor().getValue(),
2187 Version.getSubminor().getValue());
2188 else
2189 return VersionTuple(NewMajor, Version.getMinor().getValue());
2190 }
2191 }
2192
2193 return VersionTuple(2, 0);
2194 };
2195
2196 auto NewIntroduced = adjustWatchOSVersion(Introduced.Version);
2197 auto NewDeprecated = adjustWatchOSVersion(Deprecated.Version);
2198 auto NewObsoleted = adjustWatchOSVersion(Obsoleted.Version);
2199
2200 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND,
Manman Ren719a8642016-05-06 21:04:01 +00002201 Attr.getRange(),
Tim Northover7a73cc72015-10-30 16:30:49 +00002202 NewII,
Manman Ren719a8642016-05-06 21:04:01 +00002203 true/*Implicit*/,
Tim Northover7a73cc72015-10-30 16:30:49 +00002204 NewIntroduced,
2205 NewDeprecated,
2206 NewObsoleted,
2207 IsUnavailable, Str,
Manman Rend8039df2016-02-22 04:47:24 +00002208 IsStrict,
Manman Ren75bc6762016-03-21 17:30:55 +00002209 Replacement,
Tim Northover7a73cc72015-10-30 16:30:49 +00002210 Sema::AMK_None,
2211 Index);
2212 if (NewAttr)
2213 D->addAttr(NewAttr);
2214 }
2215 } else if (S.Context.getTargetInfo().getTriple().isTvOS()) {
2216 // Transcribe "ios" to "tvos" (and add a new attribute) if the versioning
2217 // matches before the start of the tvOS platform.
2218 IdentifierInfo *NewII = nullptr;
2219 if (II->getName() == "ios")
2220 NewII = &S.Context.Idents.get("tvos");
2221 else if (II->getName() == "ios_app_extension")
2222 NewII = &S.Context.Idents.get("tvos_app_extension");
2223
2224 if (NewII) {
2225 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND,
Manman Ren719a8642016-05-06 21:04:01 +00002226 Attr.getRange(),
Tim Northover7a73cc72015-10-30 16:30:49 +00002227 NewII,
Manman Ren719a8642016-05-06 21:04:01 +00002228 true/*Implicit*/,
Tim Northover7a73cc72015-10-30 16:30:49 +00002229 Introduced.Version,
2230 Deprecated.Version,
2231 Obsoleted.Version,
2232 IsUnavailable, Str,
Manman Rend8039df2016-02-22 04:47:24 +00002233 IsStrict,
Manman Ren75bc6762016-03-21 17:30:55 +00002234 Replacement,
Tim Northover7a73cc72015-10-30 16:30:49 +00002235 Sema::AMK_None,
2236 Index);
2237 if (NewAttr)
2238 D->addAttr(NewAttr);
2239 }
2240 }
Rafael Espindolac67f2232012-05-10 02:50:16 +00002241}
2242
John McCalld041a9b2013-02-20 01:54:26 +00002243template <class T>
2244static T *mergeVisibilityAttr(Sema &S, Decl *D, SourceRange range,
2245 typename T::VisibilityType value,
2246 unsigned attrSpellingListIndex) {
2247 T *existingAttr = D->getAttr<T>();
2248 if (existingAttr) {
2249 typename T::VisibilityType existingValue = existingAttr->getVisibility();
2250 if (existingValue == value)
Craig Topperc3ec1492014-05-26 06:22:03 +00002251 return nullptr;
John McCalld041a9b2013-02-20 01:54:26 +00002252 S.Diag(existingAttr->getLocation(), diag::err_mismatched_visibility);
2253 S.Diag(range.getBegin(), diag::note_previous_attribute);
2254 D->dropAttr<T>();
2255 }
2256 return ::new (S.Context) T(range, S.Context, value, attrSpellingListIndex);
2257}
2258
Rafael Espindolae200f1c2012-05-13 03:25:18 +00002259VisibilityAttr *Sema::mergeVisibilityAttr(Decl *D, SourceRange Range,
Michael Han99315932013-01-24 16:46:58 +00002260 VisibilityAttr::VisibilityType Vis,
2261 unsigned AttrSpellingListIndex) {
John McCalld041a9b2013-02-20 01:54:26 +00002262 return ::mergeVisibilityAttr<VisibilityAttr>(*this, D, Range, Vis,
2263 AttrSpellingListIndex);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00002264}
2265
John McCalld041a9b2013-02-20 01:54:26 +00002266TypeVisibilityAttr *Sema::mergeTypeVisibilityAttr(Decl *D, SourceRange Range,
2267 TypeVisibilityAttr::VisibilityType Vis,
2268 unsigned AttrSpellingListIndex) {
2269 return ::mergeVisibilityAttr<TypeVisibilityAttr>(*this, D, Range, Vis,
2270 AttrSpellingListIndex);
2271}
2272
2273static void handleVisibilityAttr(Sema &S, Decl *D, const AttributeList &Attr,
2274 bool isTypeVisibility) {
2275 // Visibility attributes don't mean anything on a typedef.
2276 if (isa<TypedefNameDecl>(D)) {
2277 S.Diag(Attr.getRange().getBegin(), diag::warn_attribute_ignored)
2278 << Attr.getName();
2279 return;
2280 }
2281
2282 // 'type_visibility' can only go on a type or namespace.
2283 if (isTypeVisibility &&
2284 !(isa<TagDecl>(D) ||
2285 isa<ObjCInterfaceDecl>(D) ||
2286 isa<NamespaceDecl>(D))) {
2287 S.Diag(Attr.getRange().getBegin(), diag::err_attribute_wrong_decl_type)
2288 << Attr.getName() << ExpectedTypeOrNamespace;
2289 return;
2290 }
2291
Benjamin Kramer70370212013-09-09 15:08:57 +00002292 // Check that the argument is a string literal.
Benjamin Kramer6ee15622013-09-13 15:35:43 +00002293 StringRef TypeStr;
2294 SourceLocation LiteralLoc;
Tim Northover6a6b63b2013-10-01 14:34:18 +00002295 if (!S.checkStringLiteralArgumentAttr(Attr, 0, TypeStr, &LiteralLoc))
Chris Lattner2c6fcf52008-06-26 18:38:35 +00002296 return;
Mike Stumpd3bb5572009-07-24 19:02:52 +00002297
Alexis Huntdcfba7b2010-08-18 23:23:40 +00002298 VisibilityAttr::VisibilityType type;
Aaron Ballman682ee422013-09-11 19:47:58 +00002299 if (!VisibilityAttr::ConvertStrToVisibilityType(TypeStr, type)) {
Benjamin Kramer6ee15622013-09-13 15:35:43 +00002300 S.Diag(LiteralLoc, diag::warn_attribute_type_not_supported)
Aaron Ballman682ee422013-09-11 19:47:58 +00002301 << Attr.getName() << TypeStr;
Chris Lattner2c6fcf52008-06-26 18:38:35 +00002302 return;
2303 }
Aaron Ballman682ee422013-09-11 19:47:58 +00002304
2305 // Complain about attempts to use protected visibility on targets
2306 // (like Darwin) that don't support it.
2307 if (type == VisibilityAttr::Protected &&
2308 !S.Context.getTargetInfo().hasProtectedVisibility()) {
2309 S.Diag(Attr.getLoc(), diag::warn_attribute_protected_visibility);
2310 type = VisibilityAttr::Default;
2311 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00002312
Michael Han99315932013-01-24 16:46:58 +00002313 unsigned Index = Attr.getAttributeSpellingListIndex();
John McCalld041a9b2013-02-20 01:54:26 +00002314 clang::Attr *newAttr;
2315 if (isTypeVisibility) {
2316 newAttr = S.mergeTypeVisibilityAttr(D, Attr.getRange(),
2317 (TypeVisibilityAttr::VisibilityType) type,
2318 Index);
2319 } else {
2320 newAttr = S.mergeVisibilityAttr(D, Attr.getRange(), type, Index);
2321 }
2322 if (newAttr)
2323 D->addAttr(newAttr);
Chris Lattner2c6fcf52008-06-26 18:38:35 +00002324}
2325
Chandler Carruthedc2c642011-07-02 00:01:44 +00002326static void handleObjCMethodFamilyAttr(Sema &S, Decl *decl,
2327 const AttributeList &Attr) {
Aaron Ballman74eeeae2013-11-27 13:27:02 +00002328 ObjCMethodDecl *method = cast<ObjCMethodDecl>(decl);
Aaron Ballman00e99962013-08-31 01:11:41 +00002329 if (!Attr.isArgIdent(0)) {
2330 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2331 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
John McCall86bc21f2011-03-02 11:33:24 +00002332 return;
2333 }
Aaron Ballman00e99962013-08-31 01:11:41 +00002334
Aaron Ballman682ee422013-09-11 19:47:58 +00002335 IdentifierLoc *IL = Attr.getArgAsIdent(0);
2336 ObjCMethodFamilyAttr::FamilyKind F;
2337 if (!ObjCMethodFamilyAttr::ConvertStrToFamilyKind(IL->Ident->getName(), F)) {
2338 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << Attr.getName()
2339 << IL->Ident;
John McCall86bc21f2011-03-02 11:33:24 +00002340 return;
2341 }
2342
Alp Toker314cc812014-01-25 16:55:45 +00002343 if (F == ObjCMethodFamilyAttr::OMF_init &&
2344 !method->getReturnType()->isObjCObjectPointerType()) {
John McCall31168b02011-06-15 23:02:42 +00002345 S.Diag(method->getLocation(), diag::err_init_method_bad_return_type)
Alp Toker314cc812014-01-25 16:55:45 +00002346 << method->getReturnType();
John McCall31168b02011-06-15 23:02:42 +00002347 // Ignore the attribute.
2348 return;
2349 }
2350
Argyrios Kyrtzidis309b4c42011-09-13 16:05:58 +00002351 method->addAttr(new (S.Context) ObjCMethodFamilyAttr(Attr.getRange(),
Aaron Ballman36a53502014-01-16 13:03:14 +00002352 S.Context, F,
2353 Attr.getAttributeSpellingListIndex()));
John McCall86bc21f2011-03-02 11:33:24 +00002354}
2355
Chandler Carruthedc2c642011-07-02 00:01:44 +00002356static void handleObjCNSObject(Sema &S, Decl *D, const AttributeList &Attr) {
Richard Smithdda56e42011-04-15 14:24:37 +00002357 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
Fariborz Jahanian255c0952009-01-13 23:34:40 +00002358 QualType T = TD->getUnderlyingType();
Ted Kremenek7712eef2012-08-29 22:54:47 +00002359 if (!T->isCARCBridgableType()) {
Fariborz Jahanian255c0952009-01-13 23:34:40 +00002360 S.Diag(TD->getLocation(), diag::err_nsobject_attribute);
2361 return;
2362 }
2363 }
Fariborz Jahanianbebd0ba2012-05-31 23:18:32 +00002364 else if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) {
2365 QualType T = PD->getType();
Ted Kremenek7712eef2012-08-29 22:54:47 +00002366 if (!T->isCARCBridgableType()) {
Fariborz Jahanianbebd0ba2012-05-31 23:18:32 +00002367 S.Diag(PD->getLocation(), diag::err_nsobject_attribute);
2368 return;
2369 }
2370 }
2371 else {
Ted Kremenek05e916b2012-03-01 01:40:32 +00002372 // It is okay to include this attribute on properties, e.g.:
2373 //
2374 // @property (retain, nonatomic) struct Bork *Q __attribute__((NSObject));
2375 //
2376 // In this case it follows tradition and suppresses an error in the above
2377 // case.
Fariborz Jahaniana45495a2011-11-29 01:48:40 +00002378 S.Diag(D->getLocation(), diag::warn_nsobject_attribute);
Ted Kremenek05e916b2012-03-01 01:40:32 +00002379 }
Michael Han99315932013-01-24 16:46:58 +00002380 D->addAttr(::new (S.Context)
2381 ObjCNSObjectAttr(Attr.getRange(), S.Context,
2382 Attr.getAttributeSpellingListIndex()));
Fariborz Jahanian255c0952009-01-13 23:34:40 +00002383}
2384
Fariborz Jahanian7a60b6d2015-04-16 18:38:44 +00002385static void handleObjCIndependentClass(Sema &S, Decl *D, const AttributeList &Attr) {
2386 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
2387 QualType T = TD->getUnderlyingType();
2388 if (!T->isObjCObjectPointerType()) {
2389 S.Diag(TD->getLocation(), diag::warn_ptr_independentclass_attribute);
2390 return;
2391 }
2392 } else {
2393 S.Diag(D->getLocation(), diag::warn_independentclass_attribute);
2394 return;
2395 }
2396 D->addAttr(::new (S.Context)
2397 ObjCIndependentClassAttr(Attr.getRange(), S.Context,
2398 Attr.getAttributeSpellingListIndex()));
2399}
2400
Chandler Carruthedc2c642011-07-02 00:01:44 +00002401static void handleBlocksAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballman00e99962013-08-31 01:11:41 +00002402 if (!Attr.isArgIdent(0)) {
Aaron Ballman29982272013-07-23 14:03:57 +00002403 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
Aaron Ballman00e99962013-08-31 01:11:41 +00002404 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
Steve Naroff3405a732008-09-18 16:44:58 +00002405 return;
2406 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00002407
Aaron Ballman00e99962013-08-31 01:11:41 +00002408 IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident;
Alexis Huntdcfba7b2010-08-18 23:23:40 +00002409 BlocksAttr::BlockType type;
Aaron Ballman682ee422013-09-11 19:47:58 +00002410 if (!BlocksAttr::ConvertStrToBlockType(II->getName(), type)) {
2411 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
2412 << Attr.getName() << II;
Steve Naroff3405a732008-09-18 16:44:58 +00002413 return;
2414 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00002415
Michael Han99315932013-01-24 16:46:58 +00002416 D->addAttr(::new (S.Context)
2417 BlocksAttr(Attr.getRange(), S.Context, type,
2418 Attr.getAttributeSpellingListIndex()));
Steve Naroff3405a732008-09-18 16:44:58 +00002419}
2420
Chandler Carruthedc2c642011-07-02 00:01:44 +00002421static void handleSentinelAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballman18a78382013-11-21 00:28:23 +00002422 unsigned sentinel = (unsigned)SentinelAttr::DefaultSentinel;
Anders Carlssonc181b012008-10-05 18:05:59 +00002423 if (Attr.getNumArgs() > 0) {
Aaron Ballman00e99962013-08-31 01:11:41 +00002424 Expr *E = Attr.getArgAsExpr(0);
Anders Carlssonc181b012008-10-05 18:05:59 +00002425 llvm::APSInt Idx(32);
Douglas Gregorbdb604a2010-05-18 23:01:22 +00002426 if (E->isTypeDependent() || E->isValueDependent() ||
2427 !E->isIntegerConstantExpr(Idx, S.Context)) {
Aaron Ballman29982272013-07-23 14:03:57 +00002428 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
Aaron Ballman3bf758c2013-07-30 01:31:03 +00002429 << Attr.getName() << 1 << AANT_ArgumentIntegerConstant
Aaron Ballman29982272013-07-23 14:03:57 +00002430 << E->getSourceRange();
Anders Carlssonc181b012008-10-05 18:05:59 +00002431 return;
2432 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00002433
John McCallb46f2872011-09-09 07:56:05 +00002434 if (Idx.isSigned() && Idx.isNegative()) {
Chris Lattner3b054132008-11-19 05:08:23 +00002435 S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_less_than_zero)
2436 << E->getSourceRange();
Anders Carlssonc181b012008-10-05 18:05:59 +00002437 return;
2438 }
John McCallb46f2872011-09-09 07:56:05 +00002439
2440 sentinel = Idx.getZExtValue();
Anders Carlssonc181b012008-10-05 18:05:59 +00002441 }
2442
Aaron Ballman18a78382013-11-21 00:28:23 +00002443 unsigned nullPos = (unsigned)SentinelAttr::DefaultNullPos;
Anders Carlssonc181b012008-10-05 18:05:59 +00002444 if (Attr.getNumArgs() > 1) {
Aaron Ballman00e99962013-08-31 01:11:41 +00002445 Expr *E = Attr.getArgAsExpr(1);
Anders Carlssonc181b012008-10-05 18:05:59 +00002446 llvm::APSInt Idx(32);
Douglas Gregorbdb604a2010-05-18 23:01:22 +00002447 if (E->isTypeDependent() || E->isValueDependent() ||
2448 !E->isIntegerConstantExpr(Idx, S.Context)) {
Aaron Ballman29982272013-07-23 14:03:57 +00002449 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
Aaron Ballman3bf758c2013-07-30 01:31:03 +00002450 << Attr.getName() << 2 << AANT_ArgumentIntegerConstant
Aaron Ballman29982272013-07-23 14:03:57 +00002451 << E->getSourceRange();
Anders Carlssonc181b012008-10-05 18:05:59 +00002452 return;
2453 }
2454 nullPos = Idx.getZExtValue();
Mike Stumpd3bb5572009-07-24 19:02:52 +00002455
John McCallb46f2872011-09-09 07:56:05 +00002456 if ((Idx.isSigned() && Idx.isNegative()) || nullPos > 1) {
Anders Carlssonc181b012008-10-05 18:05:59 +00002457 // FIXME: This error message could be improved, it would be nice
2458 // to say what the bounds actually are.
Chris Lattner3b054132008-11-19 05:08:23 +00002459 S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_not_zero_or_one)
2460 << E->getSourceRange();
Anders Carlssonc181b012008-10-05 18:05:59 +00002461 return;
2462 }
2463 }
2464
Chandler Carruthff4c4f02011-07-01 23:49:12 +00002465 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
John McCallb46f2872011-09-09 07:56:05 +00002466 const FunctionType *FT = FD->getType()->castAs<FunctionType>();
Chris Lattner9363e312009-03-17 23:03:47 +00002467 if (isa<FunctionNoProtoType>(FT)) {
2468 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_named_arguments);
2469 return;
2470 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00002471
Chris Lattner9363e312009-03-17 23:03:47 +00002472 if (!cast<FunctionProtoType>(FT)->isVariadic()) {
Fariborz Jahanian6802ed92009-05-15 21:18:04 +00002473 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
Anders Carlssonc181b012008-10-05 18:05:59 +00002474 return;
Mike Stumpd3bb5572009-07-24 19:02:52 +00002475 }
Chandler Carruthff4c4f02011-07-01 23:49:12 +00002476 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Anders Carlssonc181b012008-10-05 18:05:59 +00002477 if (!MD->isVariadic()) {
Fariborz Jahanian6802ed92009-05-15 21:18:04 +00002478 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
Anders Carlssonc181b012008-10-05 18:05:59 +00002479 return;
Fariborz Jahanian6607b212009-05-14 20:53:39 +00002480 }
Eli Friedman5c5e3b72012-01-06 01:23:10 +00002481 } else if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
2482 if (!BD->isVariadic()) {
2483 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 1;
2484 return;
2485 }
Chandler Carruthff4c4f02011-07-01 23:49:12 +00002486 } else if (const VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahanian6607b212009-05-14 20:53:39 +00002487 QualType Ty = V->getType();
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00002488 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
Aaron Ballman12b9f652014-01-16 13:55:42 +00002489 const FunctionType *FT = Ty->isFunctionPointerType()
2490 ? D->getFunctionType()
Eric Christopherbc638a82010-12-01 22:13:54 +00002491 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Fariborz Jahanian6607b212009-05-14 20:53:39 +00002492 if (!cast<FunctionProtoType>(FT)->isVariadic()) {
Fariborz Jahanian6802ed92009-05-15 21:18:04 +00002493 int m = Ty->isFunctionPointerType() ? 0 : 1;
2494 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << m;
Fariborz Jahanian6607b212009-05-14 20:53:39 +00002495 return;
2496 }
Mike Stump12b8ce12009-08-04 21:02:39 +00002497 } else {
Fariborz Jahanian6607b212009-05-14 20:53:39 +00002498 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
John McCall5fca7ea2011-03-02 12:29:23 +00002499 << Attr.getName() << ExpectedFunctionMethodOrBlock;
Fariborz Jahanian6607b212009-05-14 20:53:39 +00002500 return;
2501 }
Anders Carlssonc181b012008-10-05 18:05:59 +00002502 } else {
Chris Lattner3b054132008-11-19 05:08:23 +00002503 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
John McCall5fca7ea2011-03-02 12:29:23 +00002504 << Attr.getName() << ExpectedFunctionMethodOrBlock;
Anders Carlssonc181b012008-10-05 18:05:59 +00002505 return;
2506 }
Michael Han99315932013-01-24 16:46:58 +00002507 D->addAttr(::new (S.Context)
2508 SentinelAttr(Attr.getRange(), S.Context, sentinel, nullPos,
2509 Attr.getAttributeSpellingListIndex()));
Anders Carlssonc181b012008-10-05 18:05:59 +00002510}
2511
Chandler Carruthedc2c642011-07-02 00:01:44 +00002512static void handleWarnUnusedResult(Sema &S, Decl *D, const AttributeList &Attr) {
Alp Toker314cc812014-01-25 16:55:45 +00002513 if (D->getFunctionType() &&
2514 D->getFunctionType()->getReturnType()->isVoidType()) {
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +00002515 S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method)
2516 << Attr.getName() << 0;
Nuno Lopes56abcbd2009-12-22 23:59:52 +00002517 return;
2518 }
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +00002519 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
Alp Toker314cc812014-01-25 16:55:45 +00002520 if (MD->getReturnType()->isVoidType()) {
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +00002521 S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method)
2522 << Attr.getName() << 1;
2523 return;
2524 }
2525
Aaron Ballmane7964782016-03-07 22:44:55 +00002526 // If this is spelled as the standard C++1z attribute, but not in C++1z, warn
2527 // about using it as an extension.
2528 if (!S.getLangOpts().CPlusPlus1z && Attr.isCXX11Attribute() &&
2529 !Attr.getScopeName())
Richard Smith4f902c72016-03-08 00:32:55 +00002530 S.Diag(Attr.getLoc(), diag::ext_cxx1z_attr) << Attr.getName();
Aaron Ballmane7964782016-03-07 22:44:55 +00002531
Michael Han99315932013-01-24 16:46:58 +00002532 D->addAttr(::new (S.Context)
2533 WarnUnusedResultAttr(Attr.getRange(), S.Context,
2534 Attr.getAttributeSpellingListIndex()));
Chris Lattner237f2752009-02-14 07:37:35 +00002535}
2536
Chandler Carruthedc2c642011-07-02 00:01:44 +00002537static void handleWeakImportAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Daniel Dunbar5cb85eb2009-03-06 06:39:57 +00002538 // weak_import only applies to variable & function declarations.
2539 bool isDef = false;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00002540 if (!D->canBeWeakImported(isDef)) {
2541 if (isDef)
Reid Kleckner52d598e2013-05-20 21:53:29 +00002542 S.Diag(Attr.getLoc(), diag::warn_attribute_invalid_on_definition)
2543 << "weak_import";
Douglas Gregord71149a2011-03-23 13:27:51 +00002544 else if (isa<ObjCPropertyDecl>(D) || isa<ObjCMethodDecl>(D) ||
Douglas Gregore8bbc122011-09-02 00:18:52 +00002545 (S.Context.getTargetInfo().getTriple().isOSDarwin() &&
Fariborz Jahanian3249a1e2011-10-26 23:59:12 +00002546 (isa<ObjCInterfaceDecl>(D) || isa<EnumDecl>(D)))) {
Douglas Gregord71149a2011-03-23 13:27:51 +00002547 // Nothing to warn about here.
2548 } else
Fariborz Jahanianea70a172010-04-13 20:22:35 +00002549 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
John McCall5fca7ea2011-03-02 12:29:23 +00002550 << Attr.getName() << ExpectedVariableOrFunction;
Daniel Dunbar5cb85eb2009-03-06 06:39:57 +00002551
Daniel Dunbar5cb85eb2009-03-06 06:39:57 +00002552 return;
2553 }
2554
Michael Han99315932013-01-24 16:46:58 +00002555 D->addAttr(::new (S.Context)
2556 WeakImportAttr(Attr.getRange(), S.Context,
2557 Attr.getAttributeSpellingListIndex()));
Daniel Dunbar5cb85eb2009-03-06 06:39:57 +00002558}
2559
Tanya Lattnerbcffcdf2012-07-09 22:06:01 +00002560// Handles reqd_work_group_size and work_group_size_hint.
Aaron Ballman1d0d2a42013-12-02 22:38:33 +00002561template <typename WorkGroupAttr>
Tanya Lattnerbcffcdf2012-07-09 22:06:01 +00002562static void handleWorkGroupSize(Sema &S, Decl *D,
Nick Lewyckyb9e4a3a2012-07-24 01:31:55 +00002563 const AttributeList &Attr) {
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00002564 uint32_t WGSize[3];
Joey Goulyb1d23a82014-05-19 14:41:38 +00002565 for (unsigned i = 0; i < 3; ++i) {
2566 const Expr *E = Attr.getArgAsExpr(i);
2567 if (!checkUInt32Argument(S, Attr, E, WGSize[i], i))
Nate Begemanf2758702009-06-26 06:32:41 +00002568 return;
Joey Goulyb1d23a82014-05-19 14:41:38 +00002569 if (WGSize[i] == 0) {
2570 S.Diag(Attr.getLoc(), diag::err_attribute_argument_is_zero)
2571 << Attr.getName() << E->getSourceRange();
2572 return;
2573 }
2574 }
Tanya Lattnerbcffcdf2012-07-09 22:06:01 +00002575
Aaron Ballman1d0d2a42013-12-02 22:38:33 +00002576 WorkGroupAttr *Existing = D->getAttr<WorkGroupAttr>();
2577 if (Existing && !(Existing->getXDim() == WGSize[0] &&
2578 Existing->getYDim() == WGSize[1] &&
2579 Existing->getZDim() == WGSize[2]))
2580 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) << Attr.getName();
Tanya Lattnerbcffcdf2012-07-09 22:06:01 +00002581
Aaron Ballman1d0d2a42013-12-02 22:38:33 +00002582 D->addAttr(::new (S.Context) WorkGroupAttr(Attr.getRange(), S.Context,
2583 WGSize[0], WGSize[1], WGSize[2],
Michael Han99315932013-01-24 16:46:58 +00002584 Attr.getAttributeSpellingListIndex()));
Nate Begemanf2758702009-06-26 06:32:41 +00002585}
2586
Joey Goulyaba589c2013-03-08 09:42:32 +00002587static void handleVecTypeHint(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballman00e99962013-08-31 01:11:41 +00002588 if (!Attr.hasParsedType()) {
2589 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
2590 << Attr.getName() << 1;
2591 return;
2592 }
2593
Craig Topperc3ec1492014-05-26 06:22:03 +00002594 TypeSourceInfo *ParmTSI = nullptr;
Richard Smithb87c4652013-10-31 21:23:20 +00002595 QualType ParmType = S.GetTypeFromParser(Attr.getTypeArg(), &ParmTSI);
2596 assert(ParmTSI && "no type source info for attribute argument");
Joey Goulyaba589c2013-03-08 09:42:32 +00002597
2598 if (!ParmType->isExtVectorType() && !ParmType->isFloatingType() &&
2599 (ParmType->isBooleanType() ||
2600 !ParmType->isIntegralType(S.getASTContext()))) {
2601 S.Diag(Attr.getLoc(), diag::err_attribute_argument_vec_type_hint)
2602 << ParmType;
2603 return;
2604 }
2605
Aaron Ballmana9e05402013-12-02 22:16:55 +00002606 if (VecTypeHintAttr *A = D->getAttr<VecTypeHintAttr>()) {
Richard Smithb87c4652013-10-31 21:23:20 +00002607 if (!S.Context.hasSameType(A->getTypeHint(), ParmType)) {
Joey Goulyaba589c2013-03-08 09:42:32 +00002608 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) << Attr.getName();
2609 return;
2610 }
2611 }
2612
2613 D->addAttr(::new (S.Context) VecTypeHintAttr(Attr.getLoc(), S.Context,
Aaron Ballman36a53502014-01-16 13:03:14 +00002614 ParmTSI,
2615 Attr.getAttributeSpellingListIndex()));
Joey Goulyaba589c2013-03-08 09:42:32 +00002616}
2617
Rafael Espindolae200f1c2012-05-13 03:25:18 +00002618SectionAttr *Sema::mergeSectionAttr(Decl *D, SourceRange Range,
Michael Han99315932013-01-24 16:46:58 +00002619 StringRef Name,
2620 unsigned AttrSpellingListIndex) {
Rafael Espindola9869c3a2012-05-13 02:42:42 +00002621 if (SectionAttr *ExistingAttr = D->getAttr<SectionAttr>()) {
2622 if (ExistingAttr->getName() == Name)
Craig Topperc3ec1492014-05-26 06:22:03 +00002623 return nullptr;
Rafael Espindola9869c3a2012-05-13 02:42:42 +00002624 Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section);
2625 Diag(Range.getBegin(), diag::note_previous_attribute);
Craig Topperc3ec1492014-05-26 06:22:03 +00002626 return nullptr;
Rafael Espindola9869c3a2012-05-13 02:42:42 +00002627 }
Michael Han99315932013-01-24 16:46:58 +00002628 return ::new (Context) SectionAttr(Range, Context, Name,
2629 AttrSpellingListIndex);
Rafael Espindola9869c3a2012-05-13 02:42:42 +00002630}
2631
Reid Kleckner2a133222015-03-04 23:39:17 +00002632bool Sema::checkSectionName(SourceLocation LiteralLoc, StringRef SecName) {
2633 std::string Error = Context.getTargetInfo().isValidSectionSpecifier(SecName);
2634 if (!Error.empty()) {
2635 Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target) << Error;
2636 return false;
2637 }
2638 return true;
2639}
2640
Chandler Carruthedc2c642011-07-02 00:01:44 +00002641static void handleSectionAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Daniel Dunbar648bf782009-02-12 17:28:23 +00002642 // Make sure that there is a string literal as the sections's single
2643 // argument.
Benjamin Kramer6ee15622013-09-13 15:35:43 +00002644 StringRef Str;
2645 SourceLocation LiteralLoc;
Tim Northover6a6b63b2013-10-01 14:34:18 +00002646 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &LiteralLoc))
Daniel Dunbar648bf782009-02-12 17:28:23 +00002647 return;
Mike Stump11289f42009-09-09 15:08:12 +00002648
Reid Kleckner2a133222015-03-04 23:39:17 +00002649 if (!S.checkSectionName(LiteralLoc, Str))
2650 return;
2651
Chris Lattner30ba6742009-08-10 19:03:04 +00002652 // If the target wants to validate the section specifier, make it happen.
Benjamin Kramer6ee15622013-09-13 15:35:43 +00002653 std::string Error = S.Context.getTargetInfo().isValidSectionSpecifier(Str);
Chris Lattner20aee9b2010-01-12 20:58:53 +00002654 if (!Error.empty()) {
Benjamin Kramer6ee15622013-09-13 15:35:43 +00002655 S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target)
Chris Lattner20aee9b2010-01-12 20:58:53 +00002656 << Error;
Chris Lattner30ba6742009-08-10 19:03:04 +00002657 return;
2658 }
Mike Stump11289f42009-09-09 15:08:12 +00002659
Michael Han99315932013-01-24 16:46:58 +00002660 unsigned Index = Attr.getAttributeSpellingListIndex();
Benjamin Kramer6ee15622013-09-13 15:35:43 +00002661 SectionAttr *NewAttr = S.mergeSectionAttr(D, Attr.getRange(), Str, Index);
Rafael Espindolae200f1c2012-05-13 03:25:18 +00002662 if (NewAttr)
2663 D->addAttr(NewAttr);
Daniel Dunbar648bf782009-02-12 17:28:23 +00002664}
2665
Eric Christopher789a7ad2015-06-12 01:36:05 +00002666// Check for things we'd like to warn about, no errors or validation for now.
2667// TODO: Validation should use a backend target library that specifies
2668// the allowable subtarget features and cpus. We could use something like a
2669// TargetCodeGenInfo hook here to do validation.
2670void Sema::checkTargetAttr(SourceLocation LiteralLoc, StringRef AttrStr) {
2671 for (auto Str : {"tune=", "fpmath="})
2672 if (AttrStr.find(Str) != StringRef::npos)
2673 Diag(LiteralLoc, diag::warn_unsupported_target_attribute) << Str;
2674}
2675
Eric Christopher11acf732015-06-12 01:35:52 +00002676static void handleTargetAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Eric Christopher11acf732015-06-12 01:35:52 +00002677 StringRef Str;
2678 SourceLocation LiteralLoc;
2679 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &LiteralLoc))
2680 return;
Eric Christopher789a7ad2015-06-12 01:36:05 +00002681 S.checkTargetAttr(LiteralLoc, Str);
Eric Christopher11acf732015-06-12 01:35:52 +00002682 unsigned Index = Attr.getAttributeSpellingListIndex();
2683 TargetAttr *NewAttr =
2684 ::new (S.Context) TargetAttr(Attr.getRange(), S.Context, Str, Index);
2685 D->addAttr(NewAttr);
2686}
2687
Chandler Carruthedc2c642011-07-02 00:01:44 +00002688static void handleCleanupAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballman74eeeae2013-11-27 13:27:02 +00002689 VarDecl *VD = cast<VarDecl>(D);
2690 if (!VD->hasLocalStorage()) {
Aaron Ballmanc12aaff2013-09-11 01:37:41 +00002691 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
Anders Carlssond277d792009-01-31 01:16:18 +00002692 return;
2693 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00002694
Aaron Ballmanc12aaff2013-09-11 01:37:41 +00002695 Expr *E = Attr.getArgAsExpr(0);
2696 SourceLocation Loc = E->getExprLoc();
Craig Topperc3ec1492014-05-26 06:22:03 +00002697 FunctionDecl *FD = nullptr;
Aaron Ballmanc12aaff2013-09-11 01:37:41 +00002698 DeclarationNameInfo NI;
Aaron Ballman00e99962013-08-31 01:11:41 +00002699
Aaron Ballmanc12aaff2013-09-11 01:37:41 +00002700 // gcc only allows for simple identifiers. Since we support more than gcc, we
2701 // will warn the user.
2702 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
2703 if (DRE->hasQualifier())
2704 S.Diag(Loc, diag::warn_cleanup_ext);
2705 FD = dyn_cast<FunctionDecl>(DRE->getDecl());
2706 NI = DRE->getNameInfo();
2707 if (!FD) {
2708 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 1
2709 << NI.getName();
2710 return;
2711 }
2712 } else if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
2713 if (ULE->hasExplicitTemplateArgs())
2714 S.Diag(Loc, diag::warn_cleanup_ext);
Aaron Ballmanc12aaff2013-09-11 01:37:41 +00002715 FD = S.ResolveSingleFunctionTemplateSpecialization(ULE, true);
2716 NI = ULE->getNameInfo();
Alp Toker67b47ac2013-10-20 18:48:56 +00002717 if (!FD) {
2718 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 2
2719 << NI.getName();
2720 if (ULE->getType() == S.Context.OverloadTy)
2721 S.NoteAllOverloadCandidates(ULE);
2722 return;
2723 }
Aaron Ballmanc12aaff2013-09-11 01:37:41 +00002724 } else {
2725 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 0;
Anders Carlssond277d792009-01-31 01:16:18 +00002726 return;
2727 }
2728
Anders Carlssond277d792009-01-31 01:16:18 +00002729 if (FD->getNumParams() != 1) {
Aaron Ballmanc12aaff2013-09-11 01:37:41 +00002730 S.Diag(Loc, diag::err_attribute_cleanup_func_must_take_one_arg)
2731 << NI.getName();
Anders Carlssond277d792009-01-31 01:16:18 +00002732 return;
2733 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00002734
Anders Carlsson723f55d2009-02-07 23:16:50 +00002735 // We're currently more strict than GCC about what function types we accept.
2736 // If this ever proves to be a problem it should be easy to fix.
2737 QualType Ty = S.Context.getPointerType(VD->getType());
2738 QualType ParamTy = FD->getParamDecl(0)->getType();
Douglas Gregorc03a1082011-01-28 02:26:04 +00002739 if (S.CheckAssignmentConstraints(FD->getParamDecl(0)->getLocation(),
2740 ParamTy, Ty) != Sema::Compatible) {
Aaron Ballmanc12aaff2013-09-11 01:37:41 +00002741 S.Diag(Loc, diag::err_attribute_cleanup_func_arg_incompatible_type)
2742 << NI.getName() << ParamTy << Ty;
Anders Carlsson723f55d2009-02-07 23:16:50 +00002743 return;
2744 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00002745
Michael Han99315932013-01-24 16:46:58 +00002746 D->addAttr(::new (S.Context)
2747 CleanupAttr(Attr.getRange(), S.Context, FD,
2748 Attr.getAttributeSpellingListIndex()));
Anders Carlssond277d792009-01-31 01:16:18 +00002749}
2750
Mike Stumpd3bb5572009-07-24 19:02:52 +00002751/// Handle __attribute__((format_arg((idx)))) attribute based on
Bill Wendling44426052012-12-20 19:22:21 +00002752/// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
Chandler Carruthedc2c642011-07-02 00:01:44 +00002753static void handleFormatArgAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballman00e99962013-08-31 01:11:41 +00002754 Expr *IdxExpr = Attr.getArgAsExpr(0);
Alp Toker601b22c2014-01-21 23:35:24 +00002755 uint64_t Idx;
2756 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 1, IdxExpr, Idx))
Fariborz Jahanianf1c25022009-05-20 17:41:43 +00002757 return;
Chandler Carruth743682b2010-11-16 08:35:43 +00002758
Eric Christopherb64963e2015-08-13 21:34:35 +00002759 // Make sure the format string is really a string.
Alp Toker601b22c2014-01-21 23:35:24 +00002760 QualType Ty = getFunctionOrMethodParamType(D, Idx);
Mike Stumpd3bb5572009-07-24 19:02:52 +00002761
Eric Christopherb64963e2015-08-13 21:34:35 +00002762 bool NotNSStringTy = !isNSStringType(Ty, S.Context);
2763 if (NotNSStringTy &&
Fariborz Jahanianf1c25022009-05-20 17:41:43 +00002764 !isCFStringType(Ty, S.Context) &&
2765 (!Ty->isPointerType() ||
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002766 !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
Fariborz Jahanianf1c25022009-05-20 17:41:43 +00002767 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
Eric Christopherb64963e2015-08-13 21:34:35 +00002768 << "a string type" << IdxExpr->getSourceRange()
2769 << getFunctionOrMethodParamRange(D, 0);
Fariborz Jahanianf1c25022009-05-20 17:41:43 +00002770 return;
Mike Stumpd3bb5572009-07-24 19:02:52 +00002771 }
Chandler Carruthff4c4f02011-07-01 23:49:12 +00002772 Ty = getFunctionOrMethodResultType(D);
Fariborz Jahanianf1c25022009-05-20 17:41:43 +00002773 if (!isNSStringType(Ty, S.Context) &&
2774 !isCFStringType(Ty, S.Context) &&
2775 (!Ty->isPointerType() ||
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002776 !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
Fariborz Jahanianf1c25022009-05-20 17:41:43 +00002777 S.Diag(Attr.getLoc(), diag::err_format_attribute_result_not)
Eric Christopherb64963e2015-08-13 21:34:35 +00002778 << (NotNSStringTy ? "string type" : "NSString")
Aaron Ballman2f9e88b2014-08-04 15:17:29 +00002779 << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, 0);
Fariborz Jahanianf1c25022009-05-20 17:41:43 +00002780 return;
Mike Stumpd3bb5572009-07-24 19:02:52 +00002781 }
2782
Alp Toker601b22c2014-01-21 23:35:24 +00002783 // We cannot use the Idx returned from checkFunctionOrMethodParameterIndex
Aaron Ballmanbe50eb82013-07-30 00:48:57 +00002784 // because that has corrected for the implicit this parameter, and is zero-
2785 // based. The attribute expects what the user wrote explicitly.
2786 llvm::APSInt Val;
2787 IdxExpr->EvaluateAsInt(Val, S.Context);
2788
Michael Han99315932013-01-24 16:46:58 +00002789 D->addAttr(::new (S.Context)
Aaron Ballmanbe50eb82013-07-30 00:48:57 +00002790 FormatArgAttr(Attr.getRange(), S.Context, Val.getZExtValue(),
Michael Han99315932013-01-24 16:46:58 +00002791 Attr.getAttributeSpellingListIndex()));
Fariborz Jahanianf1c25022009-05-20 17:41:43 +00002792}
2793
Daniel Dunbarccbd9a42009-10-18 02:09:17 +00002794enum FormatAttrKind {
2795 CFStringFormat,
2796 NSStringFormat,
2797 StrftimeFormat,
2798 SupportedFormat,
Chris Lattner12161d32010-03-22 21:08:50 +00002799 IgnoredFormat,
Daniel Dunbarccbd9a42009-10-18 02:09:17 +00002800 InvalidFormat
2801};
2802
2803/// getFormatAttrKind - Map from format attribute names to supported format
2804/// types.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002805static FormatAttrKind getFormatAttrKind(StringRef Format) {
Benjamin Kramer96a44b62012-05-16 12:44:25 +00002806 return llvm::StringSwitch<FormatAttrKind>(Format)
2807 // Check for formats that get handled specially.
2808 .Case("NSString", NSStringFormat)
2809 .Case("CFString", CFStringFormat)
2810 .Case("strftime", StrftimeFormat)
Daniel Dunbarccbd9a42009-10-18 02:09:17 +00002811
Benjamin Kramer96a44b62012-05-16 12:44:25 +00002812 // Otherwise, check for supported formats.
2813 .Cases("scanf", "printf", "printf0", "strfmon", SupportedFormat)
2814 .Cases("cmn_err", "vcmn_err", "zcmn_err", SupportedFormat)
2815 .Case("kprintf", SupportedFormat) // OpenBSD.
Dimitry Andric6b5ed342015-02-19 22:32:33 +00002816 .Case("freebsd_kprintf", SupportedFormat) // FreeBSD.
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00002817 .Case("os_trace", SupportedFormat)
Daniel Dunbarccbd9a42009-10-18 02:09:17 +00002818
Benjamin Kramer96a44b62012-05-16 12:44:25 +00002819 .Cases("gcc_diag", "gcc_cdiag", "gcc_cxxdiag", "gcc_tdiag", IgnoredFormat)
2820 .Default(InvalidFormat);
Daniel Dunbarccbd9a42009-10-18 02:09:17 +00002821}
2822
Fariborz Jahanianef5f6212010-06-18 21:44:06 +00002823/// Handle __attribute__((init_priority(priority))) attributes based on
Bill Wendling44426052012-12-20 19:22:21 +00002824/// http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html
Chandler Carruthedc2c642011-07-02 00:01:44 +00002825static void handleInitPriorityAttr(Sema &S, Decl *D,
2826 const AttributeList &Attr) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002827 if (!S.getLangOpts().CPlusPlus) {
Fariborz Jahanianef5f6212010-06-18 21:44:06 +00002828 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
2829 return;
2830 }
2831
Aaron Ballman4a611152013-11-27 16:34:09 +00002832 if (S.getCurFunctionOrMethodDecl()) {
Fariborz Jahanian0bf5ee72010-06-18 23:14:53 +00002833 S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr);
2834 Attr.setInvalid();
2835 return;
2836 }
Aaron Ballman4a611152013-11-27 16:34:09 +00002837 QualType T = cast<VarDecl>(D)->getType();
Fariborz Jahanian0bf5ee72010-06-18 23:14:53 +00002838 if (S.Context.getAsArrayType(T))
2839 T = S.Context.getBaseElementType(T);
2840 if (!T->getAs<RecordType>()) {
2841 S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr);
2842 Attr.setInvalid();
2843 return;
2844 }
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00002845
2846 Expr *E = Attr.getArgAsExpr(0);
2847 uint32_t prioritynum;
2848 if (!checkUInt32Argument(S, Attr, E, prioritynum)) {
Fariborz Jahanianef5f6212010-06-18 21:44:06 +00002849 Attr.setInvalid();
2850 return;
2851 }
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00002852
Fariborz Jahanianef5f6212010-06-18 21:44:06 +00002853 if (prioritynum < 101 || prioritynum > 65535) {
2854 S.Diag(Attr.getLoc(), diag::err_attribute_argument_outof_range)
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002855 << E->getSourceRange() << Attr.getName() << 101 << 65535;
Fariborz Jahanianef5f6212010-06-18 21:44:06 +00002856 Attr.setInvalid();
2857 return;
2858 }
Michael Han99315932013-01-24 16:46:58 +00002859 D->addAttr(::new (S.Context)
2860 InitPriorityAttr(Attr.getRange(), S.Context, prioritynum,
2861 Attr.getAttributeSpellingListIndex()));
Fariborz Jahanianef5f6212010-06-18 21:44:06 +00002862}
2863
Aaron Ballmanf58070b2013-09-03 21:02:22 +00002864FormatAttr *Sema::mergeFormatAttr(Decl *D, SourceRange Range,
2865 IdentifierInfo *Format, int FormatIdx,
2866 int FirstArg,
Michael Han99315932013-01-24 16:46:58 +00002867 unsigned AttrSpellingListIndex) {
Rafael Espindola92d49452012-05-11 00:36:07 +00002868 // Check whether we already have an equivalent format attribute.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002869 for (auto *F : D->specific_attrs<FormatAttr>()) {
2870 if (F->getType() == Format &&
2871 F->getFormatIdx() == FormatIdx &&
2872 F->getFirstArg() == FirstArg) {
Rafael Espindola92d49452012-05-11 00:36:07 +00002873 // If we don't have a valid location for this attribute, adopt the
2874 // location.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002875 if (F->getLocation().isInvalid())
2876 F->setRange(Range);
Craig Topperc3ec1492014-05-26 06:22:03 +00002877 return nullptr;
Rafael Espindola92d49452012-05-11 00:36:07 +00002878 }
2879 }
2880
Aaron Ballmanf58070b2013-09-03 21:02:22 +00002881 return ::new (Context) FormatAttr(Range, Context, Format, FormatIdx,
2882 FirstArg, AttrSpellingListIndex);
Rafael Espindola92d49452012-05-11 00:36:07 +00002883}
2884
Mike Stumpd3bb5572009-07-24 19:02:52 +00002885/// Handle __attribute__((format(type,idx,firstarg))) attributes based on
Bill Wendling44426052012-12-20 19:22:21 +00002886/// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
Chandler Carruthedc2c642011-07-02 00:01:44 +00002887static void handleFormatAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballman00e99962013-08-31 01:11:41 +00002888 if (!Attr.isArgIdent(0)) {
Aaron Ballman29982272013-07-23 14:03:57 +00002889 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
Aaron Ballman00e99962013-08-31 01:11:41 +00002890 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
Chris Lattner2c6fcf52008-06-26 18:38:35 +00002891 return;
2892 }
Chris Lattner2c6fcf52008-06-26 18:38:35 +00002893
Chandler Carruth743682b2010-11-16 08:35:43 +00002894 // In C++ the implicit 'this' function parameter also counts, and they are
2895 // counted from one.
Chandler Carruthff4c4f02011-07-01 23:49:12 +00002896 bool HasImplicitThisParam = isInstanceMethod(D);
Alp Toker601b22c2014-01-21 23:35:24 +00002897 unsigned NumArgs = getFunctionOrMethodNumParams(D) + HasImplicitThisParam;
Chris Lattner2c6fcf52008-06-26 18:38:35 +00002898
Aaron Ballman00e99962013-08-31 01:11:41 +00002899 IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident;
2900 StringRef Format = II->getName();
Chris Lattner2c6fcf52008-06-26 18:38:35 +00002901
Aaron Ballman8b5e7ba2015-10-08 19:24:08 +00002902 if (normalizeName(Format)) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00002903 // If we've modified the string name, we need a new identifier for it.
2904 II = &S.Context.Idents.get(Format);
2905 }
Chris Lattner2c6fcf52008-06-26 18:38:35 +00002906
Daniel Dunbarccbd9a42009-10-18 02:09:17 +00002907 // Check for supported formats.
2908 FormatAttrKind Kind = getFormatAttrKind(Format);
Chris Lattner12161d32010-03-22 21:08:50 +00002909
2910 if (Kind == IgnoredFormat)
2911 return;
2912
Daniel Dunbarccbd9a42009-10-18 02:09:17 +00002913 if (Kind == InvalidFormat) {
Chris Lattner3b054132008-11-19 05:08:23 +00002914 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
Aaron Ballman190bad42013-12-26 16:13:50 +00002915 << Attr.getName() << II->getName();
Chris Lattner2c6fcf52008-06-26 18:38:35 +00002916 return;
2917 }
2918
2919 // checks for the 2nd argument
Aaron Ballman00e99962013-08-31 01:11:41 +00002920 Expr *IdxExpr = Attr.getArgAsExpr(1);
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00002921 uint32_t Idx;
2922 if (!checkUInt32Argument(S, Attr, IdxExpr, Idx, 2))
Chris Lattner2c6fcf52008-06-26 18:38:35 +00002923 return;
Chris Lattner2c6fcf52008-06-26 18:38:35 +00002924
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00002925 if (Idx < 1 || Idx > NumArgs) {
Chris Lattner3b054132008-11-19 05:08:23 +00002926 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
Aaron Ballmanfaed0fa2013-12-26 16:30:30 +00002927 << Attr.getName() << 2 << IdxExpr->getSourceRange();
Chris Lattner2c6fcf52008-06-26 18:38:35 +00002928 return;
2929 }
2930
2931 // FIXME: Do we need to bounds check?
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00002932 unsigned ArgIdx = Idx - 1;
Mike Stumpd3bb5572009-07-24 19:02:52 +00002933
Sebastian Redl6eedcc12009-11-17 18:02:24 +00002934 if (HasImplicitThisParam) {
2935 if (ArgIdx == 0) {
Chandler Carruth743682b2010-11-16 08:35:43 +00002936 S.Diag(Attr.getLoc(),
2937 diag::err_format_attribute_implicit_this_format_string)
2938 << IdxExpr->getSourceRange();
Sebastian Redl6eedcc12009-11-17 18:02:24 +00002939 return;
2940 }
2941 ArgIdx--;
2942 }
Mike Stump11289f42009-09-09 15:08:12 +00002943
Chris Lattner2c6fcf52008-06-26 18:38:35 +00002944 // make sure the format string is really a string
Alp Toker601b22c2014-01-21 23:35:24 +00002945 QualType Ty = getFunctionOrMethodParamType(D, ArgIdx);
Chris Lattner2c6fcf52008-06-26 18:38:35 +00002946
Daniel Dunbarccbd9a42009-10-18 02:09:17 +00002947 if (Kind == CFStringFormat) {
Daniel Dunbar980c6692008-09-26 03:32:58 +00002948 if (!isCFStringType(Ty, S.Context)) {
Chris Lattner3b054132008-11-19 05:08:23 +00002949 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
Aaron Ballmandfe8cc52014-08-04 15:26:33 +00002950 << "a CFString" << IdxExpr->getSourceRange()
2951 << getFunctionOrMethodParamRange(D, ArgIdx);
Daniel Dunbar980c6692008-09-26 03:32:58 +00002952 return;
2953 }
Daniel Dunbarccbd9a42009-10-18 02:09:17 +00002954 } else if (Kind == NSStringFormat) {
Mike Stump87c57ac2009-05-16 07:39:55 +00002955 // FIXME: do we need to check if the type is NSString*? What are the
2956 // semantics?
Chris Lattnerb632a6e2008-06-29 00:43:07 +00002957 if (!isNSStringType(Ty, S.Context)) {
Chris Lattner3b054132008-11-19 05:08:23 +00002958 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
Aaron Ballmandfe8cc52014-08-04 15:26:33 +00002959 << "an NSString" << IdxExpr->getSourceRange()
2960 << getFunctionOrMethodParamRange(D, ArgIdx);
Chris Lattner2c6fcf52008-06-26 18:38:35 +00002961 return;
Mike Stumpd3bb5572009-07-24 19:02:52 +00002962 }
Chris Lattner2c6fcf52008-06-26 18:38:35 +00002963 } else if (!Ty->isPointerType() ||
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002964 !Ty->getAs<PointerType>()->getPointeeType()->isCharType()) {
Chris Lattner3b054132008-11-19 05:08:23 +00002965 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
Aaron Ballmandfe8cc52014-08-04 15:26:33 +00002966 << "a string type" << IdxExpr->getSourceRange()
2967 << getFunctionOrMethodParamRange(D, ArgIdx);
Chris Lattner2c6fcf52008-06-26 18:38:35 +00002968 return;
2969 }
2970
2971 // check the 3rd argument
Aaron Ballman00e99962013-08-31 01:11:41 +00002972 Expr *FirstArgExpr = Attr.getArgAsExpr(2);
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00002973 uint32_t FirstArg;
2974 if (!checkUInt32Argument(S, Attr, FirstArgExpr, FirstArg, 3))
Chris Lattner2c6fcf52008-06-26 18:38:35 +00002975 return;
Chris Lattner2c6fcf52008-06-26 18:38:35 +00002976
2977 // check if the function is variadic if the 3rd argument non-zero
2978 if (FirstArg != 0) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00002979 if (isFunctionOrMethodVariadic(D)) {
Chris Lattner2c6fcf52008-06-26 18:38:35 +00002980 ++NumArgs; // +1 for ...
2981 } else {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00002982 S.Diag(D->getLocation(), diag::err_format_attribute_requires_variadic);
Chris Lattner2c6fcf52008-06-26 18:38:35 +00002983 return;
2984 }
2985 }
2986
Chris Lattner4bd8dd82008-11-19 08:23:25 +00002987 // strftime requires FirstArg to be 0 because it doesn't read from any
2988 // variable the input is just the current time + the format string.
Daniel Dunbarccbd9a42009-10-18 02:09:17 +00002989 if (Kind == StrftimeFormat) {
Chris Lattner2c6fcf52008-06-26 18:38:35 +00002990 if (FirstArg != 0) {
Chris Lattner3b054132008-11-19 05:08:23 +00002991 S.Diag(Attr.getLoc(), diag::err_format_strftime_third_parameter)
2992 << FirstArgExpr->getSourceRange();
Chris Lattner2c6fcf52008-06-26 18:38:35 +00002993 return;
2994 }
2995 // if 0 it disables parameter checking (to use with e.g. va_list)
2996 } else if (FirstArg != 0 && FirstArg != NumArgs) {
Chris Lattner3b054132008-11-19 05:08:23 +00002997 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
Aaron Ballmanfaed0fa2013-12-26 16:30:30 +00002998 << Attr.getName() << 3 << FirstArgExpr->getSourceRange();
Chris Lattner2c6fcf52008-06-26 18:38:35 +00002999 return;
3000 }
3001
Aaron Ballmanf58070b2013-09-03 21:02:22 +00003002 FormatAttr *NewAttr = S.mergeFormatAttr(D, Attr.getRange(), II,
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00003003 Idx, FirstArg,
Michael Han99315932013-01-24 16:46:58 +00003004 Attr.getAttributeSpellingListIndex());
Rafael Espindolae200f1c2012-05-13 03:25:18 +00003005 if (NewAttr)
3006 D->addAttr(NewAttr);
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003007}
3008
Chandler Carruthedc2c642011-07-02 00:01:44 +00003009static void handleTransparentUnionAttr(Sema &S, Decl *D,
3010 const AttributeList &Attr) {
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003011 // Try to find the underlying union declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +00003012 RecordDecl *RD = nullptr;
Chandler Carruthff4c4f02011-07-01 23:49:12 +00003013 TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003014 if (TD && TD->getUnderlyingType()->isUnionType())
3015 RD = TD->getUnderlyingType()->getAsUnionType()->getDecl();
3016 else
Chandler Carruthff4c4f02011-07-01 23:49:12 +00003017 RD = dyn_cast<RecordDecl>(D);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003018
3019 if (!RD || !RD->isUnion()) {
Chris Lattner3b054132008-11-19 05:08:23 +00003020 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
John McCall5fca7ea2011-03-02 12:29:23 +00003021 << Attr.getName() << ExpectedUnion;
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003022 return;
3023 }
3024
John McCallf937c022011-10-07 06:10:15 +00003025 if (!RD->isCompleteDefinition()) {
Mike Stumpd3bb5572009-07-24 19:02:52 +00003026 S.Diag(Attr.getLoc(),
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003027 diag::warn_transparent_union_attribute_not_definition);
3028 return;
3029 }
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003030
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003031 RecordDecl::field_iterator Field = RD->field_begin(),
3032 FieldEnd = RD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003033 if (Field == FieldEnd) {
3034 S.Diag(Attr.getLoc(), diag::warn_transparent_union_attribute_zero_fields);
3035 return;
3036 }
Eli Friedman7c9ba6a2008-09-02 05:19:23 +00003037
David Blaikie40ed2972012-06-06 20:45:41 +00003038 FieldDecl *FirstField = *Field;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003039 QualType FirstType = FirstField->getType();
Douglas Gregor21872662010-06-30 17:24:13 +00003040 if (FirstType->hasFloatingRepresentation() || FirstType->isVectorType()) {
Mike Stumpd3bb5572009-07-24 19:02:52 +00003041 S.Diag(FirstField->getLocation(),
Douglas Gregor21872662010-06-30 17:24:13 +00003042 diag::warn_transparent_union_attribute_floating)
3043 << FirstType->isVectorType() << FirstType;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003044 return;
3045 }
3046
3047 uint64_t FirstSize = S.Context.getTypeSize(FirstType);
3048 uint64_t FirstAlign = S.Context.getTypeAlign(FirstType);
3049 for (; Field != FieldEnd; ++Field) {
3050 QualType FieldType = Field->getType();
Aaron Ballman54fe5eb2014-01-28 01:47:34 +00003051 // FIXME: this isn't fully correct; we also need to test whether the
3052 // members of the union would all have the same calling convention as the
3053 // first member of the union. Checking just the size and alignment isn't
3054 // sufficient (consider structs passed on the stack instead of in registers
3055 // as an example).
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003056 if (S.Context.getTypeSize(FieldType) != FirstSize ||
Aaron Ballman54fe5eb2014-01-28 01:47:34 +00003057 S.Context.getTypeAlign(FieldType) > FirstAlign) {
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003058 // Warn if we drop the attribute.
3059 bool isSize = S.Context.getTypeSize(FieldType) != FirstSize;
Mike Stumpd3bb5572009-07-24 19:02:52 +00003060 unsigned FieldBits = isSize? S.Context.getTypeSize(FieldType)
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003061 : S.Context.getTypeAlign(FieldType);
Mike Stumpd3bb5572009-07-24 19:02:52 +00003062 S.Diag(Field->getLocation(),
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003063 diag::warn_transparent_union_attribute_field_size_align)
3064 << isSize << Field->getDeclName() << FieldBits;
3065 unsigned FirstBits = isSize? FirstSize : FirstAlign;
Mike Stumpd3bb5572009-07-24 19:02:52 +00003066 S.Diag(FirstField->getLocation(),
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003067 diag::note_transparent_union_first_field_size_align)
3068 << isSize << FirstBits;
Eli Friedman7c9ba6a2008-09-02 05:19:23 +00003069 return;
3070 }
3071 }
3072
Michael Han99315932013-01-24 16:46:58 +00003073 RD->addAttr(::new (S.Context)
3074 TransparentUnionAttr(Attr.getRange(), S.Context,
3075 Attr.getAttributeSpellingListIndex()));
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003076}
3077
Chandler Carruthedc2c642011-07-02 00:01:44 +00003078static void handleAnnotateAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003079 // Make sure that there is a string literal as the annotation's single
3080 // argument.
Benjamin Kramer6ee15622013-09-13 15:35:43 +00003081 StringRef Str;
Tim Northover6a6b63b2013-10-01 14:34:18 +00003082 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str))
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003083 return;
Julien Lerouge5a6b6982011-09-09 22:41:49 +00003084
3085 // Don't duplicate annotations that are already set.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003086 for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
3087 if (I->getAnnotation() == Str)
Benjamin Kramer6ee15622013-09-13 15:35:43 +00003088 return;
Julien Lerouge5a6b6982011-09-09 22:41:49 +00003089 }
Michael Han99315932013-01-24 16:46:58 +00003090
3091 D->addAttr(::new (S.Context)
Benjamin Kramer6ee15622013-09-13 15:35:43 +00003092 AnnotateAttr(Attr.getRange(), S.Context, Str,
Michael Han99315932013-01-24 16:46:58 +00003093 Attr.getAttributeSpellingListIndex()));
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003094}
3095
Hal Finkel1b0d24e2014-10-02 21:21:25 +00003096static void handleAlignValueAttr(Sema &S, Decl *D,
3097 const AttributeList &Attr) {
3098 S.AddAlignValueAttr(Attr.getRange(), D, Attr.getArgAsExpr(0),
3099 Attr.getAttributeSpellingListIndex());
3100}
3101
3102void Sema::AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E,
3103 unsigned SpellingListIndex) {
3104 AlignValueAttr TmpAttr(AttrRange, Context, E, SpellingListIndex);
3105 SourceLocation AttrLoc = AttrRange.getBegin();
3106
3107 QualType T;
3108 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
3109 T = TD->getUnderlyingType();
3110 else if (ValueDecl *VD = dyn_cast<ValueDecl>(D))
3111 T = VD->getType();
3112 else
3113 llvm_unreachable("Unknown decl type for align_value");
3114
3115 if (!T->isDependentType() && !T->isAnyPointerType() &&
3116 !T->isReferenceType() && !T->isMemberPointerType()) {
3117 Diag(AttrLoc, diag::warn_attribute_pointer_or_reference_only)
3118 << &TmpAttr /*TmpAttr.getName()*/ << T << D->getSourceRange();
3119 return;
3120 }
3121
3122 if (!E->isValueDependent()) {
David Majnemer0be6bd02015-07-26 09:02:21 +00003123 llvm::APSInt Alignment;
Hal Finkel1b0d24e2014-10-02 21:21:25 +00003124 ExprResult ICE
3125 = VerifyIntegerConstantExpression(E, &Alignment,
3126 diag::err_align_value_attribute_argument_not_int,
3127 /*AllowFold*/ false);
3128 if (ICE.isInvalid())
3129 return;
3130
3131 if (!Alignment.isPowerOf2()) {
3132 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
3133 << E->getSourceRange();
3134 return;
3135 }
3136
3137 D->addAttr(::new (Context)
3138 AlignValueAttr(AttrRange, Context, ICE.get(),
3139 SpellingListIndex));
3140 return;
3141 }
3142
3143 // Save dependent expressions in the AST to be instantiated.
3144 D->addAttr(::new (Context) AlignValueAttr(TmpAttr));
Hal Finkel1b0d24e2014-10-02 21:21:25 +00003145}
3146
Chandler Carruthedc2c642011-07-02 00:01:44 +00003147static void handleAlignedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003148 // check the attribute arguments.
Chris Lattner4a927cb2008-06-28 23:36:30 +00003149 if (Attr.getNumArgs() > 1) {
Aaron Ballmanb7243382013-07-23 19:30:11 +00003150 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
3151 << Attr.getName() << 1;
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003152 return;
3153 }
Aaron Ballman478faed2012-06-19 22:09:27 +00003154
Richard Smith848e1f12013-02-01 08:12:08 +00003155 if (Attr.getNumArgs() == 0) {
3156 D->addAttr(::new (S.Context) AlignedAttr(Attr.getRange(), S.Context,
Craig Topperc3ec1492014-05-26 06:22:03 +00003157 true, nullptr, Attr.getAttributeSpellingListIndex()));
Richard Smith848e1f12013-02-01 08:12:08 +00003158 return;
3159 }
3160
Aaron Ballman00e99962013-08-31 01:11:41 +00003161 Expr *E = Attr.getArgAsExpr(0);
Richard Smith44c247f2013-02-22 08:32:16 +00003162 if (Attr.isPackExpansion() && !E->containsUnexpandedParameterPack()) {
3163 S.Diag(Attr.getEllipsisLoc(),
3164 diag::err_pack_expansion_without_parameter_packs);
3165 return;
3166 }
3167
3168 if (!Attr.isPackExpansion() && S.DiagnoseUnexpandedParameterPack(E))
3169 return;
3170
David Majnemer26a1e0e2015-04-07 02:37:09 +00003171 if (E->isValueDependent()) {
3172 if (const auto *TND = dyn_cast<TypedefNameDecl>(D)) {
3173 if (!TND->getUnderlyingType()->isDependentType()) {
3174 S.Diag(Attr.getLoc(), diag::err_alignment_dependent_typedef_name)
3175 << E->getSourceRange();
3176 return;
3177 }
3178 }
3179 }
3180
Richard Smith44c247f2013-02-22 08:32:16 +00003181 S.AddAlignedAttr(Attr.getRange(), D, E, Attr.getAttributeSpellingListIndex(),
3182 Attr.isPackExpansion());
Richard Smith848e1f12013-02-01 08:12:08 +00003183}
3184
3185void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
Richard Smith44c247f2013-02-22 08:32:16 +00003186 unsigned SpellingListIndex, bool IsPackExpansion) {
Richard Smith848e1f12013-02-01 08:12:08 +00003187 AlignedAttr TmpAttr(AttrRange, Context, true, E, SpellingListIndex);
3188 SourceLocation AttrLoc = AttrRange.getBegin();
3189
Richard Smith1dba27c2013-01-29 09:02:09 +00003190 // C++11 alignas(...) and C11 _Alignas(...) have additional requirements.
Richard Smith848e1f12013-02-01 08:12:08 +00003191 if (TmpAttr.isAlignas()) {
Richard Smith1dba27c2013-01-29 09:02:09 +00003192 // C++11 [dcl.align]p1:
3193 // An alignment-specifier may be applied to a variable or to a class
3194 // data member, but it shall not be applied to a bit-field, a function
3195 // parameter, the formal parameter of a catch clause, or a variable
3196 // declared with the register storage class specifier. An
3197 // alignment-specifier may also be applied to the declaration of a class
3198 // or enumeration type.
3199 // C11 6.7.5/2:
3200 // An alignment attribute shall not be specified in a declaration of
3201 // a typedef, or a bit-field, or a function, or a parameter, or an
3202 // object declared with the register storage-class specifier.
3203 int DiagKind = -1;
3204 if (isa<ParmVarDecl>(D)) {
3205 DiagKind = 0;
3206 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3207 if (VD->getStorageClass() == SC_Register)
3208 DiagKind = 1;
3209 if (VD->isExceptionVariable())
3210 DiagKind = 2;
3211 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
3212 if (FD->isBitField())
3213 DiagKind = 3;
3214 } else if (!isa<TagDecl>(D)) {
Aaron Ballman3d216a52014-01-02 23:39:11 +00003215 Diag(AttrLoc, diag::err_attribute_wrong_decl_type) << &TmpAttr
Richard Smith9eaab4b2013-02-01 08:25:07 +00003216 << (TmpAttr.isC11() ? ExpectedVariableOrField
3217 : ExpectedVariableFieldOrTag);
Richard Smith1dba27c2013-01-29 09:02:09 +00003218 return;
3219 }
3220 if (DiagKind != -1) {
Richard Smith848e1f12013-02-01 08:12:08 +00003221 Diag(AttrLoc, diag::err_alignas_attribute_wrong_decl_type)
Aaron Ballman3d216a52014-01-02 23:39:11 +00003222 << &TmpAttr << DiagKind;
Richard Smith1dba27c2013-01-29 09:02:09 +00003223 return;
3224 }
3225 }
3226
Chandler Carruthf40c42f2010-06-25 03:22:07 +00003227 if (E->isTypeDependent() || E->isValueDependent()) {
3228 // Save dependent expressions in the AST to be instantiated.
Richard Smith44c247f2013-02-22 08:32:16 +00003229 AlignedAttr *AA = ::new (Context) AlignedAttr(TmpAttr);
3230 AA->setPackExpansion(IsPackExpansion);
3231 D->addAttr(AA);
Chandler Carruthf40c42f2010-06-25 03:22:07 +00003232 return;
3233 }
Michael Hanaf02bbe2013-02-01 01:19:17 +00003234
Alexis Huntdcfba7b2010-08-18 23:23:40 +00003235 // FIXME: Cache the number on the Attr object?
David Majnemer0be6bd02015-07-26 09:02:21 +00003236 llvm::APSInt Alignment;
Douglas Gregore2b37442012-05-04 22:38:52 +00003237 ExprResult ICE
3238 = VerifyIntegerConstantExpression(E, &Alignment,
3239 diag::err_aligned_attribute_argument_not_int,
3240 /*AllowFold*/ false);
Richard Smithf4c51d92012-02-04 09:53:13 +00003241 if (ICE.isInvalid())
Chris Lattner4627b742008-06-28 23:50:44 +00003242 return;
Richard Smith848e1f12013-02-01 08:12:08 +00003243
David Majnemer0be6bd02015-07-26 09:02:21 +00003244 uint64_t AlignVal = Alignment.getZExtValue();
3245
Richard Smith848e1f12013-02-01 08:12:08 +00003246 // C++11 [dcl.align]p2:
3247 // -- if the constant expression evaluates to zero, the alignment
3248 // specifier shall have no effect
3249 // C11 6.7.5p6:
3250 // An alignment specification of zero has no effect.
Paul Robinsond30e2ee2015-07-14 20:52:32 +00003251 if (!(TmpAttr.isAlignas() && !Alignment)) {
David Majnemer0be6bd02015-07-26 09:02:21 +00003252 if (!llvm::isPowerOf2_64(AlignVal)) {
Paul Robinsond30e2ee2015-07-14 20:52:32 +00003253 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
3254 << E->getSourceRange();
3255 return;
3256 }
Daniel Dunbar6e8c07d2009-02-16 23:37:57 +00003257 }
Michael Hanaf02bbe2013-02-01 01:19:17 +00003258
David Majnemerabecae72014-02-12 20:36:10 +00003259 // Alignment calculations can wrap around if it's greater than 2**28.
David Majnemer29c69db2015-07-26 01:48:59 +00003260 unsigned MaxValidAlignment =
3261 Context.getTargetInfo().getTriple().isOSBinFormatCOFF() ? 8192
3262 : 268435456;
David Majnemer0be6bd02015-07-26 09:02:21 +00003263 if (AlignVal > MaxValidAlignment) {
David Majnemerabecae72014-02-12 20:36:10 +00003264 Diag(AttrLoc, diag::err_attribute_aligned_too_great) << MaxValidAlignment
3265 << E->getSourceRange();
3266 return;
Aaron Ballman478faed2012-06-19 22:09:27 +00003267 }
Daniel Dunbar6e8c07d2009-02-16 23:37:57 +00003268
David Majnemer0be6bd02015-07-26 09:02:21 +00003269 if (Context.getTargetInfo().isTLSSupported()) {
3270 unsigned MaxTLSAlign =
3271 Context.toCharUnitsFromBits(Context.getTargetInfo().getMaxTLSAlign())
3272 .getQuantity();
3273 auto *VD = dyn_cast<VarDecl>(D);
3274 if (MaxTLSAlign && AlignVal > MaxTLSAlign && VD &&
3275 VD->getTLSKind() != VarDecl::TLS_None) {
3276 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
3277 << (unsigned)AlignVal << VD << MaxTLSAlign;
3278 return;
3279 }
3280 }
3281
Richard Smith44c247f2013-02-22 08:32:16 +00003282 AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, true,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003283 ICE.get(), SpellingListIndex);
Richard Smith44c247f2013-02-22 08:32:16 +00003284 AA->setPackExpansion(IsPackExpansion);
3285 D->addAttr(AA);
Alexis Huntdcfba7b2010-08-18 23:23:40 +00003286}
3287
Michael Hanaf02bbe2013-02-01 01:19:17 +00003288void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *TS,
Richard Smith44c247f2013-02-22 08:32:16 +00003289 unsigned SpellingListIndex, bool IsPackExpansion) {
Alexis Huntdcfba7b2010-08-18 23:23:40 +00003290 // FIXME: Cache the number on the Attr object if non-dependent?
3291 // FIXME: Perform checking of type validity
Richard Smith44c247f2013-02-22 08:32:16 +00003292 AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, false, TS,
3293 SpellingListIndex);
3294 AA->setPackExpansion(IsPackExpansion);
3295 D->addAttr(AA);
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003296}
Chris Lattneracbc2d22008-06-27 22:18:37 +00003297
Richard Smith848e1f12013-02-01 08:12:08 +00003298void Sema::CheckAlignasUnderalignment(Decl *D) {
3299 assert(D->hasAttrs() && "no attributes on decl");
3300
David Majnemer475b25e2015-01-21 10:54:38 +00003301 QualType UnderlyingTy, DiagTy;
3302 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
3303 UnderlyingTy = DiagTy = VD->getType();
3304 } else {
3305 UnderlyingTy = DiagTy = Context.getTagDeclType(cast<TagDecl>(D));
3306 if (EnumDecl *ED = dyn_cast<EnumDecl>(D))
3307 UnderlyingTy = ED->getIntegerType();
3308 }
3309 if (DiagTy->isDependentType() || DiagTy->isIncompleteType())
Richard Smith848e1f12013-02-01 08:12:08 +00003310 return;
3311
3312 // C++11 [dcl.align]p5, C11 6.7.5/4:
3313 // The combined effect of all alignment attributes in a declaration shall
3314 // not specify an alignment that is less strict than the alignment that
3315 // would otherwise be required for the entity being declared.
Craig Topperc3ec1492014-05-26 06:22:03 +00003316 AlignedAttr *AlignasAttr = nullptr;
Richard Smith848e1f12013-02-01 08:12:08 +00003317 unsigned Align = 0;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003318 for (auto *I : D->specific_attrs<AlignedAttr>()) {
Richard Smith848e1f12013-02-01 08:12:08 +00003319 if (I->isAlignmentDependent())
3320 return;
3321 if (I->isAlignas())
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003322 AlignasAttr = I;
Richard Smith848e1f12013-02-01 08:12:08 +00003323 Align = std::max(Align, I->getAlignment(Context));
3324 }
3325
3326 if (AlignasAttr && Align) {
3327 CharUnits RequestedAlign = Context.toCharUnitsFromBits(Align);
David Majnemer475b25e2015-01-21 10:54:38 +00003328 CharUnits NaturalAlign = Context.getTypeAlignInChars(UnderlyingTy);
Richard Smith848e1f12013-02-01 08:12:08 +00003329 if (NaturalAlign > RequestedAlign)
3330 Diag(AlignasAttr->getLocation(), diag::err_alignas_underaligned)
David Majnemer475b25e2015-01-21 10:54:38 +00003331 << DiagTy << (unsigned)NaturalAlign.getQuantity();
Richard Smith848e1f12013-02-01 08:12:08 +00003332 }
3333}
3334
David Majnemer2c4e00a2014-01-29 22:07:36 +00003335bool Sema::checkMSInheritanceAttrOnDefinition(
David Majnemer4bb09802014-02-10 19:50:15 +00003336 CXXRecordDecl *RD, SourceRange Range, bool BestCase,
David Majnemer2c4e00a2014-01-29 22:07:36 +00003337 MSInheritanceAttr::Spelling SemanticSpelling) {
3338 assert(RD->hasDefinition() && "RD has no definition!");
3339
David Majnemer98c9ee22014-02-07 00:43:07 +00003340 // We may not have seen base specifiers or any virtual methods yet. We will
3341 // have to wait until the record is defined to catch any mismatches.
3342 if (!RD->getDefinition()->isCompleteDefinition())
3343 return false;
David Majnemer2c4e00a2014-01-29 22:07:36 +00003344
David Majnemer98c9ee22014-02-07 00:43:07 +00003345 // The unspecified model never matches what a definition could need.
3346 if (SemanticSpelling == MSInheritanceAttr::Keyword_unspecified_inheritance)
3347 return false;
3348
David Majnemer4bb09802014-02-10 19:50:15 +00003349 if (BestCase) {
3350 if (RD->calculateInheritanceModel() == SemanticSpelling)
3351 return false;
3352 } else {
3353 if (RD->calculateInheritanceModel() <= SemanticSpelling)
3354 return false;
3355 }
David Majnemer98c9ee22014-02-07 00:43:07 +00003356
3357 Diag(Range.getBegin(), diag::err_mismatched_ms_inheritance)
3358 << 0 /*definition*/;
3359 Diag(RD->getDefinition()->getLocation(), diag::note_defined_here)
3360 << RD->getNameAsString();
3361 return true;
David Majnemer2c4e00a2014-01-29 22:07:36 +00003362}
3363
Alexey Bataevf278eb12015-11-19 10:13:11 +00003364/// parseModeAttrArg - Parses attribute mode string and returns parsed type
3365/// attribute.
3366static void parseModeAttrArg(Sema &S, StringRef Str, unsigned &DestWidth,
3367 bool &IntegerMode, bool &ComplexMode) {
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003368 IntegerMode = true;
3369 ComplexMode = false;
Daniel Dunbarafff4342009-10-18 02:09:24 +00003370 switch (Str.size()) {
Chris Lattneracbc2d22008-06-27 22:18:37 +00003371 case 2:
Eli Friedman4735374e2009-03-03 06:41:03 +00003372 switch (Str[0]) {
Alexey Bataevf278eb12015-11-19 10:13:11 +00003373 case 'Q':
3374 DestWidth = 8;
3375 break;
3376 case 'H':
3377 DestWidth = 16;
3378 break;
3379 case 'S':
3380 DestWidth = 32;
3381 break;
3382 case 'D':
3383 DestWidth = 64;
3384 break;
3385 case 'X':
3386 DestWidth = 96;
3387 break;
3388 case 'T':
3389 DestWidth = 128;
3390 break;
Eli Friedman4735374e2009-03-03 06:41:03 +00003391 }
3392 if (Str[1] == 'F') {
3393 IntegerMode = false;
3394 } else if (Str[1] == 'C') {
3395 IntegerMode = false;
3396 ComplexMode = true;
3397 } else if (Str[1] != 'I') {
3398 DestWidth = 0;
3399 }
Chris Lattneracbc2d22008-06-27 22:18:37 +00003400 break;
3401 case 4:
3402 // FIXME: glibc uses 'word' to define register_t; this is narrower than a
3403 // pointer on PIC16 and other embedded platforms.
Daniel Dunbarafff4342009-10-18 02:09:24 +00003404 if (Str == "word")
Reid Klecknerf27e7522016-02-01 18:58:24 +00003405 DestWidth = S.Context.getTargetInfo().getRegisterWidth();
Daniel Dunbarafff4342009-10-18 02:09:24 +00003406 else if (Str == "byte")
Douglas Gregore8bbc122011-09-02 00:18:52 +00003407 DestWidth = S.Context.getTargetInfo().getCharWidth();
Chris Lattneracbc2d22008-06-27 22:18:37 +00003408 break;
3409 case 7:
Daniel Dunbarafff4342009-10-18 02:09:24 +00003410 if (Str == "pointer")
Douglas Gregore8bbc122011-09-02 00:18:52 +00003411 DestWidth = S.Context.getTargetInfo().getPointerWidth(0);
Chris Lattneracbc2d22008-06-27 22:18:37 +00003412 break;
Rafael Espindolaf0dafd32013-01-07 19:58:54 +00003413 case 11:
3414 if (Str == "unwind_word")
Rafael Espindola03705972013-01-07 20:01:57 +00003415 DestWidth = S.Context.getTargetInfo().getUnwindWordWidth();
Rafael Espindolaf0dafd32013-01-07 19:58:54 +00003416 break;
Chris Lattneracbc2d22008-06-27 22:18:37 +00003417 }
Alexey Bataevf278eb12015-11-19 10:13:11 +00003418}
3419
3420/// handleModeAttr - This attribute modifies the width of a decl with primitive
3421/// type.
3422///
3423/// Despite what would be logical, the mode attribute is a decl attribute, not a
3424/// type attribute: 'int ** __attribute((mode(HI))) *G;' tries to make 'G' be
3425/// HImode, not an intermediate pointer.
3426static void handleModeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3427 // This attribute isn't documented, but glibc uses it. It changes
3428 // the width of an int or unsigned int to the specified size.
3429 if (!Attr.isArgIdent(0)) {
3430 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << Attr.getName()
3431 << AANT_ArgumentIdentifier;
3432 return;
3433 }
3434
3435 IdentifierInfo *Name = Attr.getArgAsIdent(0)->Ident;
Alexey Bataevf278eb12015-11-19 10:13:11 +00003436
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003437 S.AddModeAttr(Attr.getRange(), D, Name, Attr.getAttributeSpellingListIndex());
3438}
3439
3440void Sema::AddModeAttr(SourceRange AttrRange, Decl *D, IdentifierInfo *Name,
3441 unsigned SpellingListIndex, bool InInstantiation) {
3442 StringRef Str = Name->getName();
Alexey Bataevf278eb12015-11-19 10:13:11 +00003443 normalizeName(Str);
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003444 SourceLocation AttrLoc = AttrRange.getBegin();
Alexey Bataevf278eb12015-11-19 10:13:11 +00003445
3446 unsigned DestWidth = 0;
3447 bool IntegerMode = true;
3448 bool ComplexMode = false;
3449 llvm::APInt VectorSize(64, 0);
3450 if (Str.size() >= 4 && Str[0] == 'V') {
3451 // Minimal length of vector mode is 4: 'V' + NUMBER(>=1) + TYPE(>=2).
3452 size_t StrSize = Str.size();
3453 size_t VectorStringLength = 0;
3454 while ((VectorStringLength + 1) < StrSize &&
3455 isdigit(Str[VectorStringLength + 1]))
3456 ++VectorStringLength;
3457 if (VectorStringLength &&
3458 !Str.substr(1, VectorStringLength).getAsInteger(10, VectorSize) &&
3459 VectorSize.isPowerOf2()) {
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003460 parseModeAttrArg(*this, Str.substr(VectorStringLength + 1), DestWidth,
Alexey Bataevf278eb12015-11-19 10:13:11 +00003461 IntegerMode, ComplexMode);
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003462 // Avoid duplicate warning from template instantiation.
3463 if (!InInstantiation)
3464 Diag(AttrLoc, diag::warn_vector_mode_deprecated);
Alexey Bataevf278eb12015-11-19 10:13:11 +00003465 } else {
3466 VectorSize = 0;
3467 }
3468 }
3469
3470 if (!VectorSize)
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003471 parseModeAttrArg(*this, Str, DestWidth, IntegerMode, ComplexMode);
3472
3473 // FIXME: Sync this with InitializePredefinedMacros; we need to match int8_t
3474 // and friends, at least with glibc.
3475 // FIXME: Make sure floating-point mappings are accurate
3476 // FIXME: Support XF and TF types
3477 if (!DestWidth) {
3478 Diag(AttrLoc, diag::err_machine_mode) << 0 /*Unknown*/ << Name;
3479 return;
3480 }
Chris Lattneracbc2d22008-06-27 22:18:37 +00003481
3482 QualType OldTy;
Richard Smithdda56e42011-04-15 14:24:37 +00003483 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
Chris Lattneracbc2d22008-06-27 22:18:37 +00003484 OldTy = TD->getUnderlyingType();
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003485 else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
3486 // Something like 'typedef enum { X } __attribute__((mode(XX))) T;'.
3487 // Try to get type from enum declaration, default to int.
3488 OldTy = ED->getIntegerType();
3489 if (OldTy.isNull())
3490 OldTy = Context.IntTy;
3491 } else
Aaron Ballman6c8848a2016-01-19 22:54:26 +00003492 OldTy = cast<ValueDecl>(D)->getType();
Eli Friedman4735374e2009-03-03 06:41:03 +00003493
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003494 if (OldTy->isDependentType()) {
3495 D->addAttr(::new (Context)
3496 ModeAttr(AttrRange, Context, Name, SpellingListIndex));
3497 return;
3498 }
3499
Alexey Bataev326057d2015-06-19 07:46:21 +00003500 // Base type can also be a vector type (see PR17453).
3501 // Distinguish between base type and base element type.
3502 QualType OldElemTy = OldTy;
3503 if (const VectorType *VT = OldTy->getAs<VectorType>())
3504 OldElemTy = VT->getElementType();
3505
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003506 // GCC allows 'mode' attribute on enumeration types (even incomplete), except
3507 // for vector modes. So, 'enum X __attribute__((mode(QI)));' forms a complete
3508 // type, 'enum { A } __attribute__((mode(V4SI)))' is rejected.
3509 if ((isa<EnumDecl>(D) || OldElemTy->getAs<EnumType>()) &&
3510 VectorSize.getBoolValue()) {
3511 Diag(AttrLoc, diag::err_enum_mode_vector_type) << Name << AttrRange;
3512 return;
3513 }
3514 bool IntegralOrAnyEnumType =
3515 OldElemTy->isIntegralOrEnumerationType() || OldElemTy->getAs<EnumType>();
3516
3517 if (!OldElemTy->getAs<BuiltinType>() && !OldElemTy->isComplexType() &&
3518 !IntegralOrAnyEnumType)
3519 Diag(AttrLoc, diag::err_mode_not_primitive);
Eli Friedman4735374e2009-03-03 06:41:03 +00003520 else if (IntegerMode) {
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003521 if (!IntegralOrAnyEnumType)
3522 Diag(AttrLoc, diag::err_mode_wrong_type);
Eli Friedman4735374e2009-03-03 06:41:03 +00003523 } else if (ComplexMode) {
Alexey Bataev326057d2015-06-19 07:46:21 +00003524 if (!OldElemTy->isComplexType())
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003525 Diag(AttrLoc, diag::err_mode_wrong_type);
Eli Friedman4735374e2009-03-03 06:41:03 +00003526 } else {
Alexey Bataev326057d2015-06-19 07:46:21 +00003527 if (!OldElemTy->isFloatingType())
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003528 Diag(AttrLoc, diag::err_mode_wrong_type);
Stepan Dyatkovskiyb88c30f2013-09-18 09:08:52 +00003529 }
3530
Alexey Bataev326057d2015-06-19 07:46:21 +00003531 QualType NewElemTy;
Stepan Dyatkovskiyb88c30f2013-09-18 09:08:52 +00003532
3533 if (IntegerMode)
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003534 NewElemTy = Context.getIntTypeForBitwidth(DestWidth,
3535 OldElemTy->isSignedIntegerType());
Stepan Dyatkovskiyb88c30f2013-09-18 09:08:52 +00003536 else
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003537 NewElemTy = Context.getRealTypeForBitwidth(DestWidth);
Stepan Dyatkovskiyb88c30f2013-09-18 09:08:52 +00003538
Alexey Bataev326057d2015-06-19 07:46:21 +00003539 if (NewElemTy.isNull()) {
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003540 Diag(AttrLoc, diag::err_machine_mode) << 1 /*Unsupported*/ << Name;
Chris Lattneracbc2d22008-06-27 22:18:37 +00003541 return;
Chris Lattneracbc2d22008-06-27 22:18:37 +00003542 }
3543
Eli Friedman4735374e2009-03-03 06:41:03 +00003544 if (ComplexMode) {
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003545 NewElemTy = Context.getComplexType(NewElemTy);
Alexey Bataev326057d2015-06-19 07:46:21 +00003546 }
3547
3548 QualType NewTy = NewElemTy;
Alexey Bataevf278eb12015-11-19 10:13:11 +00003549 if (VectorSize.getBoolValue()) {
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003550 NewTy = Context.getVectorType(NewTy, VectorSize.getZExtValue(),
3551 VectorType::GenericVector);
Alexey Bataevf278eb12015-11-19 10:13:11 +00003552 } else if (const VectorType *OldVT = OldTy->getAs<VectorType>()) {
Alexey Bataev326057d2015-06-19 07:46:21 +00003553 // Complex machine mode does not support base vector types.
3554 if (ComplexMode) {
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003555 Diag(AttrLoc, diag::err_complex_mode_vector_type);
Alexey Bataev326057d2015-06-19 07:46:21 +00003556 return;
3557 }
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003558 unsigned NumElements = Context.getTypeSize(OldElemTy) *
Alexey Bataev326057d2015-06-19 07:46:21 +00003559 OldVT->getNumElements() /
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003560 Context.getTypeSize(NewElemTy);
Alexey Bataev326057d2015-06-19 07:46:21 +00003561 NewTy =
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003562 Context.getVectorType(NewElemTy, NumElements, OldVT->getVectorKind());
Alexey Bataev326057d2015-06-19 07:46:21 +00003563 }
3564
3565 if (NewTy.isNull()) {
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003566 Diag(AttrLoc, diag::err_mode_wrong_type);
Alexey Bataev326057d2015-06-19 07:46:21 +00003567 return;
Chris Lattneracbc2d22008-06-27 22:18:37 +00003568 }
3569
3570 // Install the new type.
Enea Zaffanellaa86d88c2013-06-20 12:46:19 +00003571 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
3572 TD->setModedTypeSourceInfo(TD->getTypeSourceInfo(), NewTy);
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003573 else if (EnumDecl *ED = dyn_cast<EnumDecl>(D))
3574 ED->setIntegerType(NewTy);
Enea Zaffanellaa86d88c2013-06-20 12:46:19 +00003575 else
Aaron Ballman6c8848a2016-01-19 22:54:26 +00003576 cast<ValueDecl>(D)->setType(NewTy);
Enea Zaffanellaa86d88c2013-06-20 12:46:19 +00003577
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003578 D->addAttr(::new (Context)
3579 ModeAttr(AttrRange, Context, Name, SpellingListIndex));
Chris Lattneracbc2d22008-06-27 22:18:37 +00003580}
Chris Lattner9e2aafe2008-06-29 00:23:49 +00003581
Chandler Carruthedc2c642011-07-02 00:01:44 +00003582static void handleNoDebugAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Michael Han99315932013-01-24 16:46:58 +00003583 D->addAttr(::new (S.Context)
3584 NoDebugAttr(Attr.getRange(), S.Context,
3585 Attr.getAttributeSpellingListIndex()));
Anders Carlsson76187b42009-02-13 06:46:13 +00003586}
3587
Paul Robinson30e41fb2014-12-15 18:57:28 +00003588AlwaysInlineAttr *Sema::mergeAlwaysInlineAttr(Decl *D, SourceRange Range,
Paul Robinson080b1f32015-01-13 18:34:56 +00003589 IdentifierInfo *Ident,
Paul Robinson30e41fb2014-12-15 18:57:28 +00003590 unsigned AttrSpellingListIndex) {
3591 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
Paul Robinson080b1f32015-01-13 18:34:56 +00003592 Diag(Range.getBegin(), diag::warn_attribute_ignored) << Ident;
Paul Robinson30e41fb2014-12-15 18:57:28 +00003593 Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
3594 return nullptr;
3595 }
3596
3597 if (D->hasAttr<AlwaysInlineAttr>())
3598 return nullptr;
3599
3600 return ::new (Context) AlwaysInlineAttr(Range, Context,
3601 AttrSpellingListIndex);
3602}
3603
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00003604CommonAttr *Sema::mergeCommonAttr(Decl *D, SourceRange Range,
3605 IdentifierInfo *Ident,
3606 unsigned AttrSpellingListIndex) {
3607 if (checkAttrMutualExclusion<InternalLinkageAttr>(*this, D, Range, Ident))
3608 return nullptr;
3609
3610 return ::new (Context) CommonAttr(Range, Context, AttrSpellingListIndex);
3611}
3612
3613InternalLinkageAttr *
3614Sema::mergeInternalLinkageAttr(Decl *D, SourceRange Range,
3615 IdentifierInfo *Ident,
3616 unsigned AttrSpellingListIndex) {
3617 if (auto VD = dyn_cast<VarDecl>(D)) {
3618 // Attribute applies to Var but not any subclass of it (like ParmVar,
3619 // ImplicitParm or VarTemplateSpecialization).
3620 if (VD->getKind() != Decl::Var) {
3621 Diag(Range.getBegin(), diag::warn_attribute_wrong_decl_type)
3622 << Ident << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass
3623 : ExpectedVariableOrFunction);
3624 return nullptr;
3625 }
3626 // Attribute does not apply to non-static local variables.
3627 if (VD->hasLocalStorage()) {
3628 Diag(VD->getLocation(), diag::warn_internal_linkage_local_storage);
3629 return nullptr;
3630 }
3631 }
3632
3633 if (checkAttrMutualExclusion<CommonAttr>(*this, D, Range, Ident))
3634 return nullptr;
3635
3636 return ::new (Context)
3637 InternalLinkageAttr(Range, Context, AttrSpellingListIndex);
3638}
3639
Paul Robinson30e41fb2014-12-15 18:57:28 +00003640MinSizeAttr *Sema::mergeMinSizeAttr(Decl *D, SourceRange Range,
3641 unsigned AttrSpellingListIndex) {
3642 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
3643 Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'minsize'";
3644 Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
3645 return nullptr;
3646 }
3647
3648 if (D->hasAttr<MinSizeAttr>())
3649 return nullptr;
3650
3651 return ::new (Context) MinSizeAttr(Range, Context, AttrSpellingListIndex);
3652}
3653
3654OptimizeNoneAttr *Sema::mergeOptimizeNoneAttr(Decl *D, SourceRange Range,
3655 unsigned AttrSpellingListIndex) {
3656 if (AlwaysInlineAttr *Inline = D->getAttr<AlwaysInlineAttr>()) {
3657 Diag(Inline->getLocation(), diag::warn_attribute_ignored) << Inline;
3658 Diag(Range.getBegin(), diag::note_conflicting_attribute);
3659 D->dropAttr<AlwaysInlineAttr>();
3660 }
3661 if (MinSizeAttr *MinSize = D->getAttr<MinSizeAttr>()) {
3662 Diag(MinSize->getLocation(), diag::warn_attribute_ignored) << MinSize;
3663 Diag(Range.getBegin(), diag::note_conflicting_attribute);
3664 D->dropAttr<MinSizeAttr>();
3665 }
3666
3667 if (D->hasAttr<OptimizeNoneAttr>())
3668 return nullptr;
3669
3670 return ::new (Context) OptimizeNoneAttr(Range, Context,
3671 AttrSpellingListIndex);
3672}
3673
Paul Robinsonf0674352014-03-31 22:29:15 +00003674static void handleAlwaysInlineAttr(Sema &S, Decl *D,
3675 const AttributeList &Attr) {
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00003676 if (checkAttrMutualExclusion<NotTailCalledAttr>(S, D, Attr.getRange(),
Charles Davis0e379112016-08-08 21:19:08 +00003677 Attr.getName()))
Akira Hatanakac8667622015-11-06 23:56:15 +00003678 return;
3679
Paul Robinson080b1f32015-01-13 18:34:56 +00003680 if (AlwaysInlineAttr *Inline = S.mergeAlwaysInlineAttr(
3681 D, Attr.getRange(), Attr.getName(),
3682 Attr.getAttributeSpellingListIndex()))
3683 D->addAttr(Inline);
Paul Robinsonf0674352014-03-31 22:29:15 +00003684}
3685
Paul Robinson080b1f32015-01-13 18:34:56 +00003686static void handleMinSizeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3687 if (MinSizeAttr *MinSize = S.mergeMinSizeAttr(
3688 D, Attr.getRange(), Attr.getAttributeSpellingListIndex()))
3689 D->addAttr(MinSize);
Paul Robinsonaae2fba2014-12-10 23:34:36 +00003690}
3691
Paul Robinsonf0674352014-03-31 22:29:15 +00003692static void handleOptimizeNoneAttr(Sema &S, Decl *D,
3693 const AttributeList &Attr) {
Paul Robinson080b1f32015-01-13 18:34:56 +00003694 if (OptimizeNoneAttr *Optnone = S.mergeOptimizeNoneAttr(
3695 D, Attr.getRange(), Attr.getAttributeSpellingListIndex()))
3696 D->addAttr(Optnone);
Paul Robinsonf0674352014-03-31 22:29:15 +00003697}
3698
Justin Lebar10411012016-09-30 23:57:30 +00003699static void handleSharedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3700 if (checkAttrMutualExclusion<CUDAConstantAttr>(S, D, Attr.getRange(),
3701 Attr.getName()))
3702 return;
3703 auto *VD = cast<VarDecl>(D);
3704 if (VD->hasExternalStorage()) {
3705 S.Diag(Attr.getLoc(), diag::err_cuda_extern_shared) << VD;
3706 return;
3707 }
3708 D->addAttr(::new (S.Context) CUDASharedAttr(
3709 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
3710}
3711
Chandler Carruthedc2c642011-07-02 00:01:44 +00003712static void handleGlobalAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Justin Lebar3eaaf862016-01-13 01:07:35 +00003713 if (checkAttrMutualExclusion<CUDADeviceAttr>(S, D, Attr.getRange(),
3714 Attr.getName()) ||
3715 checkAttrMutualExclusion<CUDAHostAttr>(S, D, Attr.getRange(),
3716 Attr.getName())) {
3717 return;
3718 }
Aaron Ballman3aff6332013-12-02 19:30:36 +00003719 FunctionDecl *FD = cast<FunctionDecl>(D);
Alp Toker314cc812014-01-25 16:55:45 +00003720 if (!FD->getReturnType()->isVoidType()) {
Alp Tokerf5b10792014-07-02 12:55:58 +00003721 SourceRange RTRange = FD->getReturnTypeSourceRange();
3722 S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return)
Aaron Ballman3aff6332013-12-02 19:30:36 +00003723 << FD->getType()
Alp Tokerf5b10792014-07-02 12:55:58 +00003724 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
3725 : FixItHint());
Aaron Ballman3aff6332013-12-02 19:30:36 +00003726 return;
Peter Collingbourne6ab610c2010-12-01 03:15:31 +00003727 }
Justin Lebarc66a1062016-01-20 00:26:57 +00003728 if (const auto *Method = dyn_cast<CXXMethodDecl>(FD)) {
3729 if (Method->isInstance()) {
3730 S.Diag(Method->getLocStart(), diag::err_kern_is_nonstatic_method)
3731 << Method;
3732 return;
3733 }
3734 S.Diag(Method->getLocStart(), diag::warn_kern_is_method) << Method;
3735 }
3736 // Only warn for "inline" when compiling for host, to cut down on noise.
3737 if (FD->isInlineSpecified() && !S.getLangOpts().CUDAIsDevice)
3738 S.Diag(FD->getLocStart(), diag::warn_kern_is_inline) << FD;
Peter Collingbourne6ab610c2010-12-01 03:15:31 +00003739
Aaron Ballman3aff6332013-12-02 19:30:36 +00003740 D->addAttr(::new (S.Context)
3741 CUDAGlobalAttr(Attr.getRange(), S.Context,
Eli Bendersky83860042014-09-02 22:00:06 +00003742 Attr.getAttributeSpellingListIndex()));
Peter Collingbourne6ab610c2010-12-01 03:15:31 +00003743}
3744
Chandler Carruthedc2c642011-07-02 00:01:44 +00003745static void handleGNUInlineAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003746 FunctionDecl *Fn = cast<FunctionDecl>(D);
Douglas Gregor35b57532009-10-27 21:01:01 +00003747 if (!Fn->isInlineSpecified()) {
Chris Lattnerddf6ca02009-04-20 19:12:28 +00003748 S.Diag(Attr.getLoc(), diag::warn_gnu_inline_attribute_requires_inline);
Chris Lattner4225e232009-04-14 17:02:11 +00003749 return;
3750 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00003751
Michael Han99315932013-01-24 16:46:58 +00003752 D->addAttr(::new (S.Context)
3753 GNUInlineAttr(Attr.getRange(), S.Context,
3754 Attr.getAttributeSpellingListIndex()));
Chris Lattnereaad6b72009-04-14 16:30:50 +00003755}
3756
Chandler Carruthedc2c642011-07-02 00:01:44 +00003757static void handleCallConvAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00003758 if (hasDeclarator(D)) return;
Abramo Bagnara50099372010-04-30 13:10:51 +00003759
Chandler Carruthff4c4f02011-07-01 23:49:12 +00003760 // Diagnostic is emitted elsewhere: here we store the (valid) Attr
John McCall3882ace2011-01-05 12:14:39 +00003761 // in the Decl node for syntactic reasoning, e.g., pretty-printing.
3762 CallingConv CC;
Richard Smitheec7cb12015-05-28 23:38:53 +00003763 if (S.CheckCallingConvAttr(Attr, CC, /*FD*/nullptr))
John McCall3882ace2011-01-05 12:14:39 +00003764 return;
3765
Chandler Carruthff4c4f02011-07-01 23:49:12 +00003766 if (!isa<ObjCMethodDecl>(D)) {
3767 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3768 << Attr.getName() << ExpectedFunctionOrMethod;
John McCall3882ace2011-01-05 12:14:39 +00003769 return;
3770 }
3771
Chandler Carruthff4c4f02011-07-01 23:49:12 +00003772 switch (Attr.getKind()) {
Alexis Hunt3bc72c12012-06-19 23:57:03 +00003773 case AttributeList::AT_FastCall:
Michael Han99315932013-01-24 16:46:58 +00003774 D->addAttr(::new (S.Context)
3775 FastCallAttr(Attr.getRange(), S.Context,
3776 Attr.getAttributeSpellingListIndex()));
Abramo Bagnara50099372010-04-30 13:10:51 +00003777 return;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00003778 case AttributeList::AT_StdCall:
Michael Han99315932013-01-24 16:46:58 +00003779 D->addAttr(::new (S.Context)
3780 StdCallAttr(Attr.getRange(), S.Context,
3781 Attr.getAttributeSpellingListIndex()));
Abramo Bagnara50099372010-04-30 13:10:51 +00003782 return;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00003783 case AttributeList::AT_ThisCall:
Michael Han99315932013-01-24 16:46:58 +00003784 D->addAttr(::new (S.Context)
3785 ThisCallAttr(Attr.getRange(), S.Context,
3786 Attr.getAttributeSpellingListIndex()));
Douglas Gregor4d13d102010-08-30 23:30:49 +00003787 return;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00003788 case AttributeList::AT_CDecl:
Michael Han99315932013-01-24 16:46:58 +00003789 D->addAttr(::new (S.Context)
3790 CDeclAttr(Attr.getRange(), S.Context,
3791 Attr.getAttributeSpellingListIndex()));
Abramo Bagnara50099372010-04-30 13:10:51 +00003792 return;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00003793 case AttributeList::AT_Pascal:
Michael Han99315932013-01-24 16:46:58 +00003794 D->addAttr(::new (S.Context)
3795 PascalAttr(Attr.getRange(), S.Context,
3796 Attr.getAttributeSpellingListIndex()));
Dawn Perchik335e16b2010-09-03 01:29:35 +00003797 return;
John McCall477f2bb2016-03-03 06:39:32 +00003798 case AttributeList::AT_SwiftCall:
3799 D->addAttr(::new (S.Context)
3800 SwiftCallAttr(Attr.getRange(), S.Context,
3801 Attr.getAttributeSpellingListIndex()));
3802 return;
Reid Klecknerd7857f02014-10-24 17:42:17 +00003803 case AttributeList::AT_VectorCall:
3804 D->addAttr(::new (S.Context)
3805 VectorCallAttr(Attr.getRange(), S.Context,
3806 Attr.getAttributeSpellingListIndex()));
3807 return;
Charles Davisb5a214e2013-08-30 04:39:01 +00003808 case AttributeList::AT_MSABI:
3809 D->addAttr(::new (S.Context)
3810 MSABIAttr(Attr.getRange(), S.Context,
3811 Attr.getAttributeSpellingListIndex()));
3812 return;
3813 case AttributeList::AT_SysVABI:
3814 D->addAttr(::new (S.Context)
3815 SysVABIAttr(Attr.getRange(), S.Context,
3816 Attr.getAttributeSpellingListIndex()));
3817 return;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00003818 case AttributeList::AT_Pcs: {
Anton Korobeynikov231e8752011-04-14 20:06:49 +00003819 PcsAttr::PCSType PCS;
Benjamin Kramer25885f42012-08-14 13:24:39 +00003820 switch (CC) {
3821 case CC_AAPCS:
Anton Korobeynikov231e8752011-04-14 20:06:49 +00003822 PCS = PcsAttr::AAPCS;
Benjamin Kramer25885f42012-08-14 13:24:39 +00003823 break;
3824 case CC_AAPCS_VFP:
Anton Korobeynikov231e8752011-04-14 20:06:49 +00003825 PCS = PcsAttr::AAPCS_VFP;
Benjamin Kramer25885f42012-08-14 13:24:39 +00003826 break;
3827 default:
3828 llvm_unreachable("unexpected calling convention in pcs attribute");
Anton Korobeynikov231e8752011-04-14 20:06:49 +00003829 }
3830
Michael Han99315932013-01-24 16:46:58 +00003831 D->addAttr(::new (S.Context)
3832 PcsAttr(Attr.getRange(), S.Context, PCS,
3833 Attr.getAttributeSpellingListIndex()));
Derek Schuffa2020962012-10-16 22:30:41 +00003834 return;
Anton Korobeynikov231e8752011-04-14 20:06:49 +00003835 }
Guy Benyeif0a014b2012-12-25 08:53:55 +00003836 case AttributeList::AT_IntelOclBicc:
Michael Han99315932013-01-24 16:46:58 +00003837 D->addAttr(::new (S.Context)
3838 IntelOclBiccAttr(Attr.getRange(), S.Context,
3839 Attr.getAttributeSpellingListIndex()));
Guy Benyeif0a014b2012-12-25 08:53:55 +00003840 return;
Roman Levenstein35aa5ce2016-03-16 18:00:46 +00003841 case AttributeList::AT_PreserveMost:
3842 D->addAttr(::new (S.Context) PreserveMostAttr(
3843 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
3844 return;
3845 case AttributeList::AT_PreserveAll:
3846 D->addAttr(::new (S.Context) PreserveAllAttr(
3847 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
3848 return;
Abramo Bagnara50099372010-04-30 13:10:51 +00003849 default:
3850 llvm_unreachable("unexpected attribute kind");
Abramo Bagnara50099372010-04-30 13:10:51 +00003851 }
3852}
3853
Aaron Ballman02df2e02012-12-09 17:45:41 +00003854bool Sema::CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC,
3855 const FunctionDecl *FD) {
John McCall3882ace2011-01-05 12:14:39 +00003856 if (attr.isInvalid())
3857 return true;
3858
John McCall3b5a8f52016-03-03 00:10:03 +00003859 if (attr.hasProcessingCache()) {
3860 CC = (CallingConv) attr.getProcessingCache();
3861 return false;
3862 }
3863
Benjamin Kramer833fb9f2012-08-14 13:13:47 +00003864 unsigned ReqArgs = attr.getKind() == AttributeList::AT_Pcs ? 1 : 0;
Aaron Ballman00e99962013-08-31 01:11:41 +00003865 if (!checkAttributeNumArgs(*this, attr, ReqArgs)) {
John McCall3882ace2011-01-05 12:14:39 +00003866 attr.setInvalid();
3867 return true;
3868 }
3869
Aaron Ballmanab7691c2014-01-09 22:48:32 +00003870 // TODO: diagnose uses of these conventions on the wrong target.
John McCall3882ace2011-01-05 12:14:39 +00003871 switch (attr.getKind()) {
Alexis Hunt3bc72c12012-06-19 23:57:03 +00003872 case AttributeList::AT_CDecl: CC = CC_C; break;
3873 case AttributeList::AT_FastCall: CC = CC_X86FastCall; break;
3874 case AttributeList::AT_StdCall: CC = CC_X86StdCall; break;
3875 case AttributeList::AT_ThisCall: CC = CC_X86ThisCall; break;
3876 case AttributeList::AT_Pascal: CC = CC_X86Pascal; break;
John McCall477f2bb2016-03-03 06:39:32 +00003877 case AttributeList::AT_SwiftCall: CC = CC_Swift; break;
Reid Klecknerd7857f02014-10-24 17:42:17 +00003878 case AttributeList::AT_VectorCall: CC = CC_X86VectorCall; break;
Charles Davisb5a214e2013-08-30 04:39:01 +00003879 case AttributeList::AT_MSABI:
3880 CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_C :
3881 CC_X86_64Win64;
3882 break;
3883 case AttributeList::AT_SysVABI:
3884 CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_X86_64SysV :
3885 CC_C;
3886 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00003887 case AttributeList::AT_Pcs: {
Aaron Ballmand6600a52013-09-13 17:48:25 +00003888 StringRef StrRef;
Tim Northover6a6b63b2013-10-01 14:34:18 +00003889 if (!checkStringLiteralArgumentAttr(attr, 0, StrRef)) {
Anton Korobeynikov231e8752011-04-14 20:06:49 +00003890 attr.setInvalid();
3891 return true;
3892 }
Anton Korobeynikov231e8752011-04-14 20:06:49 +00003893 if (StrRef == "aapcs") {
3894 CC = CC_AAPCS;
3895 break;
3896 } else if (StrRef == "aapcs-vfp") {
3897 CC = CC_AAPCS_VFP;
3898 break;
3899 }
Benjamin Kramer833fb9f2012-08-14 13:13:47 +00003900
3901 attr.setInvalid();
3902 Diag(attr.getLoc(), diag::err_invalid_pcs);
3903 return true;
Anton Korobeynikov231e8752011-04-14 20:06:49 +00003904 }
Guy Benyeif0a014b2012-12-25 08:53:55 +00003905 case AttributeList::AT_IntelOclBicc: CC = CC_IntelOclBicc; break;
Roman Levenstein35aa5ce2016-03-16 18:00:46 +00003906 case AttributeList::AT_PreserveMost: CC = CC_PreserveMost; break;
3907 case AttributeList::AT_PreserveAll: CC = CC_PreserveAll; break;
David Blaikie8a40f702012-01-17 06:56:22 +00003908 default: llvm_unreachable("unexpected attribute kind");
John McCall3882ace2011-01-05 12:14:39 +00003909 }
3910
Aaron Ballmane91c6be2012-10-02 14:26:08 +00003911 const TargetInfo &TI = Context.getTargetInfo();
3912 TargetInfo::CallingConvCheckResult A = TI.checkCallingConvention(CC);
Reid Kleckner9fde2e02015-02-26 19:43:46 +00003913 if (A != TargetInfo::CCCR_OK) {
3914 if (A == TargetInfo::CCCR_Warning)
3915 Diag(attr.getLoc(), diag::warn_cconv_ignored) << attr.getName();
Aaron Ballman02df2e02012-12-09 17:45:41 +00003916
Reid Kleckner9fde2e02015-02-26 19:43:46 +00003917 // This convention is not valid for the target. Use the default function or
3918 // method calling convention.
Alexey Bataeva7547182016-05-18 09:06:38 +00003919 bool IsCXXMethod = false, IsVariadic = false;
3920 if (FD) {
3921 IsCXXMethod = FD->isCXXInstanceMember();
3922 IsVariadic = FD->isVariadic();
3923 }
3924 CC = Context.getDefaultCallingConvention(IsVariadic, IsCXXMethod);
Aaron Ballmane91c6be2012-10-02 14:26:08 +00003925 }
3926
John McCall3b5a8f52016-03-03 00:10:03 +00003927 attr.setProcessingCache((unsigned) CC);
John McCall3882ace2011-01-05 12:14:39 +00003928 return false;
3929}
3930
John McCall477f2bb2016-03-03 06:39:32 +00003931/// Pointer-like types in the default address space.
3932static bool isValidSwiftContextType(QualType type) {
3933 if (!type->hasPointerRepresentation())
3934 return type->isDependentType();
3935 return type->getPointeeType().getAddressSpace() == 0;
3936}
3937
3938/// Pointers and references in the default address space.
3939static bool isValidSwiftIndirectResultType(QualType type) {
3940 if (auto ptrType = type->getAs<PointerType>()) {
3941 type = ptrType->getPointeeType();
3942 } else if (auto refType = type->getAs<ReferenceType>()) {
3943 type = refType->getPointeeType();
3944 } else {
3945 return type->isDependentType();
3946 }
3947 return type.getAddressSpace() == 0;
3948}
3949
3950/// Pointers and references to pointers in the default address space.
3951static bool isValidSwiftErrorResultType(QualType type) {
3952 if (auto ptrType = type->getAs<PointerType>()) {
3953 type = ptrType->getPointeeType();
3954 } else if (auto refType = type->getAs<ReferenceType>()) {
3955 type = refType->getPointeeType();
3956 } else {
3957 return type->isDependentType();
3958 }
3959 if (!type.getQualifiers().empty())
3960 return false;
3961 return isValidSwiftContextType(type);
3962}
3963
3964static void handleParameterABIAttr(Sema &S, Decl *D, const AttributeList &attr,
3965 ParameterABI abi) {
3966 S.AddParameterABIAttr(attr.getRange(), D, abi,
3967 attr.getAttributeSpellingListIndex());
3968}
3969
3970void Sema::AddParameterABIAttr(SourceRange range, Decl *D, ParameterABI abi,
3971 unsigned spellingIndex) {
3972
3973 QualType type = cast<ParmVarDecl>(D)->getType();
3974
3975 if (auto existingAttr = D->getAttr<ParameterABIAttr>()) {
3976 if (existingAttr->getABI() != abi) {
3977 Diag(range.getBegin(), diag::err_attributes_are_not_compatible)
3978 << getParameterABISpelling(abi) << existingAttr;
3979 Diag(existingAttr->getLocation(), diag::note_conflicting_attribute);
3980 return;
3981 }
3982 }
3983
3984 switch (abi) {
3985 case ParameterABI::Ordinary:
3986 llvm_unreachable("explicit attribute for ordinary parameter ABI?");
3987
3988 case ParameterABI::SwiftContext:
3989 if (!isValidSwiftContextType(type)) {
3990 Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type)
3991 << getParameterABISpelling(abi)
3992 << /*pointer to pointer */ 0 << type;
3993 }
3994 D->addAttr(::new (Context)
3995 SwiftContextAttr(range, Context, spellingIndex));
3996 return;
3997
3998 case ParameterABI::SwiftErrorResult:
3999 if (!isValidSwiftErrorResultType(type)) {
4000 Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type)
4001 << getParameterABISpelling(abi)
4002 << /*pointer to pointer */ 1 << type;
4003 }
4004 D->addAttr(::new (Context)
4005 SwiftErrorResultAttr(range, Context, spellingIndex));
4006 return;
4007
4008 case ParameterABI::SwiftIndirectResult:
4009 if (!isValidSwiftIndirectResultType(type)) {
4010 Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type)
4011 << getParameterABISpelling(abi)
4012 << /*pointer*/ 0 << type;
4013 }
4014 D->addAttr(::new (Context)
4015 SwiftIndirectResultAttr(range, Context, spellingIndex));
4016 return;
4017 }
4018 llvm_unreachable("bad parameter ABI attribute");
4019}
4020
John McCall3882ace2011-01-05 12:14:39 +00004021/// Checks a regparm attribute, returning true if it is ill-formed and
4022/// otherwise setting numParams to the appropriate value.
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004023bool Sema::CheckRegparmAttr(const AttributeList &Attr, unsigned &numParams) {
4024 if (Attr.isInvalid())
John McCall3882ace2011-01-05 12:14:39 +00004025 return true;
4026
Aaron Ballmanc2cbc662013-07-18 18:01:48 +00004027 if (!checkAttributeNumArgs(*this, Attr, 1)) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004028 Attr.setInvalid();
John McCall3882ace2011-01-05 12:14:39 +00004029 return true;
Fariborz Jahaniana2d609e2009-03-27 18:38:55 +00004030 }
Eli Friedman7044b762009-03-27 21:06:47 +00004031
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00004032 uint32_t NP;
Aaron Ballman00e99962013-08-31 01:11:41 +00004033 Expr *NumParamsExpr = Attr.getArgAsExpr(0);
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00004034 if (!checkUInt32Argument(*this, Attr, NumParamsExpr, NP)) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004035 Attr.setInvalid();
John McCall3882ace2011-01-05 12:14:39 +00004036 return true;
Eli Friedman7044b762009-03-27 21:06:47 +00004037 }
4038
Douglas Gregore8bbc122011-09-02 00:18:52 +00004039 if (Context.getTargetInfo().getRegParmMax() == 0) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004040 Diag(Attr.getLoc(), diag::err_attribute_regparm_wrong_platform)
Eli Friedman7044b762009-03-27 21:06:47 +00004041 << NumParamsExpr->getSourceRange();
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004042 Attr.setInvalid();
John McCall3882ace2011-01-05 12:14:39 +00004043 return true;
Eli Friedman7044b762009-03-27 21:06:47 +00004044 }
4045
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00004046 numParams = NP;
Douglas Gregore8bbc122011-09-02 00:18:52 +00004047 if (numParams > Context.getTargetInfo().getRegParmMax()) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004048 Diag(Attr.getLoc(), diag::err_attribute_regparm_invalid_number)
Douglas Gregore8bbc122011-09-02 00:18:52 +00004049 << Context.getTargetInfo().getRegParmMax() << NumParamsExpr->getSourceRange();
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004050 Attr.setInvalid();
John McCall3882ace2011-01-05 12:14:39 +00004051 return true;
Eli Friedman7044b762009-03-27 21:06:47 +00004052 }
4053
John McCall3882ace2011-01-05 12:14:39 +00004054 return false;
Fariborz Jahaniana2d609e2009-03-27 18:38:55 +00004055}
4056
Artem Belevichbcec9da2016-06-06 22:54:57 +00004057// Checks whether an argument of launch_bounds attribute is
4058// acceptable, performs implicit conversion to Rvalue, and returns
4059// non-nullptr Expr result on success. Otherwise, it returns nullptr
4060// and may output an error.
4061static Expr *makeLaunchBoundsArgExpr(Sema &S, Expr *E,
4062 const CUDALaunchBoundsAttr &Attr,
4063 const unsigned Idx) {
Artem Belevich7093e402015-04-21 22:55:54 +00004064 if (S.DiagnoseUnexpandedParameterPack(E))
Artem Belevichbcec9da2016-06-06 22:54:57 +00004065 return nullptr;
Artem Belevich7093e402015-04-21 22:55:54 +00004066
4067 // Accept template arguments for now as they depend on something else.
4068 // We'll get to check them when they eventually get instantiated.
4069 if (E->isValueDependent())
Artem Belevichbcec9da2016-06-06 22:54:57 +00004070 return E;
Artem Belevich7093e402015-04-21 22:55:54 +00004071
4072 llvm::APSInt I(64);
4073 if (!E->isIntegerConstantExpr(I, S.Context)) {
4074 S.Diag(E->getExprLoc(), diag::err_attribute_argument_n_type)
4075 << &Attr << Idx << AANT_ArgumentIntegerConstant << E->getSourceRange();
Artem Belevichbcec9da2016-06-06 22:54:57 +00004076 return nullptr;
Artem Belevich7093e402015-04-21 22:55:54 +00004077 }
4078 // Make sure we can fit it in 32 bits.
4079 if (!I.isIntN(32)) {
4080 S.Diag(E->getExprLoc(), diag::err_ice_too_large) << I.toString(10, false)
4081 << 32 << /* Unsigned */ 1;
Artem Belevichbcec9da2016-06-06 22:54:57 +00004082 return nullptr;
Artem Belevich7093e402015-04-21 22:55:54 +00004083 }
4084 if (I < 0)
4085 S.Diag(E->getExprLoc(), diag::warn_attribute_argument_n_negative)
4086 << &Attr << Idx << E->getSourceRange();
4087
Artem Belevichbcec9da2016-06-06 22:54:57 +00004088 // We may need to perform implicit conversion of the argument.
4089 InitializedEntity Entity = InitializedEntity::InitializeParameter(
4090 S.Context, S.Context.getConstType(S.Context.IntTy), /*consume*/ false);
4091 ExprResult ValArg = S.PerformCopyInitialization(Entity, SourceLocation(), E);
4092 assert(!ValArg.isInvalid() &&
4093 "Unexpected PerformCopyInitialization() failure.");
4094
4095 return ValArg.getAs<Expr>();
Artem Belevich7093e402015-04-21 22:55:54 +00004096}
4097
4098void Sema::AddLaunchBoundsAttr(SourceRange AttrRange, Decl *D, Expr *MaxThreads,
4099 Expr *MinBlocks, unsigned SpellingListIndex) {
4100 CUDALaunchBoundsAttr TmpAttr(AttrRange, Context, MaxThreads, MinBlocks,
4101 SpellingListIndex);
Artem Belevichbcec9da2016-06-06 22:54:57 +00004102 MaxThreads = makeLaunchBoundsArgExpr(*this, MaxThreads, TmpAttr, 0);
4103 if (MaxThreads == nullptr)
Aaron Ballman3aff6332013-12-02 19:30:36 +00004104 return;
4105
Artem Belevichbcec9da2016-06-06 22:54:57 +00004106 if (MinBlocks) {
4107 MinBlocks = makeLaunchBoundsArgExpr(*this, MinBlocks, TmpAttr, 1);
4108 if (MinBlocks == nullptr)
4109 return;
4110 }
Artem Belevich7093e402015-04-21 22:55:54 +00004111
4112 D->addAttr(::new (Context) CUDALaunchBoundsAttr(
4113 AttrRange, Context, MaxThreads, MinBlocks, SpellingListIndex));
4114}
4115
4116static void handleLaunchBoundsAttr(Sema &S, Decl *D,
4117 const AttributeList &Attr) {
4118 if (!checkAttributeAtLeastNumArgs(S, Attr, 1) ||
4119 !checkAttributeAtMostNumArgs(S, Attr, 2))
4120 return;
4121
4122 S.AddLaunchBoundsAttr(Attr.getRange(), D, Attr.getArgAsExpr(0),
4123 Attr.getNumArgs() > 1 ? Attr.getArgAsExpr(1) : nullptr,
4124 Attr.getAttributeSpellingListIndex());
Peter Collingbourne827301e2010-12-12 23:03:07 +00004125}
4126
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004127static void handleArgumentWithTypeTagAttr(Sema &S, Decl *D,
4128 const AttributeList &Attr) {
Aaron Ballman00e99962013-08-31 01:11:41 +00004129 if (!Attr.isArgIdent(0)) {
Aaron Ballman29982272013-07-23 14:03:57 +00004130 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
Aaron Ballman3bf758c2013-07-30 01:31:03 +00004131 << Attr.getName() << /* arg num = */ 1 << AANT_ArgumentIdentifier;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004132 return;
4133 }
Aaron Ballman00e99962013-08-31 01:11:41 +00004134
4135 if (!checkAttributeNumArgs(S, Attr, 3))
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004136 return;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004137
Aaron Ballman00e99962013-08-31 01:11:41 +00004138 IdentifierInfo *ArgumentKind = Attr.getArgAsIdent(0)->Ident;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004139
4140 if (!isFunctionOrMethod(D) || !hasFunctionProto(D)) {
4141 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
4142 << Attr.getName() << ExpectedFunctionOrMethod;
4143 return;
4144 }
4145
4146 uint64_t ArgumentIdx;
Alp Toker601b22c2014-01-21 23:35:24 +00004147 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 2, Attr.getArgAsExpr(1),
4148 ArgumentIdx))
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004149 return;
4150
4151 uint64_t TypeTagIdx;
Alp Toker601b22c2014-01-21 23:35:24 +00004152 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 3, Attr.getArgAsExpr(2),
4153 TypeTagIdx))
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004154 return;
4155
Aaron Ballmanfaed0fa2013-12-26 16:30:30 +00004156 bool IsPointer = (Attr.getName()->getName() == "pointer_with_type_tag");
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004157 if (IsPointer) {
4158 // Ensure that buffer has a pointer type.
Alp Toker601b22c2014-01-21 23:35:24 +00004159 QualType BufferTy = getFunctionOrMethodParamType(D, ArgumentIdx);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004160 if (!BufferTy->isPointerType()) {
4161 S.Diag(Attr.getLoc(), diag::err_attribute_pointers_only)
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00004162 << Attr.getName() << 0;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004163 }
4164 }
4165
Michael Han99315932013-01-24 16:46:58 +00004166 D->addAttr(::new (S.Context)
4167 ArgumentWithTypeTagAttr(Attr.getRange(), S.Context, ArgumentKind,
4168 ArgumentIdx, TypeTagIdx, IsPointer,
4169 Attr.getAttributeSpellingListIndex()));
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004170}
4171
4172static void handleTypeTagForDatatypeAttr(Sema &S, Decl *D,
4173 const AttributeList &Attr) {
Aaron Ballman00e99962013-08-31 01:11:41 +00004174 if (!Attr.isArgIdent(0)) {
Aaron Ballman29982272013-07-23 14:03:57 +00004175 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
Aaron Ballman3bf758c2013-07-30 01:31:03 +00004176 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004177 return;
4178 }
Aaron Ballman00e99962013-08-31 01:11:41 +00004179
4180 if (!checkAttributeNumArgs(S, Attr, 1))
4181 return;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004182
Aaron Ballman90f8c6f2013-11-25 18:50:49 +00004183 if (!isa<VarDecl>(D)) {
4184 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
4185 << Attr.getName() << ExpectedVariable;
4186 return;
4187 }
4188
Aaron Ballman00e99962013-08-31 01:11:41 +00004189 IdentifierInfo *PointerKind = Attr.getArgAsIdent(0)->Ident;
Craig Topperc3ec1492014-05-26 06:22:03 +00004190 TypeSourceInfo *MatchingCTypeLoc = nullptr;
Richard Smithb87c4652013-10-31 21:23:20 +00004191 S.GetTypeFromParser(Attr.getMatchingCType(), &MatchingCTypeLoc);
4192 assert(MatchingCTypeLoc && "no type source info for attribute argument");
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004193
Michael Han99315932013-01-24 16:46:58 +00004194 D->addAttr(::new (S.Context)
4195 TypeTagForDatatypeAttr(Attr.getRange(), S.Context, PointerKind,
Richard Smithb87c4652013-10-31 21:23:20 +00004196 MatchingCTypeLoc,
Michael Han99315932013-01-24 16:46:58 +00004197 Attr.getLayoutCompatible(),
4198 Attr.getMustBeNull(),
4199 Attr.getAttributeSpellingListIndex()));
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004200}
4201
Chris Lattner9e2aafe2008-06-29 00:23:49 +00004202//===----------------------------------------------------------------------===//
Ted Kremenek9ecdfaf2009-05-09 02:44:38 +00004203// Checker-specific attribute handlers.
4204//===----------------------------------------------------------------------===//
4205
Fariborz Jahanian4eba3dc2014-06-12 16:12:30 +00004206static bool isValidSubjectOfNSReturnsRetainedAttribute(QualType type) {
Fariborz Jahanian9c100322014-06-11 21:22:53 +00004207 return type->isDependentType() ||
Fariborz Jahanian4eba3dc2014-06-12 16:12:30 +00004208 type->isObjCRetainableType();
Fariborz Jahanian9c100322014-06-11 21:22:53 +00004209}
4210
John McCalled433932011-01-25 03:31:58 +00004211static bool isValidSubjectOfNSAttribute(Sema &S, QualType type) {
Douglas Gregorf892c7f2011-10-09 22:26:49 +00004212 return type->isDependentType() ||
4213 type->isObjCObjectPointerType() ||
4214 S.Context.isObjCNSObjectType(type);
John McCalled433932011-01-25 03:31:58 +00004215}
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004216
John McCalled433932011-01-25 03:31:58 +00004217static bool isValidSubjectOfCFAttribute(Sema &S, QualType type) {
Douglas Gregorf892c7f2011-10-09 22:26:49 +00004218 return type->isDependentType() ||
4219 type->isPointerType() ||
4220 isValidSubjectOfNSAttribute(S, type);
John McCalled433932011-01-25 03:31:58 +00004221}
4222
Chandler Carruthedc2c642011-07-02 00:01:44 +00004223static void handleNSConsumedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
John McCall3b5a8f52016-03-03 00:10:03 +00004224 S.AddNSConsumedAttr(Attr.getRange(), D, Attr.getAttributeSpellingListIndex(),
4225 Attr.getKind() == AttributeList::AT_NSConsumed,
4226 /*template instantiation*/ false);
4227}
Aaron Ballman74eeeae2013-11-27 13:27:02 +00004228
John McCall3b5a8f52016-03-03 00:10:03 +00004229void Sema::AddNSConsumedAttr(SourceRange attrRange, Decl *D,
4230 unsigned spellingIndex, bool isNSConsumed,
4231 bool isTemplateInstantiation) {
4232 ParmVarDecl *param = cast<ParmVarDecl>(D);
4233 bool typeOK;
4234
4235 if (isNSConsumed) {
4236 typeOK = isValidSubjectOfNSAttribute(*this, param->getType());
John McCalled433932011-01-25 03:31:58 +00004237 } else {
John McCall3b5a8f52016-03-03 00:10:03 +00004238 typeOK = isValidSubjectOfCFAttribute(*this, param->getType());
John McCalled433932011-01-25 03:31:58 +00004239 }
4240
4241 if (!typeOK) {
John McCall3b5a8f52016-03-03 00:10:03 +00004242 // These attributes are normally just advisory, but in ARC, ns_consumed
4243 // is significant. Allow non-dependent code to contain inappropriate
4244 // attributes even in ARC, but require template instantiations to be
4245 // set up correctly.
4246 Diag(D->getLocStart(),
4247 (isTemplateInstantiation && isNSConsumed &&
4248 getLangOpts().ObjCAutoRefCount
4249 ? diag::err_ns_attribute_wrong_parameter_type
4250 : diag::warn_ns_attribute_wrong_parameter_type))
4251 << attrRange
4252 << (isNSConsumed ? "ns_consumed" : "cf_consumed")
4253 << (isNSConsumed ? /*objc pointers*/ 0 : /*cf pointers*/ 1);
John McCalled433932011-01-25 03:31:58 +00004254 return;
4255 }
4256
John McCall3b5a8f52016-03-03 00:10:03 +00004257 if (isNSConsumed)
4258 param->addAttr(::new (Context)
4259 NSConsumedAttr(attrRange, Context, spellingIndex));
John McCalled433932011-01-25 03:31:58 +00004260 else
John McCall3b5a8f52016-03-03 00:10:03 +00004261 param->addAttr(::new (Context)
4262 CFConsumedAttr(attrRange, Context, spellingIndex));
John McCalled433932011-01-25 03:31:58 +00004263}
4264
Chandler Carruthedc2c642011-07-02 00:01:44 +00004265static void handleNSReturnsRetainedAttr(Sema &S, Decl *D,
4266 const AttributeList &Attr) {
John McCalled433932011-01-25 03:31:58 +00004267 QualType returnType;
Mike Stumpd3bb5572009-07-24 19:02:52 +00004268
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004269 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
Alp Toker314cc812014-01-25 16:55:45 +00004270 returnType = MD->getReturnType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00004271 else if (S.getLangOpts().ObjCAutoRefCount && hasDeclarator(D) &&
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004272 (Attr.getKind() == AttributeList::AT_NSReturnsRetained))
John McCall31168b02011-06-15 23:02:42 +00004273 return; // ignore: was handled as a type attribute
Fariborz Jahanian272b7dc2012-08-28 22:26:21 +00004274 else if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
4275 returnType = PD->getType();
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004276 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
Alp Toker314cc812014-01-25 16:55:45 +00004277 returnType = FD->getReturnType();
Douglas Gregoreb6e64c2015-06-19 23:17:46 +00004278 else if (auto *Param = dyn_cast<ParmVarDecl>(D)) {
4279 returnType = Param->getType()->getPointeeType();
4280 if (returnType.isNull()) {
4281 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_parameter_type)
4282 << Attr.getName() << /*pointer-to-CF*/2
4283 << Attr.getRange();
4284 return;
4285 }
4286 } else {
4287 AttributeDeclKind ExpectedDeclKind;
4288 switch (Attr.getKind()) {
4289 default: llvm_unreachable("invalid ownership attribute");
4290 case AttributeList::AT_NSReturnsRetained:
4291 case AttributeList::AT_NSReturnsAutoreleased:
4292 case AttributeList::AT_NSReturnsNotRetained:
4293 ExpectedDeclKind = ExpectedFunctionOrMethod;
4294 break;
4295
4296 case AttributeList::AT_CFReturnsRetained:
4297 case AttributeList::AT_CFReturnsNotRetained:
4298 ExpectedDeclKind = ExpectedFunctionMethodOrParameter;
4299 break;
4300 }
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004301 S.Diag(D->getLocStart(), diag::warn_attribute_wrong_decl_type)
Douglas Gregoreb6e64c2015-06-19 23:17:46 +00004302 << Attr.getRange() << Attr.getName() << ExpectedDeclKind;
Ted Kremenek9ecdfaf2009-05-09 02:44:38 +00004303 return;
4304 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00004305
John McCalled433932011-01-25 03:31:58 +00004306 bool typeOK;
4307 bool cf;
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004308 switch (Attr.getKind()) {
David Blaikie8a40f702012-01-17 06:56:22 +00004309 default: llvm_unreachable("invalid ownership attribute");
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004310 case AttributeList::AT_NSReturnsRetained:
Fariborz Jahanian4eba3dc2014-06-12 16:12:30 +00004311 typeOK = isValidSubjectOfNSReturnsRetainedAttribute(returnType);
Fariborz Jahanian9c100322014-06-11 21:22:53 +00004312 cf = false;
4313 break;
4314
4315 case AttributeList::AT_NSReturnsAutoreleased:
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004316 case AttributeList::AT_NSReturnsNotRetained:
John McCalled433932011-01-25 03:31:58 +00004317 typeOK = isValidSubjectOfNSAttribute(S, returnType);
4318 cf = false;
4319 break;
4320
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004321 case AttributeList::AT_CFReturnsRetained:
4322 case AttributeList::AT_CFReturnsNotRetained:
John McCalled433932011-01-25 03:31:58 +00004323 typeOK = isValidSubjectOfCFAttribute(S, returnType);
4324 cf = true;
4325 break;
4326 }
4327
4328 if (!typeOK) {
Douglas Gregoreb6e64c2015-06-19 23:17:46 +00004329 if (isa<ParmVarDecl>(D)) {
4330 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_parameter_type)
4331 << Attr.getName() << /*pointer-to-CF*/2
4332 << Attr.getRange();
4333 } else {
4334 // Needs to be kept in sync with warn_ns_attribute_wrong_return_type.
4335 enum : unsigned {
4336 Function,
4337 Method,
4338 Property
4339 } SubjectKind = Function;
4340 if (isa<ObjCMethodDecl>(D))
4341 SubjectKind = Method;
4342 else if (isa<ObjCPropertyDecl>(D))
4343 SubjectKind = Property;
4344 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_return_type)
4345 << Attr.getName() << SubjectKind << cf
4346 << Attr.getRange();
4347 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00004348 return;
Ted Kremenek3b204e42009-05-13 21:07:32 +00004349 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00004350
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004351 switch (Attr.getKind()) {
Ted Kremenek9ecdfaf2009-05-09 02:44:38 +00004352 default:
David Blaikie83d382b2011-09-23 05:06:16 +00004353 llvm_unreachable("invalid ownership attribute");
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004354 case AttributeList::AT_NSReturnsAutoreleased:
Nico Weber462fd1e2015-01-07 23:50:05 +00004355 D->addAttr(::new (S.Context) NSReturnsAutoreleasedAttr(
4356 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
John McCalled433932011-01-25 03:31:58 +00004357 return;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004358 case AttributeList::AT_CFReturnsNotRetained:
Nico Weber462fd1e2015-01-07 23:50:05 +00004359 D->addAttr(::new (S.Context) CFReturnsNotRetainedAttr(
4360 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
Ted Kremenekd9c66632010-02-18 00:05:45 +00004361 return;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004362 case AttributeList::AT_NSReturnsNotRetained:
Nico Weber462fd1e2015-01-07 23:50:05 +00004363 D->addAttr(::new (S.Context) NSReturnsNotRetainedAttr(
4364 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
Ted Kremenekd9c66632010-02-18 00:05:45 +00004365 return;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004366 case AttributeList::AT_CFReturnsRetained:
Nico Weber462fd1e2015-01-07 23:50:05 +00004367 D->addAttr(::new (S.Context) CFReturnsRetainedAttr(
4368 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
Ted Kremenek9ecdfaf2009-05-09 02:44:38 +00004369 return;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004370 case AttributeList::AT_NSReturnsRetained:
Nico Weber462fd1e2015-01-07 23:50:05 +00004371 D->addAttr(::new (S.Context) NSReturnsRetainedAttr(
4372 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
Ted Kremenek9ecdfaf2009-05-09 02:44:38 +00004373 return;
4374 };
4375}
4376
John McCallcf166702011-07-22 08:53:00 +00004377static void handleObjCReturnsInnerPointerAttr(Sema &S, Decl *D,
4378 const AttributeList &attr) {
Fariborz Jahanian8bf05562013-09-19 17:52:50 +00004379 const int EP_ObjCMethod = 1;
4380 const int EP_ObjCProperty = 2;
Fariborz Jahanian5c005832013-09-19 17:18:55 +00004381
John McCallcf166702011-07-22 08:53:00 +00004382 SourceLocation loc = attr.getLoc();
Fariborz Jahanian8a5e9472013-09-19 16:37:20 +00004383 QualType resultType;
Aaron Ballman74eeeae2013-11-27 13:27:02 +00004384 if (isa<ObjCMethodDecl>(D))
Alp Toker314cc812014-01-25 16:55:45 +00004385 resultType = cast<ObjCMethodDecl>(D)->getReturnType();
Fariborz Jahanian8a5e9472013-09-19 16:37:20 +00004386 else
Aaron Ballman74eeeae2013-11-27 13:27:02 +00004387 resultType = cast<ObjCPropertyDecl>(D)->getType();
John McCallcf166702011-07-22 08:53:00 +00004388
Fariborz Jahanian044a5be2011-09-30 20:50:23 +00004389 if (!resultType->isReferenceType() &&
4390 (!resultType->isPointerType() || resultType->isObjCRetainableType())) {
Fariborz Jahanian8a5e9472013-09-19 16:37:20 +00004391 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_return_type)
John McCallcf166702011-07-22 08:53:00 +00004392 << SourceRange(loc)
Aaron Ballman74eeeae2013-11-27 13:27:02 +00004393 << attr.getName()
4394 << (isa<ObjCMethodDecl>(D) ? EP_ObjCMethod : EP_ObjCProperty)
Fariborz Jahanian5c005832013-09-19 17:18:55 +00004395 << /*non-retainable pointer*/ 2;
John McCallcf166702011-07-22 08:53:00 +00004396
4397 // Drop the attribute.
4398 return;
4399 }
4400
Nico Weber462fd1e2015-01-07 23:50:05 +00004401 D->addAttr(::new (S.Context) ObjCReturnsInnerPointerAttr(
4402 attr.getRange(), S.Context, attr.getAttributeSpellingListIndex()));
John McCallcf166702011-07-22 08:53:00 +00004403}
4404
Fariborz Jahanian566fff02012-09-07 23:46:23 +00004405static void handleObjCRequiresSuperAttr(Sema &S, Decl *D,
4406 const AttributeList &attr) {
Aaron Ballman74eeeae2013-11-27 13:27:02 +00004407 ObjCMethodDecl *method = cast<ObjCMethodDecl>(D);
Fariborz Jahanian566fff02012-09-07 23:46:23 +00004408
Fariborz Jahanian566fff02012-09-07 23:46:23 +00004409 DeclContext *DC = method->getDeclContext();
4410 if (const ObjCProtocolDecl *PDecl = dyn_cast_or_null<ObjCProtocolDecl>(DC)) {
4411 S.Diag(D->getLocStart(), diag::warn_objc_requires_super_protocol)
4412 << attr.getName() << 0;
4413 S.Diag(PDecl->getLocation(), diag::note_protocol_decl);
4414 return;
4415 }
4416 if (method->getMethodFamily() == OMF_dealloc) {
4417 S.Diag(D->getLocStart(), diag::warn_objc_requires_super_protocol)
4418 << attr.getName() << 1;
4419 return;
4420 }
4421
Michael Han99315932013-01-24 16:46:58 +00004422 method->addAttr(::new (S.Context)
4423 ObjCRequiresSuperAttr(attr.getRange(), S.Context,
4424 attr.getAttributeSpellingListIndex()));
Fariborz Jahanian566fff02012-09-07 23:46:23 +00004425}
4426
Aaron Ballmanfb763042013-12-02 18:05:46 +00004427static void handleCFAuditedTransferAttr(Sema &S, Decl *D,
4428 const AttributeList &Attr) {
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00004429 if (checkAttrMutualExclusion<CFUnknownTransferAttr>(S, D, Attr.getRange(),
4430 Attr.getName()))
John McCall32f5fe12011-09-30 05:12:12 +00004431 return;
John McCall32f5fe12011-09-30 05:12:12 +00004432
Aaron Ballmanfb763042013-12-02 18:05:46 +00004433 D->addAttr(::new (S.Context)
4434 CFAuditedTransferAttr(Attr.getRange(), S.Context,
4435 Attr.getAttributeSpellingListIndex()));
4436}
4437
4438static void handleCFUnknownTransferAttr(Sema &S, Decl *D,
4439 const AttributeList &Attr) {
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00004440 if (checkAttrMutualExclusion<CFAuditedTransferAttr>(S, D, Attr.getRange(),
4441 Attr.getName()))
Aaron Ballmanfb763042013-12-02 18:05:46 +00004442 return;
4443
4444 D->addAttr(::new (S.Context)
4445 CFUnknownTransferAttr(Attr.getRange(), S.Context,
4446 Attr.getAttributeSpellingListIndex()));
John McCall32f5fe12011-09-30 05:12:12 +00004447}
4448
Fariborz Jahanian0a0a3972013-11-13 23:59:17 +00004449static void handleObjCBridgeAttr(Sema &S, Scope *Sc, Decl *D,
4450 const AttributeList &Attr) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004451 IdentifierLoc * Parm = Attr.isArgIdent(0) ? Attr.getArgAsIdent(0) : nullptr;
Ted Kremenek2d3379e2013-11-21 07:20:34 +00004452
Fariborz Jahanian0a0a3972013-11-13 23:59:17 +00004453 if (!Parm) {
Ted Kremenek2d3379e2013-11-21 07:20:34 +00004454 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
Fariborz Jahanian0a0a3972013-11-13 23:59:17 +00004455 return;
4456 }
John McCall28592582015-02-01 22:34:06 +00004457
4458 // Typedefs only allow objc_bridge(id) and have some additional checking.
4459 if (auto TD = dyn_cast<TypedefNameDecl>(D)) {
4460 if (!Parm->Ident->isStr("id")) {
4461 S.Diag(Attr.getLoc(), diag::err_objc_attr_typedef_not_id)
4462 << Attr.getName();
4463 return;
4464 }
4465
4466 // Only allow 'cv void *'.
4467 QualType T = TD->getUnderlyingType();
4468 if (!T->isVoidPointerType()) {
4469 S.Diag(Attr.getLoc(), diag::err_objc_attr_typedef_not_void_pointer);
4470 return;
4471 }
4472 }
Fariborz Jahanian0a0a3972013-11-13 23:59:17 +00004473
4474 D->addAttr(::new (S.Context)
Ted Kremenek2d3379e2013-11-21 07:20:34 +00004475 ObjCBridgeAttr(Attr.getRange(), S.Context, Parm->Ident,
Fariborz Jahanian0a0a3972013-11-13 23:59:17 +00004476 Attr.getAttributeSpellingListIndex()));
4477}
4478
Fariborz Jahanian87c77912013-11-21 20:50:32 +00004479static void handleObjCBridgeMutableAttr(Sema &S, Scope *Sc, Decl *D,
4480 const AttributeList &Attr) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004481 IdentifierLoc * Parm = Attr.isArgIdent(0) ? Attr.getArgAsIdent(0) : nullptr;
4482
Fariborz Jahanian87c77912013-11-21 20:50:32 +00004483 if (!Parm) {
4484 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
4485 return;
4486 }
4487
4488 D->addAttr(::new (S.Context)
4489 ObjCBridgeMutableAttr(Attr.getRange(), S.Context, Parm->Ident,
4490 Attr.getAttributeSpellingListIndex()));
4491}
4492
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00004493static void handleObjCBridgeRelatedAttr(Sema &S, Scope *Sc, Decl *D,
4494 const AttributeList &Attr) {
4495 IdentifierInfo *RelatedClass =
Craig Topperc3ec1492014-05-26 06:22:03 +00004496 Attr.isArgIdent(0) ? Attr.getArgAsIdent(0)->Ident : nullptr;
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00004497 if (!RelatedClass) {
4498 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
4499 return;
4500 }
4501 IdentifierInfo *ClassMethod =
Craig Topperc3ec1492014-05-26 06:22:03 +00004502 Attr.getArgAsIdent(1) ? Attr.getArgAsIdent(1)->Ident : nullptr;
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00004503 IdentifierInfo *InstanceMethod =
Craig Topperc3ec1492014-05-26 06:22:03 +00004504 Attr.getArgAsIdent(2) ? Attr.getArgAsIdent(2)->Ident : nullptr;
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00004505 D->addAttr(::new (S.Context)
4506 ObjCBridgeRelatedAttr(Attr.getRange(), S.Context, RelatedClass,
4507 ClassMethod, InstanceMethod,
4508 Attr.getAttributeSpellingListIndex()));
4509}
4510
Argyrios Kyrtzidisd1438b42013-12-03 21:11:25 +00004511static void handleObjCDesignatedInitializer(Sema &S, Decl *D,
4512 const AttributeList &Attr) {
Fariborz Jahanian6efab6e2014-03-14 18:19:46 +00004513 ObjCInterfaceDecl *IFace;
Nico Weber462fd1e2015-01-07 23:50:05 +00004514 if (ObjCCategoryDecl *CatDecl =
4515 dyn_cast<ObjCCategoryDecl>(D->getDeclContext()))
Fariborz Jahanian6efab6e2014-03-14 18:19:46 +00004516 IFace = CatDecl->getClassInterface();
4517 else
4518 IFace = cast<ObjCInterfaceDecl>(D->getDeclContext());
Ben Langmuirc91ac9e2015-01-20 20:41:36 +00004519
4520 if (!IFace)
4521 return;
4522
Argyrios Kyrtzidis9ed9e5f2013-12-03 21:11:30 +00004523 IFace->setHasDesignatedInitializers();
Argyrios Kyrtzidise8186812013-12-07 06:08:04 +00004524 D->addAttr(::new (S.Context)
Argyrios Kyrtzidisd1438b42013-12-03 21:11:25 +00004525 ObjCDesignatedInitializerAttr(Attr.getRange(), S.Context,
4526 Attr.getAttributeSpellingListIndex()));
4527}
4528
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00004529static void handleObjCRuntimeName(Sema &S, Decl *D,
4530 const AttributeList &Attr) {
Fariborz Jahaniana2e5deb2014-07-16 19:44:34 +00004531 StringRef MetaDataName;
4532 if (!S.checkStringLiteralArgumentAttr(Attr, 0, MetaDataName))
4533 return;
4534 D->addAttr(::new (S.Context)
4535 ObjCRuntimeNameAttr(Attr.getRange(), S.Context,
4536 MetaDataName,
4537 Attr.getAttributeSpellingListIndex()));
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00004538}
4539
Nico Webera6916892016-06-10 18:53:04 +00004540// When a user wants to use objc_boxable with a union or struct
4541// but they don't have access to the declaration (legacy/third-party code)
4542// then they can 'enable' this feature with a typedef:
Alex Denisovfde64952015-06-26 05:28:36 +00004543// typedef struct __attribute((objc_boxable)) legacy_struct legacy_struct;
4544static void handleObjCBoxable(Sema &S, Decl *D, const AttributeList &Attr) {
4545 bool notify = false;
4546
4547 RecordDecl *RD = dyn_cast<RecordDecl>(D);
4548 if (RD && RD->getDefinition()) {
4549 RD = RD->getDefinition();
4550 notify = true;
4551 }
4552
4553 if (RD) {
4554 ObjCBoxableAttr *BoxableAttr = ::new (S.Context)
4555 ObjCBoxableAttr(Attr.getRange(), S.Context,
4556 Attr.getAttributeSpellingListIndex());
4557 RD->addAttr(BoxableAttr);
4558 if (notify) {
4559 // we need to notify ASTReader/ASTWriter about
4560 // modification of existing declaration
4561 if (ASTMutationListener *L = S.getASTMutationListener())
4562 L->AddedAttributeToRecord(BoxableAttr, RD);
4563 }
4564 }
4565}
4566
Chandler Carruthedc2c642011-07-02 00:01:44 +00004567static void handleObjCOwnershipAttr(Sema &S, Decl *D,
4568 const AttributeList &Attr) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004569 if (hasDeclarator(D)) return;
John McCall31168b02011-06-15 23:02:42 +00004570
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004571 S.Diag(D->getLocStart(), diag::err_attribute_wrong_decl_type)
Douglas Gregor5c3cc422012-03-14 16:55:17 +00004572 << Attr.getRange() << Attr.getName() << ExpectedVariable;
John McCall31168b02011-06-15 23:02:42 +00004573}
4574
Chandler Carruthedc2c642011-07-02 00:01:44 +00004575static void handleObjCPreciseLifetimeAttr(Sema &S, Decl *D,
4576 const AttributeList &Attr) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004577 ValueDecl *vd = cast<ValueDecl>(D);
John McCall31168b02011-06-15 23:02:42 +00004578 QualType type = vd->getType();
4579
4580 if (!type->isDependentType() &&
4581 !type->isObjCLifetimeType()) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004582 S.Diag(Attr.getLoc(), diag::err_objc_precise_lifetime_bad_type)
John McCall31168b02011-06-15 23:02:42 +00004583 << type;
4584 return;
4585 }
4586
4587 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
4588
4589 // If we have no lifetime yet, check the lifetime we're presumably
4590 // going to infer.
4591 if (lifetime == Qualifiers::OCL_None && !type->isDependentType())
4592 lifetime = type->getObjCARCImplicitLifetime();
4593
4594 switch (lifetime) {
4595 case Qualifiers::OCL_None:
4596 assert(type->isDependentType() &&
4597 "didn't infer lifetime for non-dependent type?");
4598 break;
4599
4600 case Qualifiers::OCL_Weak: // meaningful
4601 case Qualifiers::OCL_Strong: // meaningful
4602 break;
4603
4604 case Qualifiers::OCL_ExplicitNone:
4605 case Qualifiers::OCL_Autoreleasing:
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004606 S.Diag(Attr.getLoc(), diag::warn_objc_precise_lifetime_meaningless)
John McCall31168b02011-06-15 23:02:42 +00004607 << (lifetime == Qualifiers::OCL_Autoreleasing);
4608 break;
4609 }
4610
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004611 D->addAttr(::new (S.Context)
Michael Han99315932013-01-24 16:46:58 +00004612 ObjCPreciseLifetimeAttr(Attr.getRange(), S.Context,
4613 Attr.getAttributeSpellingListIndex()));
John McCall31168b02011-06-15 23:02:42 +00004614}
4615
Francois Picheta83957a2010-12-19 06:50:37 +00004616//===----------------------------------------------------------------------===//
4617// Microsoft specific attribute handlers.
4618//===----------------------------------------------------------------------===//
4619
Nico Weber88f5ed92016-09-13 18:55:26 +00004620UuidAttr *Sema::mergeUuidAttr(Decl *D, SourceRange Range,
4621 unsigned AttrSpellingListIndex, StringRef Uuid) {
4622 if (const auto *UA = D->getAttr<UuidAttr>()) {
Nico Weberd58c2602016-09-14 01:16:54 +00004623 if (UA->getGuid().equals_lower(Uuid))
Nico Weber88f5ed92016-09-13 18:55:26 +00004624 return nullptr;
4625 Diag(UA->getLocation(), diag::err_mismatched_uuid);
4626 Diag(Range.getBegin(), diag::note_previous_uuid);
4627 D->dropAttr<UuidAttr>();
4628 }
4629
4630 return ::new (Context) UuidAttr(Range, Context, Uuid, AttrSpellingListIndex);
4631}
4632
Chandler Carruthedc2c642011-07-02 00:01:44 +00004633static void handleUuidAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballmandf8fe4c2013-11-24 21:35:16 +00004634 if (!S.LangOpts.CPlusPlus) {
4635 S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang)
4636 << Attr.getName() << AttributeLangSupport::C;
4637 return;
4638 }
4639
Aaron Ballman60e705e2013-11-24 20:58:02 +00004640 if (!isa<CXXRecordDecl>(D)) {
4641 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
4642 << Attr.getName() << ExpectedClass;
4643 return;
4644 }
4645
Benjamin Kramer6ee15622013-09-13 15:35:43 +00004646 StringRef StrRef;
4647 SourceLocation LiteralLoc;
Tim Northover6a6b63b2013-10-01 14:34:18 +00004648 if (!S.checkStringLiteralArgumentAttr(Attr, 0, StrRef, &LiteralLoc))
Reid Kleckner140c4a72013-05-17 14:04:52 +00004649 return;
Francois Pichet7da11662010-12-20 01:41:49 +00004650
David Majnemer89085342013-08-09 08:56:20 +00004651 // GUID format is "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" or
4652 // "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}", normalize to the former.
David Majnemer89085342013-08-09 08:56:20 +00004653 if (StrRef.size() == 38 && StrRef.front() == '{' && StrRef.back() == '}')
4654 StrRef = StrRef.drop_front().drop_back();
Francois Pichet7da11662010-12-20 01:41:49 +00004655
Reid Kleckner140c4a72013-05-17 14:04:52 +00004656 // Validate GUID length.
David Majnemer89085342013-08-09 08:56:20 +00004657 if (StrRef.size() != 36) {
Benjamin Kramer6ee15622013-09-13 15:35:43 +00004658 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
Reid Kleckner140c4a72013-05-17 14:04:52 +00004659 return;
4660 }
Anders Carlsson19588aa2011-01-23 21:07:30 +00004661
David Majnemer89085342013-08-09 08:56:20 +00004662 for (unsigned i = 0; i < 36; ++i) {
Reid Kleckner140c4a72013-05-17 14:04:52 +00004663 if (i == 8 || i == 13 || i == 18 || i == 23) {
David Majnemer89085342013-08-09 08:56:20 +00004664 if (StrRef[i] != '-') {
Benjamin Kramer6ee15622013-09-13 15:35:43 +00004665 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
Francois Pichet7da11662010-12-20 01:41:49 +00004666 return;
4667 }
David Majnemer89085342013-08-09 08:56:20 +00004668 } else if (!isHexDigit(StrRef[i])) {
Benjamin Kramer6ee15622013-09-13 15:35:43 +00004669 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
Reid Kleckner140c4a72013-05-17 14:04:52 +00004670 return;
Francois Pichet7da11662010-12-20 01:41:49 +00004671 }
Reid Kleckner140c4a72013-05-17 14:04:52 +00004672 }
Francois Picheta83957a2010-12-19 06:50:37 +00004673
Nico Weber88f5ed92016-09-13 18:55:26 +00004674 UuidAttr *UA = S.mergeUuidAttr(D, Attr.getRange(),
4675 Attr.getAttributeSpellingListIndex(), StrRef);
4676 if (UA)
4677 D->addAttr(UA);
Charles Davis163855f2010-02-16 18:27:26 +00004678}
4679
David Majnemer2c4e00a2014-01-29 22:07:36 +00004680static void handleMSInheritanceAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4681 if (!S.LangOpts.CPlusPlus) {
4682 S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang)
4683 << Attr.getName() << AttributeLangSupport::C;
4684 return;
4685 }
4686 MSInheritanceAttr *IA = S.mergeMSInheritanceAttr(
David Majnemer4bb09802014-02-10 19:50:15 +00004687 D, Attr.getRange(), /*BestCase=*/true,
4688 Attr.getAttributeSpellingListIndex(),
David Majnemer2c4e00a2014-01-29 22:07:36 +00004689 (MSInheritanceAttr::Spelling)Attr.getSemanticSpelling());
David Majnemer929025d2016-01-26 19:30:26 +00004690 if (IA) {
David Majnemer2c4e00a2014-01-29 22:07:36 +00004691 D->addAttr(IA);
David Majnemer929025d2016-01-26 19:30:26 +00004692 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
4693 }
David Majnemer2c4e00a2014-01-29 22:07:36 +00004694}
4695
Reid Kleckner7d6d2702014-05-01 03:16:47 +00004696static void handleDeclspecThreadAttr(Sema &S, Decl *D,
4697 const AttributeList &Attr) {
4698 VarDecl *VD = cast<VarDecl>(D);
4699 if (!S.Context.getTargetInfo().isTLSSupported()) {
4700 S.Diag(Attr.getLoc(), diag::err_thread_unsupported);
4701 return;
4702 }
4703 if (VD->getTSCSpec() != TSCS_unspecified) {
4704 S.Diag(Attr.getLoc(), diag::err_declspec_thread_on_thread_variable);
4705 return;
4706 }
4707 if (VD->hasLocalStorage()) {
4708 S.Diag(Attr.getLoc(), diag::err_thread_non_global) << "__declspec(thread)";
4709 return;
4710 }
4711 VD->addAttr(::new (S.Context) ThreadAttr(
4712 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4713}
4714
Dmitry Polukhinbf17ecf2016-03-09 15:30:53 +00004715static void handleAbiTagAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4716 SmallVector<StringRef, 4> Tags;
4717 for (unsigned I = 0, E = Attr.getNumArgs(); I != E; ++I) {
4718 StringRef Tag;
4719 if (!S.checkStringLiteralArgumentAttr(Attr, I, Tag))
4720 return;
4721 Tags.push_back(Tag);
4722 }
4723
4724 if (const auto *NS = dyn_cast<NamespaceDecl>(D)) {
4725 if (!NS->isInline()) {
4726 S.Diag(Attr.getLoc(), diag::warn_attr_abi_tag_namespace) << 0;
4727 return;
4728 }
4729 if (NS->isAnonymousNamespace()) {
4730 S.Diag(Attr.getLoc(), diag::warn_attr_abi_tag_namespace) << 1;
4731 return;
4732 }
4733 if (Attr.getNumArgs() == 0)
4734 Tags.push_back(NS->getName());
4735 } else if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
4736 return;
4737
4738 // Store tags sorted and without duplicates.
4739 std::sort(Tags.begin(), Tags.end());
4740 Tags.erase(std::unique(Tags.begin(), Tags.end()), Tags.end());
4741
4742 D->addAttr(::new (S.Context)
4743 AbiTagAttr(Attr.getRange(), S.Context, Tags.data(), Tags.size(),
4744 Attr.getAttributeSpellingListIndex()));
Dmitry Polukhinbf17ecf2016-03-09 15:30:53 +00004745}
4746
Aaron Ballmanab7691c2014-01-09 22:48:32 +00004747static void handleARMInterruptAttr(Sema &S, Decl *D,
4748 const AttributeList &Attr) {
4749 // Check the attribute arguments.
4750 if (Attr.getNumArgs() > 1) {
4751 S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments)
4752 << Attr.getName() << 1;
4753 return;
4754 }
4755
4756 StringRef Str;
4757 SourceLocation ArgLoc;
4758
4759 if (Attr.getNumArgs() == 0)
4760 Str = "";
4761 else if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &ArgLoc))
4762 return;
4763
4764 ARMInterruptAttr::InterruptType Kind;
4765 if (!ARMInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
4766 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
4767 << Attr.getName() << Str << ArgLoc;
4768 return;
4769 }
4770
4771 unsigned Index = Attr.getAttributeSpellingListIndex();
4772 D->addAttr(::new (S.Context)
4773 ARMInterruptAttr(Attr.getLoc(), S.Context, Kind, Index));
4774}
4775
4776static void handleMSP430InterruptAttr(Sema &S, Decl *D,
4777 const AttributeList &Attr) {
4778 if (!checkAttributeNumArgs(S, Attr, 1))
4779 return;
4780
4781 if (!Attr.isArgExpr(0)) {
4782 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << Attr.getName()
4783 << AANT_ArgumentIntegerConstant;
4784 return;
4785 }
4786
4787 // FIXME: Check for decl - it should be void ()(void).
4788
4789 Expr *NumParamsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
4790 llvm::APSInt NumParams(32);
4791 if (!NumParamsExpr->isIntegerConstantExpr(NumParams, S.Context)) {
4792 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
4793 << Attr.getName() << AANT_ArgumentIntegerConstant
4794 << NumParamsExpr->getSourceRange();
4795 return;
4796 }
4797
4798 unsigned Num = NumParams.getLimitedValue(255);
4799 if ((Num & 1) || Num > 30) {
4800 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
4801 << Attr.getName() << (int)NumParams.getSExtValue()
4802 << NumParamsExpr->getSourceRange();
4803 return;
4804 }
4805
Aaron Ballman36a53502014-01-16 13:03:14 +00004806 D->addAttr(::new (S.Context)
4807 MSP430InterruptAttr(Attr.getLoc(), S.Context, Num,
4808 Attr.getAttributeSpellingListIndex()));
4809 D->addAttr(UsedAttr::CreateImplicit(S.Context));
Aaron Ballmanab7691c2014-01-09 22:48:32 +00004810}
4811
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00004812static void handleMipsInterruptAttr(Sema &S, Decl *D,
4813 const AttributeList &Attr) {
4814 // Only one optional argument permitted.
4815 if (Attr.getNumArgs() > 1) {
4816 S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments)
4817 << Attr.getName() << 1;
4818 return;
4819 }
4820
4821 StringRef Str;
4822 SourceLocation ArgLoc;
4823
4824 if (Attr.getNumArgs() == 0)
4825 Str = "";
4826 else if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &ArgLoc))
4827 return;
4828
4829 // Semantic checks for a function with the 'interrupt' attribute for MIPS:
4830 // a) Must be a function.
4831 // b) Must have no parameters.
4832 // c) Must have the 'void' return type.
4833 // d) Cannot have the 'mips16' attribute, as that instruction set
4834 // lacks the 'eret' instruction.
4835 // e) The attribute itself must either have no argument or one of the
4836 // valid interrupt types, see [MipsInterruptDocs].
4837
4838 if (!isFunctionOrMethod(D)) {
4839 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
4840 << "'interrupt'" << ExpectedFunctionOrMethod;
4841 return;
4842 }
4843
4844 if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) {
4845 S.Diag(D->getLocation(), diag::warn_mips_interrupt_attribute)
4846 << 0;
4847 return;
4848 }
4849
4850 if (!getFunctionOrMethodResultType(D)->isVoidType()) {
4851 S.Diag(D->getLocation(), diag::warn_mips_interrupt_attribute)
4852 << 1;
4853 return;
4854 }
4855
4856 if (checkAttrMutualExclusion<Mips16Attr>(S, D, Attr.getRange(),
4857 Attr.getName()))
4858 return;
4859
4860 MipsInterruptAttr::InterruptType Kind;
4861 if (!MipsInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
4862 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
4863 << Attr.getName() << "'" + std::string(Str) + "'";
4864 return;
4865 }
4866
4867 D->addAttr(::new (S.Context) MipsInterruptAttr(
4868 Attr.getLoc(), S.Context, Kind, Attr.getAttributeSpellingListIndex()));
4869}
4870
Alexey Bataevd51e9932016-01-15 04:06:31 +00004871static void handleAnyX86InterruptAttr(Sema &S, Decl *D,
4872 const AttributeList &Attr) {
4873 // Semantic checks for a function with the 'interrupt' attribute.
4874 // a) Must be a function.
4875 // b) Must have the 'void' return type.
4876 // c) Must take 1 or 2 arguments.
4877 // d) The 1st argument must be a pointer.
4878 // e) The 2nd argument (if any) must be an unsigned integer.
4879 if (!isFunctionOrMethod(D) || !hasFunctionProto(D) || isInstanceMethod(D) ||
4880 CXXMethodDecl::isStaticOverloadedOperator(
4881 cast<NamedDecl>(D)->getDeclName().getCXXOverloadedOperator())) {
4882 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
4883 << Attr.getName() << ExpectedFunctionWithProtoType;
4884 return;
4885 }
4886 // Interrupt handler must have void return type.
4887 if (!getFunctionOrMethodResultType(D)->isVoidType()) {
4888 S.Diag(getFunctionOrMethodResultSourceRange(D).getBegin(),
4889 diag::err_anyx86_interrupt_attribute)
4890 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
4891 ? 0
4892 : 1)
4893 << 0;
4894 return;
4895 }
4896 // Interrupt handler must have 1 or 2 parameters.
4897 unsigned NumParams = getFunctionOrMethodNumParams(D);
4898 if (NumParams < 1 || NumParams > 2) {
4899 S.Diag(D->getLocStart(), diag::err_anyx86_interrupt_attribute)
4900 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
4901 ? 0
4902 : 1)
4903 << 1;
4904 return;
4905 }
4906 // The first argument must be a pointer.
4907 if (!getFunctionOrMethodParamType(D, 0)->isPointerType()) {
4908 S.Diag(getFunctionOrMethodParamRange(D, 0).getBegin(),
4909 diag::err_anyx86_interrupt_attribute)
4910 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
4911 ? 0
4912 : 1)
4913 << 2;
4914 return;
4915 }
4916 // The second argument, if present, must be an unsigned integer.
4917 unsigned TypeSize =
4918 S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64
4919 ? 64
4920 : 32;
4921 if (NumParams == 2 &&
4922 (!getFunctionOrMethodParamType(D, 1)->isUnsignedIntegerType() ||
4923 S.Context.getTypeSize(getFunctionOrMethodParamType(D, 1)) != TypeSize)) {
4924 S.Diag(getFunctionOrMethodParamRange(D, 1).getBegin(),
4925 diag::err_anyx86_interrupt_attribute)
4926 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
4927 ? 0
4928 : 1)
4929 << 3 << S.Context.getIntTypeForBitwidth(TypeSize, /*Signed=*/false);
4930 return;
4931 }
4932 D->addAttr(::new (S.Context) AnyX86InterruptAttr(
4933 Attr.getLoc(), S.Context, Attr.getAttributeSpellingListIndex()));
4934 D->addAttr(UsedAttr::CreateImplicit(S.Context));
4935}
4936
Aaron Ballmanab7691c2014-01-09 22:48:32 +00004937static void handleInterruptAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4938 // Dispatch the interrupt attribute based on the current target.
Alexey Bataevd51e9932016-01-15 04:06:31 +00004939 switch (S.Context.getTargetInfo().getTriple().getArch()) {
4940 case llvm::Triple::msp430:
Aaron Ballmanab7691c2014-01-09 22:48:32 +00004941 handleMSP430InterruptAttr(S, D, Attr);
Alexey Bataevd51e9932016-01-15 04:06:31 +00004942 break;
4943 case llvm::Triple::mipsel:
4944 case llvm::Triple::mips:
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00004945 handleMipsInterruptAttr(S, D, Attr);
Alexey Bataevd51e9932016-01-15 04:06:31 +00004946 break;
4947 case llvm::Triple::x86:
4948 case llvm::Triple::x86_64:
4949 handleAnyX86InterruptAttr(S, D, Attr);
4950 break;
4951 default:
Aaron Ballmanab7691c2014-01-09 22:48:32 +00004952 handleARMInterruptAttr(S, D, Attr);
Alexey Bataevd51e9932016-01-15 04:06:31 +00004953 break;
4954 }
Aaron Ballmanab7691c2014-01-09 22:48:32 +00004955}
4956
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00004957static void handleAMDGPUFlatWorkGroupSizeAttr(Sema &S, Decl *D,
4958 const AttributeList &Attr) {
4959 uint32_t Min = 0;
4960 Expr *MinExpr = Attr.getArgAsExpr(0);
4961 if (!checkUInt32Argument(S, Attr, MinExpr, Min))
Matt Arsenault43fae6c2014-12-04 20:38:18 +00004962 return;
4963
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00004964 uint32_t Max = 0;
4965 Expr *MaxExpr = Attr.getArgAsExpr(1);
4966 if (!checkUInt32Argument(S, Attr, MaxExpr, Max))
4967 return;
4968
4969 if (Min == 0 && Max != 0) {
4970 S.Diag(Attr.getLoc(), diag::err_attribute_argument_invalid)
4971 << Attr.getName() << 0;
4972 return;
4973 }
4974 if (Min > Max) {
4975 S.Diag(Attr.getLoc(), diag::err_attribute_argument_invalid)
4976 << Attr.getName() << 1;
4977 return;
4978 }
4979
Matt Arsenault43fae6c2014-12-04 20:38:18 +00004980 D->addAttr(::new (S.Context)
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00004981 AMDGPUFlatWorkGroupSizeAttr(Attr.getLoc(), S.Context, Min, Max,
4982 Attr.getAttributeSpellingListIndex()));
4983}
4984
4985static void handleAMDGPUWavesPerEUAttr(Sema &S, Decl *D,
4986 const AttributeList &Attr) {
4987 uint32_t Min = 0;
4988 Expr *MinExpr = Attr.getArgAsExpr(0);
4989 if (!checkUInt32Argument(S, Attr, MinExpr, Min))
4990 return;
4991
4992 uint32_t Max = 0;
4993 if (Attr.getNumArgs() == 2) {
4994 Expr *MaxExpr = Attr.getArgAsExpr(1);
4995 if (!checkUInt32Argument(S, Attr, MaxExpr, Max))
4996 return;
4997 }
4998
4999 if (Min == 0 && Max != 0) {
5000 S.Diag(Attr.getLoc(), diag::err_attribute_argument_invalid)
5001 << Attr.getName() << 0;
5002 return;
5003 }
5004 if (Max != 0 && Min > Max) {
5005 S.Diag(Attr.getLoc(), diag::err_attribute_argument_invalid)
5006 << Attr.getName() << 1;
5007 return;
5008 }
5009
5010 D->addAttr(::new (S.Context)
5011 AMDGPUWavesPerEUAttr(Attr.getLoc(), S.Context, Min, Max,
5012 Attr.getAttributeSpellingListIndex()));
Matt Arsenault43fae6c2014-12-04 20:38:18 +00005013}
5014
5015static void handleAMDGPUNumSGPRAttr(Sema &S, Decl *D,
5016 const AttributeList &Attr) {
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00005017 uint32_t NumSGPR = 0;
5018 Expr *NumSGPRExpr = Attr.getArgAsExpr(0);
5019 if (!checkUInt32Argument(S, Attr, NumSGPRExpr, NumSGPR))
Matt Arsenault43fae6c2014-12-04 20:38:18 +00005020 return;
5021
5022 D->addAttr(::new (S.Context)
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00005023 AMDGPUNumSGPRAttr(Attr.getLoc(), S.Context, NumSGPR,
5024 Attr.getAttributeSpellingListIndex()));
5025}
5026
5027static void handleAMDGPUNumVGPRAttr(Sema &S, Decl *D,
5028 const AttributeList &Attr) {
5029 uint32_t NumVGPR = 0;
5030 Expr *NumVGPRExpr = Attr.getArgAsExpr(0);
5031 if (!checkUInt32Argument(S, Attr, NumVGPRExpr, NumVGPR))
5032 return;
5033
5034 D->addAttr(::new (S.Context)
5035 AMDGPUNumVGPRAttr(Attr.getLoc(), S.Context, NumVGPR,
Matt Arsenault43fae6c2014-12-04 20:38:18 +00005036 Attr.getAttributeSpellingListIndex()));
5037}
5038
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005039static void handleX86ForceAlignArgPointerAttr(Sema &S, Decl *D,
5040 const AttributeList& Attr) {
5041 // If we try to apply it to a function pointer, don't warn, but don't
5042 // do anything, either. It doesn't matter anyway, because there's nothing
5043 // special about calling a force_align_arg_pointer function.
5044 ValueDecl *VD = dyn_cast<ValueDecl>(D);
5045 if (VD && VD->getType()->isFunctionPointerType())
5046 return;
5047 // Also don't warn on function pointer typedefs.
5048 TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D);
5049 if (TD && (TD->getUnderlyingType()->isFunctionPointerType() ||
5050 TD->getUnderlyingType()->isFunctionType()))
5051 return;
5052 // Attribute can only be applied to function types.
5053 if (!isa<FunctionDecl>(D)) {
5054 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
5055 << Attr.getName() << /* function */0;
5056 return;
5057 }
5058
Aaron Ballman36a53502014-01-16 13:03:14 +00005059 D->addAttr(::new (S.Context)
5060 X86ForceAlignArgPointerAttr(Attr.getRange(), S.Context,
5061 Attr.getAttributeSpellingListIndex()));
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005062}
5063
David Majnemercd3ebfe2016-05-23 17:16:12 +00005064static void handleLayoutVersion(Sema &S, Decl *D, const AttributeList &Attr) {
5065 uint32_t Version;
5066 Expr *VersionExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
5067 if (!checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), Version))
5068 return;
5069
5070 // TODO: Investigate what happens with the next major version of MSVC.
5071 if (Version != LangOptions::MSVC2015) {
5072 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
5073 << Attr.getName() << Version << VersionExpr->getSourceRange();
5074 return;
5075 }
5076
5077 D->addAttr(::new (S.Context)
5078 LayoutVersionAttr(Attr.getRange(), S.Context, Version,
5079 Attr.getAttributeSpellingListIndex()));
5080}
5081
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005082DLLImportAttr *Sema::mergeDLLImportAttr(Decl *D, SourceRange Range,
5083 unsigned AttrSpellingListIndex) {
5084 if (D->hasAttr<DLLExportAttr>()) {
Nico Rieck60478662014-02-22 19:47:30 +00005085 Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'dllimport'";
Craig Topperc3ec1492014-05-26 06:22:03 +00005086 return nullptr;
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005087 }
5088
5089 if (D->hasAttr<DLLImportAttr>())
Craig Topperc3ec1492014-05-26 06:22:03 +00005090 return nullptr;
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005091
Aaron Ballman3f5f3e72014-01-20 16:15:55 +00005092 return ::new (Context) DLLImportAttr(Range, Context, AttrSpellingListIndex);
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005093}
5094
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005095DLLExportAttr *Sema::mergeDLLExportAttr(Decl *D, SourceRange Range,
5096 unsigned AttrSpellingListIndex) {
5097 if (DLLImportAttr *Import = D->getAttr<DLLImportAttr>()) {
Nico Rieck60478662014-02-22 19:47:30 +00005098 Diag(Import->getLocation(), diag::warn_attribute_ignored) << Import;
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005099 D->dropAttr<DLLImportAttr>();
5100 }
5101
5102 if (D->hasAttr<DLLExportAttr>())
Craig Topperc3ec1492014-05-26 06:22:03 +00005103 return nullptr;
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005104
Aaron Ballman3f5f3e72014-01-20 16:15:55 +00005105 return ::new (Context) DLLExportAttr(Range, Context, AttrSpellingListIndex);
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005106}
5107
Hans Wennborge82f19c2014-06-24 23:57:05 +00005108static void handleDLLAttr(Sema &S, Decl *D, const AttributeList &A) {
Hans Wennborg5e645282014-06-24 23:57:13 +00005109 if (isa<ClassTemplatePartialSpecializationDecl>(D) &&
5110 S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5111 S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored)
5112 << A.getName();
5113 return;
5114 }
5115
Hans Wennborg606bd6d2014-11-03 14:24:45 +00005116 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5117 if (FD->isInlined() && A.getKind() == AttributeList::AT_DLLImport &&
5118 !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5119 // MinGW doesn't allow dllimport on inline functions.
5120 S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored_on_inline)
5121 << A.getName();
5122 return;
5123 }
5124 }
5125
Hans Wennborg5869ec42015-09-15 21:05:30 +00005126 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
5127 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5128 MD->getParent()->isLambda()) {
5129 S.Diag(A.getRange().getBegin(), diag::err_attribute_dll_lambda) << A.getName();
5130 return;
5131 }
5132 }
5133
Hans Wennborge82f19c2014-06-24 23:57:05 +00005134 unsigned Index = A.getAttributeSpellingListIndex();
5135 Attr *NewAttr = A.getKind() == AttributeList::AT_DLLExport
5136 ? (Attr *)S.mergeDLLExportAttr(D, A.getRange(), Index)
5137 : (Attr *)S.mergeDLLImportAttr(D, A.getRange(), Index);
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005138 if (NewAttr)
5139 D->addAttr(NewAttr);
5140}
5141
David Majnemer2c4e00a2014-01-29 22:07:36 +00005142MSInheritanceAttr *
David Majnemer4bb09802014-02-10 19:50:15 +00005143Sema::mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase,
David Majnemer2c4e00a2014-01-29 22:07:36 +00005144 unsigned AttrSpellingListIndex,
5145 MSInheritanceAttr::Spelling SemanticSpelling) {
5146 if (MSInheritanceAttr *IA = D->getAttr<MSInheritanceAttr>()) {
5147 if (IA->getSemanticSpelling() == SemanticSpelling)
Craig Topperc3ec1492014-05-26 06:22:03 +00005148 return nullptr;
David Majnemer2c4e00a2014-01-29 22:07:36 +00005149 Diag(IA->getLocation(), diag::err_mismatched_ms_inheritance)
5150 << 1 /*previous declaration*/;
5151 Diag(Range.getBegin(), diag::note_previous_ms_inheritance);
5152 D->dropAttr<MSInheritanceAttr>();
5153 }
5154
5155 CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
5156 if (RD->hasDefinition()) {
David Majnemer4bb09802014-02-10 19:50:15 +00005157 if (checkMSInheritanceAttrOnDefinition(RD, Range, BestCase,
5158 SemanticSpelling)) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005159 return nullptr;
David Majnemer2c4e00a2014-01-29 22:07:36 +00005160 }
5161 } else {
5162 if (isa<ClassTemplatePartialSpecializationDecl>(RD)) {
5163 Diag(Range.getBegin(), diag::warn_ignored_ms_inheritance)
5164 << 1 /*partial specialization*/;
Craig Topperc3ec1492014-05-26 06:22:03 +00005165 return nullptr;
David Majnemer2c4e00a2014-01-29 22:07:36 +00005166 }
5167 if (RD->getDescribedClassTemplate()) {
5168 Diag(Range.getBegin(), diag::warn_ignored_ms_inheritance)
5169 << 0 /*primary template*/;
Craig Topperc3ec1492014-05-26 06:22:03 +00005170 return nullptr;
David Majnemer2c4e00a2014-01-29 22:07:36 +00005171 }
5172 }
5173
5174 return ::new (Context)
David Majnemer4bb09802014-02-10 19:50:15 +00005175 MSInheritanceAttr(Range, Context, BestCase, AttrSpellingListIndex);
David Majnemer2c4e00a2014-01-29 22:07:36 +00005176}
5177
Aaron Ballmanefe348e2014-02-18 17:36:50 +00005178static void handleCapabilityAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5179 // The capability attributes take a single string parameter for the name of
5180 // the capability they represent. The lockable attribute does not take any
5181 // parameters. However, semantically, both attributes represent the same
5182 // concept, and so they use the same semantic attribute. Eventually, the
5183 // lockable attribute will be removed.
Aaron Ballman6c810072014-03-05 21:47:13 +00005184 //
Alp Toker958027b2014-07-14 19:42:55 +00005185 // For backward compatibility, any capability which has no specified string
Aaron Ballman6c810072014-03-05 21:47:13 +00005186 // literal will be considered a "mutex."
5187 StringRef N("mutex");
Aaron Ballmanefe348e2014-02-18 17:36:50 +00005188 SourceLocation LiteralLoc;
5189 if (Attr.getKind() == AttributeList::AT_Capability &&
5190 !S.checkStringLiteralArgumentAttr(Attr, 0, N, &LiteralLoc))
5191 return;
5192
Aaron Ballman6c810072014-03-05 21:47:13 +00005193 // Currently, there are only two names allowed for a capability: role and
5194 // mutex (case insensitive). Diagnose other capability names.
5195 if (!N.equals_lower("mutex") && !N.equals_lower("role"))
5196 S.Diag(LiteralLoc, diag::warn_invalid_capability_name) << N;
5197
Aaron Ballmanefe348e2014-02-18 17:36:50 +00005198 D->addAttr(::new (S.Context) CapabilityAttr(Attr.getRange(), S.Context, N,
5199 Attr.getAttributeSpellingListIndex()));
5200}
5201
Aaron Ballman9e9d1842014-02-21 21:05:14 +00005202static void handleAssertCapabilityAttr(Sema &S, Decl *D,
5203 const AttributeList &Attr) {
5204 D->addAttr(::new (S.Context) AssertCapabilityAttr(Attr.getRange(), S.Context,
5205 Attr.getArgAsExpr(0),
5206 Attr.getAttributeSpellingListIndex()));
5207}
5208
5209static void handleAcquireCapabilityAttr(Sema &S, Decl *D,
5210 const AttributeList &Attr) {
5211 SmallVector<Expr*, 1> Args;
Aaron Ballman18d85ae2014-03-20 16:02:49 +00005212 if (!checkLockFunAttrCommon(S, D, Attr, Args))
Aaron Ballman9e9d1842014-02-21 21:05:14 +00005213 return;
5214
5215 D->addAttr(::new (S.Context) AcquireCapabilityAttr(Attr.getRange(),
5216 S.Context,
5217 Args.data(), Args.size(),
5218 Attr.getAttributeSpellingListIndex()));
5219}
5220
5221static void handleTryAcquireCapabilityAttr(Sema &S, Decl *D,
5222 const AttributeList &Attr) {
5223 SmallVector<Expr*, 2> Args;
5224 if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
5225 return;
5226
5227 D->addAttr(::new (S.Context) TryAcquireCapabilityAttr(Attr.getRange(),
5228 S.Context,
5229 Attr.getArgAsExpr(0),
5230 Args.data(),
5231 Args.size(),
5232 Attr.getAttributeSpellingListIndex()));
5233}
5234
5235static void handleReleaseCapabilityAttr(Sema &S, Decl *D,
5236 const AttributeList &Attr) {
Aaron Ballman9e9d1842014-02-21 21:05:14 +00005237 // Check that all arguments are lockable objects.
Aaron Ballman18d85ae2014-03-20 16:02:49 +00005238 SmallVector<Expr *, 1> Args;
Aaron Ballman69e6e7c2014-03-24 19:29:19 +00005239 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 0, true);
Aaron Ballman9e9d1842014-02-21 21:05:14 +00005240
Aaron Ballman18d85ae2014-03-20 16:02:49 +00005241 D->addAttr(::new (S.Context) ReleaseCapabilityAttr(
5242 Attr.getRange(), S.Context, Args.data(), Args.size(),
5243 Attr.getAttributeSpellingListIndex()));
Aaron Ballman9e9d1842014-02-21 21:05:14 +00005244}
5245
Aaron Ballmanefe348e2014-02-18 17:36:50 +00005246static void handleRequiresCapabilityAttr(Sema &S, Decl *D,
5247 const AttributeList &Attr) {
5248 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
5249 return;
5250
5251 // check that all arguments are lockable objects
5252 SmallVector<Expr*, 1> Args;
Aaron Ballman69e6e7c2014-03-24 19:29:19 +00005253 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
Aaron Ballmanefe348e2014-02-18 17:36:50 +00005254 if (Args.empty())
5255 return;
5256
5257 RequiresCapabilityAttr *RCA = ::new (S.Context)
5258 RequiresCapabilityAttr(Attr.getRange(), S.Context, Args.data(),
5259 Args.size(), Attr.getAttributeSpellingListIndex());
5260
5261 D->addAttr(RCA);
5262}
5263
Aaron Ballman43f40102014-11-14 22:34:56 +00005264static void handleDeprecatedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5265 if (auto *NSD = dyn_cast<NamespaceDecl>(D)) {
5266 if (NSD->isAnonymousNamespace()) {
5267 S.Diag(Attr.getLoc(), diag::warn_deprecated_anonymous_namespace);
5268 // Do not want to attach the attribute to the namespace because that will
5269 // cause confusing diagnostic reports for uses of declarations within the
5270 // namespace.
5271 return;
5272 }
5273 }
Saleem Abdulrasoolf931a382015-02-16 22:27:01 +00005274
Manman Renc7890fe2016-03-16 18:50:49 +00005275 // Handle the cases where the attribute has a text message.
5276 StringRef Str, Replacement;
5277 if (Attr.isArgExpr(0) && Attr.getArgAsExpr(0) &&
5278 !S.checkStringLiteralArgumentAttr(Attr, 0, Str))
5279 return;
5280
5281 // Only support a single optional message for Declspec and CXX11.
5282 if (Attr.isDeclspecAttribute() || Attr.isCXX11Attribute())
5283 checkAttributeAtMostNumArgs(S, Attr, 1);
5284 else if (Attr.isArgExpr(1) && Attr.getArgAsExpr(1) &&
5285 !S.checkStringLiteralArgumentAttr(Attr, 1, Replacement))
5286 return;
5287
Saleem Abdulrasoolf931a382015-02-16 22:27:01 +00005288 if (!S.getLangOpts().CPlusPlus14)
5289 if (Attr.isCXX11Attribute() &&
5290 !(Attr.hasScope() && Attr.getScopeName()->isStr("gnu")))
Richard Smith4f902c72016-03-08 00:32:55 +00005291 S.Diag(Attr.getLoc(), diag::ext_cxx14_attr) << Attr.getName();
Saleem Abdulrasoolf931a382015-02-16 22:27:01 +00005292
Manman Renc7890fe2016-03-16 18:50:49 +00005293 D->addAttr(::new (S.Context) DeprecatedAttr(Attr.getRange(), S.Context, Str,
5294 Replacement,
5295 Attr.getAttributeSpellingListIndex()));
Aaron Ballman43f40102014-11-14 22:34:56 +00005296}
5297
Peter Collingbourne915df992015-05-15 18:33:32 +00005298static void handleNoSanitizeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5299 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
5300 return;
5301
Benjamin Kramer1b582012016-02-13 18:11:49 +00005302 std::vector<StringRef> Sanitizers;
Peter Collingbourne915df992015-05-15 18:33:32 +00005303
5304 for (unsigned I = 0, E = Attr.getNumArgs(); I != E; ++I) {
5305 StringRef SanitizerName;
5306 SourceLocation LiteralLoc;
5307
5308 if (!S.checkStringLiteralArgumentAttr(Attr, I, SanitizerName, &LiteralLoc))
5309 return;
5310
5311 if (parseSanitizerValue(SanitizerName, /*AllowGroups=*/true) == 0)
5312 S.Diag(LiteralLoc, diag::warn_unknown_sanitizer_ignored) << SanitizerName;
5313
5314 Sanitizers.push_back(SanitizerName);
5315 }
5316
5317 D->addAttr(::new (S.Context) NoSanitizeAttr(
5318 Attr.getRange(), S.Context, Sanitizers.data(), Sanitizers.size(),
5319 Attr.getAttributeSpellingListIndex()));
5320}
5321
5322static void handleNoSanitizeSpecificAttr(Sema &S, Decl *D,
5323 const AttributeList &Attr) {
Aaron Ballman8b5e7ba2015-10-08 19:24:08 +00005324 StringRef AttrName = Attr.getName()->getName();
5325 normalizeName(AttrName);
Benjamin Kramer1b582012016-02-13 18:11:49 +00005326 StringRef SanitizerName =
5327 llvm::StringSwitch<StringRef>(AttrName)
Peter Collingbourne915df992015-05-15 18:33:32 +00005328 .Case("no_address_safety_analysis", "address")
5329 .Case("no_sanitize_address", "address")
5330 .Case("no_sanitize_thread", "thread")
Peter Collingbourne94410942015-05-15 20:11:18 +00005331 .Case("no_sanitize_memory", "memory");
Peter Collingbourne915df992015-05-15 18:33:32 +00005332 D->addAttr(::new (S.Context)
5333 NoSanitizeAttr(Attr.getRange(), S.Context, &SanitizerName, 1,
5334 Attr.getAttributeSpellingListIndex()));
5335}
5336
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00005337static void handleInternalLinkageAttr(Sema &S, Decl *D,
5338 const AttributeList &Attr) {
5339 if (InternalLinkageAttr *Internal =
5340 S.mergeInternalLinkageAttr(D, Attr.getRange(), Attr.getName(),
5341 Attr.getAttributeSpellingListIndex()))
5342 D->addAttr(Internal);
5343}
5344
Anastasia Stulovac4bb5df2016-03-31 11:07:22 +00005345static void handleOpenCLNoSVMAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5346 if (S.LangOpts.OpenCLVersion != 200)
5347 S.Diag(Attr.getLoc(), diag::err_attribute_requires_opencl_version)
5348 << Attr.getName() << "2.0" << 0;
5349 else
5350 S.Diag(Attr.getLoc(), diag::warn_opencl_attr_deprecated_ignored)
5351 << Attr.getName() << "2.0";
5352}
5353
Aaron Ballman8ee40b72013-09-09 23:33:17 +00005354/// Handles semantic checking for features that are common to all attributes,
5355/// such as checking whether a parameter was properly specified, or the correct
5356/// number of arguments were passed, etc.
5357static bool handleCommonAttributeFeatures(Sema &S, Scope *scope, Decl *D,
5358 const AttributeList &Attr) {
5359 // Several attributes carry different semantics than the parsing requires, so
5360 // those are opted out of the common handling.
5361 //
5362 // We also bail on unknown and ignored attributes because those are handled
5363 // as part of the target-specific handling logic.
5364 if (Attr.hasCustomParsing() ||
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005365 Attr.getKind() == AttributeList::UnknownAttribute)
Aaron Ballman8ee40b72013-09-09 23:33:17 +00005366 return false;
5367
Aaron Ballman3aff6332013-12-02 19:30:36 +00005368 // Check whether the attribute requires specific language extensions to be
5369 // enabled.
5370 if (!Attr.diagnoseLangOpts(S))
5371 return true;
5372
Aaron Ballman8ed8dbd2014-07-31 16:37:04 +00005373 if (Attr.getMinArgs() == Attr.getMaxArgs()) {
5374 // If there are no optional arguments, then checking for the argument count
5375 // is trivial.
5376 if (!checkAttributeNumArgs(S, Attr, Attr.getMinArgs()))
5377 return true;
5378 } else {
5379 // There are optional arguments, so checking is slightly more involved.
5380 if (Attr.getMinArgs() &&
5381 !checkAttributeAtLeastNumArgs(S, Attr, Attr.getMinArgs()))
5382 return true;
5383 else if (!Attr.hasVariadicArg() && Attr.getMaxArgs() &&
5384 !checkAttributeAtMostNumArgs(S, Attr, Attr.getMaxArgs()))
5385 return true;
5386 }
Aaron Ballman74eeeae2013-11-27 13:27:02 +00005387
5388 // Check whether the attribute appertains to the given subject.
5389 if (!Attr.diagnoseAppertainsTo(S, D))
5390 return true;
5391
Aaron Ballman8ee40b72013-09-09 23:33:17 +00005392 return false;
5393}
5394
Xiuli Pan11e13f62016-02-26 03:13:03 +00005395static void handleOpenCLAccessAttr(Sema &S, Decl *D,
5396 const AttributeList &Attr) {
5397 if (D->isInvalidDecl())
5398 return;
5399
5400 // Check if there is only one access qualifier.
5401 if (D->hasAttr<OpenCLAccessAttr>()) {
5402 S.Diag(Attr.getLoc(), diag::err_opencl_multiple_access_qualifiers)
5403 << D->getSourceRange();
5404 D->setInvalidDecl(true);
5405 return;
5406 }
5407
5408 // OpenCL v2.0 s6.6 - read_write can be used for image types to specify that an
5409 // image object can be read and written.
5410 // OpenCL v2.0 s6.13.6 - A kernel cannot read from and write to the same pipe
5411 // object. Using the read_write (or __read_write) qualifier with the pipe
5412 // qualifier is a compilation error.
5413 if (const ParmVarDecl *PDecl = dyn_cast<ParmVarDecl>(D)) {
5414 const Type *DeclTy = PDecl->getType().getCanonicalType().getTypePtr();
5415 if (Attr.getName()->getName().find("read_write") != StringRef::npos) {
5416 if (S.getLangOpts().OpenCLVersion < 200 || DeclTy->isPipeType()) {
5417 S.Diag(Attr.getLoc(), diag::err_opencl_invalid_read_write)
5418 << Attr.getName() << PDecl->getType() << DeclTy->isImageType();
5419 D->setInvalidDecl(true);
5420 return;
5421 }
5422 }
5423 }
5424
5425 D->addAttr(::new (S.Context) OpenCLAccessAttr(
5426 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
5427}
5428
Ted Kremenek9ecdfaf2009-05-09 02:44:38 +00005429//===----------------------------------------------------------------------===//
Chris Lattner9e2aafe2008-06-29 00:23:49 +00005430// Top Level Sema Entry Points
5431//===----------------------------------------------------------------------===//
5432
Richard Smithf8a75c32013-08-29 00:47:48 +00005433/// ProcessDeclAttribute - Apply the specific attribute to the specified decl if
5434/// the attribute applies to decls. If the attribute is a type attribute, just
5435/// silently ignore it if a GNU attribute.
5436static void ProcessDeclAttribute(Sema &S, Scope *scope, Decl *D,
5437 const AttributeList &Attr,
5438 bool IncludeCXX11Attributes) {
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005439 if (Attr.isInvalid() || Attr.getKind() == AttributeList::IgnoredAttribute)
Richard Smithf8a75c32013-08-29 00:47:48 +00005440 return;
Abramo Bagnara50099372010-04-30 13:10:51 +00005441
Richard Smithf8a75c32013-08-29 00:47:48 +00005442 // Ignore C++11 attributes on declarator chunks: they appertain to the type
5443 // instead.
5444 if (Attr.isCXX11Attribute() && !IncludeCXX11Attributes)
5445 return;
5446
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005447 // Unknown attributes are automatically warned on. Target-specific attributes
5448 // which do not apply to the current target architecture are treated as
5449 // though they were unknown attributes.
5450 if (Attr.getKind() == AttributeList::UnknownAttribute ||
Bob Wilson7c730832015-07-20 22:57:31 +00005451 !Attr.existsInTarget(S.Context.getTargetInfo())) {
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005452 S.Diag(Attr.getLoc(), Attr.isDeclspecAttribute()
5453 ? diag::warn_unhandled_ms_attribute_ignored
5454 : diag::warn_unknown_attribute_ignored)
5455 << Attr.getName();
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005456 return;
5457 }
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005458
Aaron Ballman8ee40b72013-09-09 23:33:17 +00005459 if (handleCommonAttributeFeatures(S, scope, D, Attr))
5460 return;
5461
Chris Lattnerb632a6e2008-06-29 00:43:07 +00005462 switch (Attr.getKind()) {
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005463 default:
Richard Smith4f902c72016-03-08 00:32:55 +00005464 if (!Attr.isStmtAttr()) {
5465 // Type attributes are handled elsewhere; silently move on.
5466 assert(Attr.isTypeAttr() && "Non-type attribute not handled");
5467 break;
5468 }
5469 S.Diag(Attr.getLoc(), diag::err_stmt_attribute_invalid_on_decl)
5470 << Attr.getName() << D->getLocation();
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005471 break;
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005472 case AttributeList::AT_Interrupt:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005473 handleInterruptAttr(S, D, Attr);
5474 break;
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005475 case AttributeList::AT_X86ForceAlignArgPointer:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005476 handleX86ForceAlignArgPointerAttr(S, D, Attr);
5477 break;
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005478 case AttributeList::AT_DLLExport:
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005479 case AttributeList::AT_DLLImport:
Hans Wennborge82f19c2014-06-24 23:57:05 +00005480 handleDLLAttr(S, D, Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005481 break;
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005482 case AttributeList::AT_Mips16:
Justin Lebar3eaaf862016-01-13 01:07:35 +00005483 handleSimpleAttributeWithExclusions<Mips16Attr, MipsInterruptAttr>(S, D,
5484 Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005485 break;
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005486 case AttributeList::AT_NoMips16:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005487 handleSimpleAttribute<NoMips16Attr>(S, D, Attr);
5488 break;
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00005489 case AttributeList::AT_AMDGPUFlatWorkGroupSize:
5490 handleAMDGPUFlatWorkGroupSizeAttr(S, D, Attr);
5491 break;
5492 case AttributeList::AT_AMDGPUWavesPerEU:
5493 handleAMDGPUWavesPerEUAttr(S, D, Attr);
Matt Arsenault43fae6c2014-12-04 20:38:18 +00005494 break;
5495 case AttributeList::AT_AMDGPUNumSGPR:
5496 handleAMDGPUNumSGPRAttr(S, D, Attr);
5497 break;
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00005498 case AttributeList::AT_AMDGPUNumVGPR:
5499 handleAMDGPUNumVGPRAttr(S, D, Attr);
5500 break;
Aaron Ballman9beb5172013-12-02 15:13:14 +00005501 case AttributeList::AT_IBAction:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005502 handleSimpleAttribute<IBActionAttr>(S, D, Attr);
5503 break;
5504 case AttributeList::AT_IBOutlet:
5505 handleIBOutlet(S, D, Attr);
5506 break;
Richard Smith10876ef2013-01-17 01:30:42 +00005507 case AttributeList::AT_IBOutletCollection:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005508 handleIBOutletCollection(S, D, Attr);
5509 break;
Dmitry Polukhin85eda122016-04-11 07:48:59 +00005510 case AttributeList::AT_IFunc:
5511 handleIFuncAttr(S, D, Attr);
5512 break;
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005513 case AttributeList::AT_Alias:
5514 handleAliasAttr(S, D, Attr);
5515 break;
5516 case AttributeList::AT_Aligned:
5517 handleAlignedAttr(S, D, Attr);
5518 break;
Hal Finkel1b0d24e2014-10-02 21:21:25 +00005519 case AttributeList::AT_AlignValue:
5520 handleAlignValueAttr(S, D, Attr);
5521 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005522 case AttributeList::AT_AlwaysInline:
Paul Robinsonf0674352014-03-31 22:29:15 +00005523 handleAlwaysInlineAttr(S, D, Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005524 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005525 case AttributeList::AT_AnalyzerNoReturn:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005526 handleAnalyzerNoReturnAttr(S, D, Attr);
5527 break;
5528 case AttributeList::AT_TLSModel:
5529 handleTLSModelAttr(S, D, Attr);
5530 break;
5531 case AttributeList::AT_Annotate:
5532 handleAnnotateAttr(S, D, Attr);
5533 break;
5534 case AttributeList::AT_Availability:
5535 handleAvailabilityAttr(S, D, Attr);
5536 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005537 case AttributeList::AT_CarriesDependency:
Richard Smithe233fbf2013-01-28 22:42:45 +00005538 handleDependencyAttr(S, scope, D, Attr);
5539 break;
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005540 case AttributeList::AT_Common:
5541 handleCommonAttr(S, D, Attr);
5542 break;
Aaron Ballman3aff6332013-12-02 19:30:36 +00005543 case AttributeList::AT_CUDAConstant:
Justin Lebar3eaaf862016-01-13 01:07:35 +00005544 handleSimpleAttributeWithExclusions<CUDAConstantAttr, CUDASharedAttr>(S, D,
5545 Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005546 break;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00005547 case AttributeList::AT_PassObjectSize:
5548 handlePassObjectSizeAttr(S, D, Attr);
5549 break;
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005550 case AttributeList::AT_Constructor:
5551 handleConstructorAttr(S, D, Attr);
5552 break;
Richard Smith10876ef2013-01-17 01:30:42 +00005553 case AttributeList::AT_CXX11NoReturn:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005554 handleSimpleAttribute<CXX11NoReturnAttr>(S, D, Attr);
5555 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005556 case AttributeList::AT_Deprecated:
Aaron Ballman43f40102014-11-14 22:34:56 +00005557 handleDeprecatedAttr(S, D, Attr);
Benjamin Kramerf435ab42012-05-16 12:19:08 +00005558 break;
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005559 case AttributeList::AT_Destructor:
5560 handleDestructorAttr(S, D, Attr);
5561 break;
5562 case AttributeList::AT_EnableIf:
5563 handleEnableIfAttr(S, D, Attr);
5564 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005565 case AttributeList::AT_ExtVectorType:
Chandler Carruthedc2c642011-07-02 00:01:44 +00005566 handleExtVectorTypeAttr(S, scope, D, Attr);
Chris Lattnerb632a6e2008-06-29 00:43:07 +00005567 break;
Quentin Colombet4e172062012-11-01 23:55:47 +00005568 case AttributeList::AT_MinSize:
Paul Robinsonaae2fba2014-12-10 23:34:36 +00005569 handleMinSizeAttr(S, D, Attr);
Quentin Colombet4e172062012-11-01 23:55:47 +00005570 break;
Paul Robinsonf0674352014-03-31 22:29:15 +00005571 case AttributeList::AT_OptimizeNone:
5572 handleOptimizeNoneAttr(S, D, Attr);
5573 break;
Alexis Hunt724f14e2014-11-28 00:53:20 +00005574 case AttributeList::AT_FlagEnum:
5575 handleSimpleAttribute<FlagEnumAttr>(S, D, Attr);
5576 break;
Peter Collingbourne41af7c22014-05-20 17:12:51 +00005577 case AttributeList::AT_Flatten:
5578 handleSimpleAttribute<FlattenAttr>(S, D, Attr);
5579 break;
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005580 case AttributeList::AT_Format:
5581 handleFormatAttr(S, D, Attr);
5582 break;
5583 case AttributeList::AT_FormatArg:
5584 handleFormatArgAttr(S, D, Attr);
5585 break;
5586 case AttributeList::AT_CUDAGlobal:
5587 handleGlobalAttr(S, D, Attr);
5588 break;
Aaron Ballmanf79ee272013-12-02 21:09:08 +00005589 case AttributeList::AT_CUDADevice:
Justin Lebar3eaaf862016-01-13 01:07:35 +00005590 handleSimpleAttributeWithExclusions<CUDADeviceAttr, CUDAGlobalAttr>(S, D,
5591 Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005592 break;
Aaron Ballman3aff6332013-12-02 19:30:36 +00005593 case AttributeList::AT_CUDAHost:
Justin Lebar3eaaf862016-01-13 01:07:35 +00005594 handleSimpleAttributeWithExclusions<CUDAHostAttr, CUDAGlobalAttr>(S, D,
5595 Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005596 break;
5597 case AttributeList::AT_GNUInline:
5598 handleGNUInlineAttr(S, D, Attr);
5599 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005600 case AttributeList::AT_CUDALaunchBounds:
Chandler Carruthedc2c642011-07-02 00:01:44 +00005601 handleLaunchBoundsAttr(S, D, Attr);
Peter Collingbourne827301e2010-12-12 23:03:07 +00005602 break;
David Majnemer631a90b2015-02-04 07:23:21 +00005603 case AttributeList::AT_Restrict:
5604 handleRestrictAttr(S, D, Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005605 break;
Aaron Ballman6f9165a2013-11-27 15:24:06 +00005606 case AttributeList::AT_MayAlias:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005607 handleSimpleAttribute<MayAliasAttr>(S, D, Attr);
5608 break;
5609 case AttributeList::AT_Mode:
5610 handleModeAttr(S, D, Attr);
5611 break;
David Majnemer1bf0f8e2015-07-20 22:51:52 +00005612 case AttributeList::AT_NoAlias:
5613 handleSimpleAttribute<NoAliasAttr>(S, D, Attr);
5614 break;
Aaron Ballman6f9165a2013-11-27 15:24:06 +00005615 case AttributeList::AT_NoCommon:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005616 handleSimpleAttribute<NoCommonAttr>(S, D, Attr);
5617 break;
Peter Collingbourneb4728c12014-05-19 22:14:34 +00005618 case AttributeList::AT_NoSplitStack:
5619 handleSimpleAttribute<NoSplitStackAttr>(S, D, Attr);
5620 break;
Ted Kremenek9aedc152014-01-17 06:24:56 +00005621 case AttributeList::AT_NonNull:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005622 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(D))
5623 handleNonNullAttrParameter(S, PVD, Attr);
5624 else
5625 handleNonNullAttr(S, D, Attr);
5626 break;
Aaron Ballmanfc1951c2014-01-20 14:19:44 +00005627 case AttributeList::AT_ReturnsNonNull:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005628 handleReturnsNonNullAttr(S, D, Attr);
5629 break;
Hal Finkelee90a222014-09-26 05:04:30 +00005630 case AttributeList::AT_AssumeAligned:
5631 handleAssumeAlignedAttr(S, D, Attr);
5632 break;
Aaron Ballman6f9165a2013-11-27 15:24:06 +00005633 case AttributeList::AT_Overloadable:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005634 handleSimpleAttribute<OverloadableAttr>(S, D, Attr);
5635 break;
5636 case AttributeList::AT_Ownership:
5637 handleOwnershipAttr(S, D, Attr);
5638 break;
5639 case AttributeList::AT_Cold:
5640 handleColdAttr(S, D, Attr);
5641 break;
5642 case AttributeList::AT_Hot:
5643 handleHotAttr(S, D, Attr);
5644 break;
Aaron Ballman6f9165a2013-11-27 15:24:06 +00005645 case AttributeList::AT_Naked:
Charles Davis0e379112016-08-08 21:19:08 +00005646 handleNakedAttr(S, D, Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005647 break;
5648 case AttributeList::AT_NoReturn:
5649 handleNoReturnAttr(S, D, Attr);
5650 break;
Aaron Ballmanbf7b1ee2013-12-21 16:49:29 +00005651 case AttributeList::AT_NoThrow:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005652 handleSimpleAttribute<NoThrowAttr>(S, D, Attr);
5653 break;
Aaron Ballman3aff6332013-12-02 19:30:36 +00005654 case AttributeList::AT_CUDAShared:
Justin Lebar10411012016-09-30 23:57:30 +00005655 handleSharedAttr(S, D, Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005656 break;
5657 case AttributeList::AT_VecReturn:
5658 handleVecReturnAttr(S, D, Attr);
5659 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005660 case AttributeList::AT_ObjCOwnership:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005661 handleObjCOwnershipAttr(S, D, Attr);
5662 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005663 case AttributeList::AT_ObjCPreciseLifetime:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005664 handleObjCPreciseLifetimeAttr(S, D, Attr);
5665 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005666 case AttributeList::AT_ObjCReturnsInnerPointer:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005667 handleObjCReturnsInnerPointerAttr(S, D, Attr);
5668 break;
Fariborz Jahanian566fff02012-09-07 23:46:23 +00005669 case AttributeList::AT_ObjCRequiresSuper:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005670 handleObjCRequiresSuperAttr(S, D, Attr);
5671 break;
Fariborz Jahanian0a0a3972013-11-13 23:59:17 +00005672 case AttributeList::AT_ObjCBridge:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005673 handleObjCBridgeAttr(S, scope, D, Attr);
5674 break;
Fariborz Jahanian87c77912013-11-21 20:50:32 +00005675 case AttributeList::AT_ObjCBridgeMutable:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005676 handleObjCBridgeMutableAttr(S, scope, D, Attr);
5677 break;
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00005678 case AttributeList::AT_ObjCBridgeRelated:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005679 handleObjCBridgeRelatedAttr(S, scope, D, Attr);
5680 break;
Argyrios Kyrtzidisd1438b42013-12-03 21:11:25 +00005681 case AttributeList::AT_ObjCDesignatedInitializer:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005682 handleObjCDesignatedInitializer(S, D, Attr);
5683 break;
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00005684 case AttributeList::AT_ObjCRuntimeName:
5685 handleObjCRuntimeName(S, D, Attr);
5686 break;
Douglas Gregor24ae22c2016-04-01 23:23:52 +00005687 case AttributeList::AT_ObjCRuntimeVisible:
5688 handleSimpleAttribute<ObjCRuntimeVisibleAttr>(S, D, Attr);
5689 break;
Alex Denisovfde64952015-06-26 05:28:36 +00005690 case AttributeList::AT_ObjCBoxable:
5691 handleObjCBoxable(S, D, Attr);
5692 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005693 case AttributeList::AT_CFAuditedTransfer:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005694 handleCFAuditedTransferAttr(S, D, Attr);
5695 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005696 case AttributeList::AT_CFUnknownTransfer:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005697 handleCFUnknownTransferAttr(S, D, Attr);
5698 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005699 case AttributeList::AT_CFConsumed:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005700 case AttributeList::AT_NSConsumed:
5701 handleNSConsumedAttr(S, D, Attr);
5702 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005703 case AttributeList::AT_NSConsumesSelf:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005704 handleSimpleAttribute<NSConsumesSelfAttr>(S, D, Attr);
5705 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005706 case AttributeList::AT_NSReturnsAutoreleased:
5707 case AttributeList::AT_NSReturnsNotRetained:
5708 case AttributeList::AT_CFReturnsNotRetained:
5709 case AttributeList::AT_NSReturnsRetained:
5710 case AttributeList::AT_CFReturnsRetained:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005711 handleNSReturnsRetainedAttr(S, D, Attr);
5712 break;
Tanya Lattnerbcffcdf2012-07-09 22:06:01 +00005713 case AttributeList::AT_WorkGroupSizeHint:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005714 handleWorkGroupSize<WorkGroupSizeHintAttr>(S, D, Attr);
5715 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005716 case AttributeList::AT_ReqdWorkGroupSize:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005717 handleWorkGroupSize<ReqdWorkGroupSizeAttr>(S, D, Attr);
5718 break;
Joey Goulyaba589c2013-03-08 09:42:32 +00005719 case AttributeList::AT_VecTypeHint:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005720 handleVecTypeHint(S, D, Attr);
5721 break;
Eric Fiselier341e8252016-09-02 18:53:31 +00005722 case AttributeList::AT_RequireConstantInit:
5723 handleSimpleAttribute<RequireConstantInitAttr>(S, D, Attr);
5724 break;
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005725 case AttributeList::AT_InitPriority:
5726 handleInitPriorityAttr(S, D, Attr);
5727 break;
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005728 case AttributeList::AT_Packed:
5729 handlePackedAttr(S, D, Attr);
5730 break;
5731 case AttributeList::AT_Section:
5732 handleSectionAttr(S, D, Attr);
5733 break;
Eric Christopher11acf732015-06-12 01:35:52 +00005734 case AttributeList::AT_Target:
5735 handleTargetAttr(S, D, Attr);
5736 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005737 case AttributeList::AT_Unavailable:
Aaron Ballman8b8ebdd2013-07-18 13:13:52 +00005738 handleAttrWithMessage<UnavailableAttr>(S, D, Attr);
Benjamin Kramerf435ab42012-05-16 12:19:08 +00005739 break;
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005740 case AttributeList::AT_ArcWeakrefUnavailable:
5741 handleSimpleAttribute<ArcWeakrefUnavailableAttr>(S, D, Attr);
5742 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005743 case AttributeList::AT_ObjCRootClass:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005744 handleSimpleAttribute<ObjCRootClassAttr>(S, D, Attr);
5745 break;
Ted Kremenekf41cf7f12013-12-10 19:43:48 +00005746 case AttributeList::AT_ObjCExplicitProtocolImpl:
Ted Kremenek438f8db2014-02-22 01:06:05 +00005747 handleObjCSuppresProtocolAttr(S, D, Attr);
Ted Kremenek28eace62013-11-23 01:01:34 +00005748 break;
5749 case AttributeList::AT_ObjCRequiresPropertyDefs:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005750 handleSimpleAttribute<ObjCRequiresPropertyDefsAttr>(S, D, Attr);
5751 break;
Aaron Ballman12b9f652014-01-16 13:55:42 +00005752 case AttributeList::AT_Unused:
Aaron Ballman0bcd6c12016-03-09 16:48:08 +00005753 handleUnusedAttr(S, D, Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005754 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005755 case AttributeList::AT_ReturnsTwice:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005756 handleSimpleAttribute<ReturnsTwiceAttr>(S, D, Attr);
5757 break;
Akira Hatanakac8667622015-11-06 23:56:15 +00005758 case AttributeList::AT_NotTailCalled:
5759 handleNotTailCalledAttr(S, D, Attr);
5760 break;
Akira Hatanaka7828b1e2015-11-13 00:42:21 +00005761 case AttributeList::AT_DisableTailCalls:
5762 handleDisableTailCallsAttr(S, D, Attr);
5763 break;
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005764 case AttributeList::AT_Used:
5765 handleUsedAttr(S, D, Attr);
5766 break;
John McCalld041a9b2013-02-20 01:54:26 +00005767 case AttributeList::AT_Visibility:
5768 handleVisibilityAttr(S, D, Attr, false);
5769 break;
5770 case AttributeList::AT_TypeVisibility:
5771 handleVisibilityAttr(S, D, Attr, true);
5772 break;
Lubos Lunakedc13882013-07-20 15:05:36 +00005773 case AttributeList::AT_WarnUnused:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005774 handleSimpleAttribute<WarnUnusedAttr>(S, D, Attr);
5775 break;
5776 case AttributeList::AT_WarnUnusedResult:
5777 handleWarnUnusedResult(S, D, Attr);
Chris Lattner237f2752009-02-14 07:37:35 +00005778 break;
Aaron Ballman604dfec2013-12-02 17:07:07 +00005779 case AttributeList::AT_Weak:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005780 handleSimpleAttribute<WeakAttr>(S, D, Attr);
5781 break;
5782 case AttributeList::AT_WeakRef:
5783 handleWeakRefAttr(S, D, Attr);
5784 break;
5785 case AttributeList::AT_WeakImport:
5786 handleWeakImportAttr(S, D, Attr);
5787 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005788 case AttributeList::AT_TransparentUnion:
Chandler Carruthedc2c642011-07-02 00:01:44 +00005789 handleTransparentUnionAttr(S, D, Attr);
Chris Lattnerb632a6e2008-06-29 00:43:07 +00005790 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005791 case AttributeList::AT_ObjCException:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005792 handleSimpleAttribute<ObjCExceptionAttr>(S, D, Attr);
5793 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005794 case AttributeList::AT_ObjCMethodFamily:
Chandler Carruthedc2c642011-07-02 00:01:44 +00005795 handleObjCMethodFamilyAttr(S, D, Attr);
John McCall86bc21f2011-03-02 11:33:24 +00005796 break;
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005797 case AttributeList::AT_ObjCNSObject:
5798 handleObjCNSObject(S, D, Attr);
5799 break;
Fariborz Jahanian7a60b6d2015-04-16 18:38:44 +00005800 case AttributeList::AT_ObjCIndependentClass:
5801 handleObjCIndependentClass(S, D, Attr);
5802 break;
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005803 case AttributeList::AT_Blocks:
5804 handleBlocksAttr(S, D, Attr);
5805 break;
5806 case AttributeList::AT_Sentinel:
5807 handleSentinelAttr(S, D, Attr);
5808 break;
Aaron Ballmanbf7b1ee2013-12-21 16:49:29 +00005809 case AttributeList::AT_Const:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005810 handleSimpleAttribute<ConstAttr>(S, D, Attr);
5811 break;
Aaron Ballman6f9165a2013-11-27 15:24:06 +00005812 case AttributeList::AT_Pure:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005813 handleSimpleAttribute<PureAttr>(S, D, Attr);
5814 break;
5815 case AttributeList::AT_Cleanup:
5816 handleCleanupAttr(S, D, Attr);
5817 break;
5818 case AttributeList::AT_NoDebug:
5819 handleNoDebugAttr(S, D, Attr);
5820 break;
Aaron Ballman7c19ab12014-02-22 16:59:24 +00005821 case AttributeList::AT_NoDuplicate:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005822 handleSimpleAttribute<NoDuplicateAttr>(S, D, Attr);
5823 break;
Aaron Ballman6f9165a2013-11-27 15:24:06 +00005824 case AttributeList::AT_NoInline:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005825 handleSimpleAttribute<NoInlineAttr>(S, D, Attr);
5826 break;
5827 case AttributeList::AT_NoInstrumentFunction: // Interacts with -pg.
5828 handleSimpleAttribute<NoInstrumentFunctionAttr>(S, D, Attr);
5829 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005830 case AttributeList::AT_StdCall:
5831 case AttributeList::AT_CDecl:
5832 case AttributeList::AT_FastCall:
5833 case AttributeList::AT_ThisCall:
5834 case AttributeList::AT_Pascal:
John McCall477f2bb2016-03-03 06:39:32 +00005835 case AttributeList::AT_SwiftCall:
Reid Klecknerd7857f02014-10-24 17:42:17 +00005836 case AttributeList::AT_VectorCall:
Charles Davisb5a214e2013-08-30 04:39:01 +00005837 case AttributeList::AT_MSABI:
5838 case AttributeList::AT_SysVABI:
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005839 case AttributeList::AT_Pcs:
Guy Benyeif0a014b2012-12-25 08:53:55 +00005840 case AttributeList::AT_IntelOclBicc:
Roman Levenstein35aa5ce2016-03-16 18:00:46 +00005841 case AttributeList::AT_PreserveMost:
5842 case AttributeList::AT_PreserveAll:
Chandler Carruthedc2c642011-07-02 00:01:44 +00005843 handleCallConvAttr(S, D, Attr);
John McCallab26cfa2010-02-05 21:31:56 +00005844 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005845 case AttributeList::AT_OpenCLKernel:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005846 handleSimpleAttribute<OpenCLKernelAttr>(S, D, Attr);
5847 break;
Xiuli Pan11e13f62016-02-26 03:13:03 +00005848 case AttributeList::AT_OpenCLAccess:
5849 handleOpenCLAccessAttr(S, D, Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005850 break;
Anastasia Stulovafde76222016-04-01 16:05:09 +00005851 case AttributeList::AT_OpenCLNoSVM:
5852 handleOpenCLNoSVMAttr(S, D, Attr);
5853 break;
John McCall477f2bb2016-03-03 06:39:32 +00005854 case AttributeList::AT_SwiftContext:
5855 handleParameterABIAttr(S, D, Attr, ParameterABI::SwiftContext);
5856 break;
5857 case AttributeList::AT_SwiftErrorResult:
5858 handleParameterABIAttr(S, D, Attr, ParameterABI::SwiftErrorResult);
5859 break;
5860 case AttributeList::AT_SwiftIndirectResult:
5861 handleParameterABIAttr(S, D, Attr, ParameterABI::SwiftIndirectResult);
5862 break;
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00005863 case AttributeList::AT_InternalLinkage:
5864 handleInternalLinkageAttr(S, D, Attr);
5865 break;
Peter Collingbourne3afb2662016-04-28 17:09:37 +00005866 case AttributeList::AT_LTOVisibilityPublic:
5867 handleSimpleAttribute<LTOVisibilityPublicAttr>(S, D, Attr);
5868 break;
John McCall8d32c052012-05-22 21:28:12 +00005869
5870 // Microsoft attributes:
David Majnemercd3ebfe2016-05-23 17:16:12 +00005871 case AttributeList::AT_EmptyBases:
5872 handleSimpleAttribute<EmptyBasesAttr>(S, D, Attr);
5873 break;
5874 case AttributeList::AT_LayoutVersion:
5875 handleLayoutVersion(S, D, Attr);
5876 break;
David Majnemer8ab003a2015-02-02 19:30:52 +00005877 case AttributeList::AT_MSNoVTable:
5878 handleSimpleAttribute<MSNoVTableAttr>(S, D, Attr);
David Majnemer129f4172015-02-02 10:22:20 +00005879 break;
David Majnemer8ab003a2015-02-02 19:30:52 +00005880 case AttributeList::AT_MSStruct:
5881 handleSimpleAttribute<MSStructAttr>(S, D, Attr);
John McCall8d32c052012-05-22 21:28:12 +00005882 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005883 case AttributeList::AT_Uuid:
Chandler Carruthedc2c642011-07-02 00:01:44 +00005884 handleUuidAttr(S, D, Attr);
Francois Picheta83957a2010-12-19 06:50:37 +00005885 break;
Aaron Ballman8edb5c22013-12-18 23:44:18 +00005886 case AttributeList::AT_MSInheritance:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005887 handleMSInheritanceAttr(S, D, Attr);
5888 break;
Reid Klecknerb144d362013-05-20 14:02:37 +00005889 case AttributeList::AT_SelectAny:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005890 handleSimpleAttribute<SelectAnyAttr>(S, D, Attr);
5891 break;
Reid Kleckner7d6d2702014-05-01 03:16:47 +00005892 case AttributeList::AT_Thread:
5893 handleDeclspecThreadAttr(S, D, Attr);
5894 break;
David Majnemercd3ebfe2016-05-23 17:16:12 +00005895
Dmitry Polukhinbf17ecf2016-03-09 15:30:53 +00005896 case AttributeList::AT_AbiTag:
5897 handleAbiTagAttr(S, D, Attr);
5898 break;
Caitlin Sadowskiaac4d212011-07-28 17:21:07 +00005899
5900 // Thread safety attributes:
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00005901 case AttributeList::AT_AssertExclusiveLock:
5902 handleAssertExclusiveLockAttr(S, D, Attr);
5903 break;
5904 case AttributeList::AT_AssertSharedLock:
5905 handleAssertSharedLockAttr(S, D, Attr);
5906 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005907 case AttributeList::AT_GuardedVar:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005908 handleSimpleAttribute<GuardedVarAttr>(S, D, Attr);
5909 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005910 case AttributeList::AT_PtGuardedVar:
Michael Han3be3b442012-07-23 18:48:41 +00005911 handlePtGuardedVarAttr(S, D, Attr);
Caitlin Sadowskiaac4d212011-07-28 17:21:07 +00005912 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005913 case AttributeList::AT_ScopedLockable:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005914 handleSimpleAttribute<ScopedLockableAttr>(S, D, Attr);
5915 break;
Peter Collingbourne915df992015-05-15 18:33:32 +00005916 case AttributeList::AT_NoSanitize:
5917 handleNoSanitizeAttr(S, D, Attr);
5918 break;
5919 case AttributeList::AT_NoSanitizeSpecific:
5920 handleNoSanitizeSpecificAttr(S, D, Attr);
Kostya Serebryany588d6ab2012-01-24 19:25:38 +00005921 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005922 case AttributeList::AT_NoThreadSafetyAnalysis:
Aaron Ballman6f9165a2013-11-27 15:24:06 +00005923 handleSimpleAttribute<NoThreadSafetyAnalysisAttr>(S, D, Attr);
Kostya Serebryany4c0fc992013-02-26 06:58:27 +00005924 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005925 case AttributeList::AT_GuardedBy:
Caitlin Sadowski63fa6672011-07-28 20:12:35 +00005926 handleGuardedByAttr(S, D, Attr);
5927 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005928 case AttributeList::AT_PtGuardedBy:
Michael Han3be3b442012-07-23 18:48:41 +00005929 handlePtGuardedByAttr(S, D, Attr);
Caitlin Sadowski63fa6672011-07-28 20:12:35 +00005930 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005931 case AttributeList::AT_ExclusiveTrylockFunction:
Michael Han3be3b442012-07-23 18:48:41 +00005932 handleExclusiveTrylockFunctionAttr(S, D, Attr);
Caitlin Sadowski63fa6672011-07-28 20:12:35 +00005933 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005934 case AttributeList::AT_LockReturned:
Caitlin Sadowski63fa6672011-07-28 20:12:35 +00005935 handleLockReturnedAttr(S, D, Attr);
5936 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005937 case AttributeList::AT_LocksExcluded:
Caitlin Sadowski63fa6672011-07-28 20:12:35 +00005938 handleLocksExcludedAttr(S, D, Attr);
5939 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005940 case AttributeList::AT_SharedTrylockFunction:
Michael Han3be3b442012-07-23 18:48:41 +00005941 handleSharedTrylockFunctionAttr(S, D, Attr);
Caitlin Sadowski63fa6672011-07-28 20:12:35 +00005942 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005943 case AttributeList::AT_AcquiredBefore:
Michael Han3be3b442012-07-23 18:48:41 +00005944 handleAcquiredBeforeAttr(S, D, Attr);
Caitlin Sadowski63fa6672011-07-28 20:12:35 +00005945 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005946 case AttributeList::AT_AcquiredAfter:
Michael Han3be3b442012-07-23 18:48:41 +00005947 handleAcquiredAfterAttr(S, D, Attr);
Caitlin Sadowski63fa6672011-07-28 20:12:35 +00005948 break;
Caitlin Sadowskiaac4d212011-07-28 17:21:07 +00005949
Aaron Ballmanefe348e2014-02-18 17:36:50 +00005950 // Capability analysis attributes.
5951 case AttributeList::AT_Capability:
5952 case AttributeList::AT_Lockable:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005953 handleCapabilityAttr(S, D, Attr);
5954 break;
Aaron Ballman9e9d1842014-02-21 21:05:14 +00005955 case AttributeList::AT_RequiresCapability:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005956 handleRequiresCapabilityAttr(S, D, Attr);
5957 break;
Aaron Ballman9e9d1842014-02-21 21:05:14 +00005958
5959 case AttributeList::AT_AssertCapability:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005960 handleAssertCapabilityAttr(S, D, Attr);
5961 break;
Aaron Ballman9e9d1842014-02-21 21:05:14 +00005962 case AttributeList::AT_AcquireCapability:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005963 handleAcquireCapabilityAttr(S, D, Attr);
5964 break;
Aaron Ballman9e9d1842014-02-21 21:05:14 +00005965 case AttributeList::AT_ReleaseCapability:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005966 handleReleaseCapabilityAttr(S, D, Attr);
5967 break;
Aaron Ballman9e9d1842014-02-21 21:05:14 +00005968 case AttributeList::AT_TryAcquireCapability:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005969 handleTryAcquireCapabilityAttr(S, D, Attr);
5970 break;
Aaron Ballmanefe348e2014-02-18 17:36:50 +00005971
DeLesley Hutchins8d41d992013-10-11 22:30:48 +00005972 // Consumed analysis attributes.
DeLesley Hutchins5a715c42013-08-30 22:56:34 +00005973 case AttributeList::AT_Consumable:
5974 handleConsumableAttr(S, D, Attr);
5975 break;
DeLesley Hutchinsf28bbec2014-01-14 00:36:53 +00005976 case AttributeList::AT_ConsumableAutoCast:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005977 handleSimpleAttribute<ConsumableAutoCastAttr>(S, D, Attr);
5978 break;
DeLesley Hutchinsf28bbec2014-01-14 00:36:53 +00005979 case AttributeList::AT_ConsumableSetOnRead:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005980 handleSimpleAttribute<ConsumableSetOnReadAttr>(S, D, Attr);
5981 break;
DeLesley Hutchins210791a2013-10-04 21:28:06 +00005982 case AttributeList::AT_CallableWhen:
5983 handleCallableWhenAttr(S, D, Attr);
DeLesley Hutchins48a31762013-08-12 21:20:55 +00005984 break;
DeLesley Hutchins69391772013-10-17 23:23:53 +00005985 case AttributeList::AT_ParamTypestate:
5986 handleParamTypestateAttr(S, D, Attr);
5987 break;
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00005988 case AttributeList::AT_ReturnTypestate:
5989 handleReturnTypestateAttr(S, D, Attr);
5990 break;
DeLesley Hutchins33a29342013-10-11 23:03:26 +00005991 case AttributeList::AT_SetTypestate:
5992 handleSetTypestateAttr(S, D, Attr);
5993 break;
Chris Wailes9385f9f2013-10-29 20:28:41 +00005994 case AttributeList::AT_TestTypestate:
5995 handleTestTypestateAttr(S, D, Attr);
DeLesley Hutchins33a29342013-10-11 23:03:26 +00005996 break;
DeLesley Hutchins48a31762013-08-12 21:20:55 +00005997
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00005998 // Type safety attributes.
5999 case AttributeList::AT_ArgumentWithTypeTag:
6000 handleArgumentWithTypeTagAttr(S, D, Attr);
6001 break;
6002 case AttributeList::AT_TypeTagForDatatype:
6003 handleTypeTagForDatatypeAttr(S, D, Attr);
6004 break;
Pirama Arumuga Nainare5d2d712016-06-10 21:51:18 +00006005 case AttributeList::AT_RenderScriptKernel:
6006 handleSimpleAttribute<RenderScriptKernelAttr>(S, D, Attr);
Pirama Arumuga Nainar8b788d02016-06-09 23:34:20 +00006007 break;
Aaron Ballman7d2aecb2016-07-13 22:32:15 +00006008 // XRay attributes.
6009 case AttributeList::AT_XRayInstrument:
6010 handleSimpleAttribute<XRayInstrumentAttr>(S, D, Attr);
6011 break;
Chris Lattnerb632a6e2008-06-29 00:43:07 +00006012 }
6013}
6014
6015/// ProcessDeclAttributeList - Apply all the decl attributes in the specified
6016/// attribute list to the specified decl, ignoring any type attributes.
Eric Christopherbc638a82010-12-01 22:13:54 +00006017void Sema::ProcessDeclAttributeList(Scope *S, Decl *D,
Peter Collingbourneb331b262011-01-21 02:08:45 +00006018 const AttributeList *AttrList,
Richard Smith10876ef2013-01-17 01:30:42 +00006019 bool IncludeCXX11Attributes) {
6020 for (const AttributeList* l = AttrList; l; l = l->getNext())
Richard Smithf8a75c32013-08-29 00:47:48 +00006021 ProcessDeclAttribute(*this, S, D, *l, IncludeCXX11Attributes);
Rafael Espindolac18086a2010-02-23 22:00:30 +00006022
Joey Gouly2cd9db12013-12-13 16:15:28 +00006023 // FIXME: We should be able to handle these cases in TableGen.
Rafael Espindolac18086a2010-02-23 22:00:30 +00006024 // GCC accepts
6025 // static int a9 __attribute__((weakref));
6026 // but that looks really pointless. We reject it.
Richard Smithf8a75c32013-08-29 00:47:48 +00006027 if (D->hasAttr<WeakRefAttr>() && !D->hasAttr<AliasAttr>()) {
Aaron Ballman9f6fec42014-01-02 23:02:01 +00006028 Diag(AttrList->getLoc(), diag::err_attribute_weakref_without_alias)
6029 << cast<NamedDecl>(D);
Rafael Espindolab3069002013-01-16 23:49:06 +00006030 D->dropAttr<WeakRefAttr>();
Rafael Espindolac18086a2010-02-23 22:00:30 +00006031 return;
Chris Lattnerb632a6e2008-06-29 00:43:07 +00006032 }
Joey Gouly2cd9db12013-12-13 16:15:28 +00006033
Aaron Ballmanbe243a72014-12-04 22:45:31 +00006034 // FIXME: We should be able to handle this in TableGen as well. It would be
6035 // good to have a way to specify "these attributes must appear as a group",
6036 // for these. Additionally, it would be good to have a way to specify "these
6037 // attribute must never appear as a group" for attributes like cold and hot.
Joey Gouly2cd9db12013-12-13 16:15:28 +00006038 if (!D->hasAttr<OpenCLKernelAttr>()) {
6039 // These attributes cannot be applied to a non-kernel function.
Aaron Ballman3e424b52013-12-26 18:30:57 +00006040 if (Attr *A = D->getAttr<ReqdWorkGroupSizeAttr>()) {
Matt Arsenaultb9e9dc52014-12-05 18:03:58 +00006041 // FIXME: This emits a different error message than
6042 // diag::err_attribute_wrong_decl_type + ExpectedKernelFunction.
Aaron Ballman3e424b52013-12-26 18:30:57 +00006043 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
Joey Gouly2cd9db12013-12-13 16:15:28 +00006044 D->setInvalidDecl();
Matt Arsenault43cfcbc2014-12-05 18:03:55 +00006045 } else if (Attr *A = D->getAttr<WorkGroupSizeHintAttr>()) {
Aaron Ballman3e424b52013-12-26 18:30:57 +00006046 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
Joey Gouly2cd9db12013-12-13 16:15:28 +00006047 D->setInvalidDecl();
Matt Arsenault43cfcbc2014-12-05 18:03:55 +00006048 } else if (Attr *A = D->getAttr<VecTypeHintAttr>()) {
Aaron Ballman3e424b52013-12-26 18:30:57 +00006049 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
Joey Gouly2cd9db12013-12-13 16:15:28 +00006050 D->setInvalidDecl();
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00006051 } else if (Attr *A = D->getAttr<AMDGPUFlatWorkGroupSizeAttr>()) {
6052 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
6053 << A << ExpectedKernelFunction;
6054 D->setInvalidDecl();
6055 } else if (Attr *A = D->getAttr<AMDGPUWavesPerEUAttr>()) {
Matt Arsenaultb9e9dc52014-12-05 18:03:58 +00006056 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
6057 << A << ExpectedKernelFunction;
6058 D->setInvalidDecl();
6059 } else if (Attr *A = D->getAttr<AMDGPUNumSGPRAttr>()) {
6060 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
6061 << A << ExpectedKernelFunction;
6062 D->setInvalidDecl();
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00006063 } else if (Attr *A = D->getAttr<AMDGPUNumVGPRAttr>()) {
6064 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
6065 << A << ExpectedKernelFunction;
6066 D->setInvalidDecl();
Joey Gouly2cd9db12013-12-13 16:15:28 +00006067 }
6068 }
Chris Lattnerb632a6e2008-06-29 00:43:07 +00006069}
6070
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00006071// Annotation attributes are the only attributes allowed after an access
6072// specifier.
6073bool Sema::ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
6074 const AttributeList *AttrList) {
6075 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006076 if (l->getKind() == AttributeList::AT_Annotate) {
David Majnemer706f3152014-12-14 01:05:01 +00006077 ProcessDeclAttribute(*this, nullptr, ASDecl, *l, l->isCXX11Attribute());
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00006078 } else {
6079 Diag(l->getLoc(), diag::err_only_annotate_after_access_spec);
6080 return true;
6081 }
6082 }
6083
6084 return false;
6085}
6086
John McCall42856de2011-10-01 05:17:03 +00006087/// checkUnusedDeclAttributes - Check a list of attributes to see if it
6088/// contains any decl attributes that we should warn about.
6089static void checkUnusedDeclAttributes(Sema &S, const AttributeList *A) {
6090 for ( ; A; A = A->getNext()) {
6091 // Only warn if the attribute is an unignored, non-type attribute.
Richard Smith810ad3e2013-01-29 10:02:16 +00006092 if (A->isUsedAsTypeAttr() || A->isInvalid()) continue;
John McCall42856de2011-10-01 05:17:03 +00006093 if (A->getKind() == AttributeList::IgnoredAttribute) continue;
6094
6095 if (A->getKind() == AttributeList::UnknownAttribute) {
6096 S.Diag(A->getLoc(), diag::warn_unknown_attribute_ignored)
6097 << A->getName() << A->getRange();
6098 } else {
6099 S.Diag(A->getLoc(), diag::warn_attribute_not_on_decl)
6100 << A->getName() << A->getRange();
6101 }
6102 }
6103}
6104
6105/// checkUnusedDeclAttributes - Given a declarator which is not being
6106/// used to build a declaration, complain about any decl attributes
6107/// which might be lying around on it.
6108void Sema::checkUnusedDeclAttributes(Declarator &D) {
6109 ::checkUnusedDeclAttributes(*this, D.getDeclSpec().getAttributes().getList());
6110 ::checkUnusedDeclAttributes(*this, D.getAttributes());
6111 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i)
6112 ::checkUnusedDeclAttributes(*this, D.getTypeObject(i).getAttrs());
6113}
6114
Ryan Flynn7d470f32009-07-30 03:15:39 +00006115/// DeclClonePragmaWeak - clone existing decl (maybe definition),
James Dennett634962f2012-06-14 21:40:34 +00006116/// \#pragma weak needs a non-definition decl and source may not have one.
Eli Friedmance3e2c82011-09-07 04:05:06 +00006117NamedDecl * Sema::DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
6118 SourceLocation Loc) {
Ryan Flynnd963a492009-07-31 02:52:19 +00006119 assert(isa<FunctionDecl>(ND) || isa<VarDecl>(ND));
Craig Topperc3ec1492014-05-26 06:22:03 +00006120 NamedDecl *NewD = nullptr;
Ryan Flynn7d470f32009-07-30 03:15:39 +00006121 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
Alexander Kornienko061900f2015-12-03 11:37:28 +00006122 FunctionDecl *NewFD;
6123 // FIXME: Missing call to CheckFunctionDeclaration().
Eli Friedmance3e2c82011-09-07 04:05:06 +00006124 // FIXME: Mangling?
6125 // FIXME: Is the qualifier info correct?
6126 // FIXME: Is the DeclContext correct?
Alexander Kornienko061900f2015-12-03 11:37:28 +00006127 NewFD = FunctionDecl::Create(FD->getASTContext(), FD->getDeclContext(),
6128 Loc, Loc, DeclarationName(II),
6129 FD->getType(), FD->getTypeSourceInfo(),
6130 SC_None, false/*isInlineSpecified*/,
6131 FD->hasPrototype(),
6132 false/*isConstexprSpecified*/);
Eli Friedmance3e2c82011-09-07 04:05:06 +00006133 NewD = NewFD;
6134
6135 if (FD->getQualifier())
Douglas Gregor14454802011-02-25 02:25:35 +00006136 NewFD->setQualifierInfo(FD->getQualifierLoc());
Eli Friedmance3e2c82011-09-07 04:05:06 +00006137
6138 // Fake up parameter variables; they are declared as if this were
6139 // a typedef.
6140 QualType FDTy = FD->getType();
6141 if (const FunctionProtoType *FT = FDTy->getAs<FunctionProtoType>()) {
6142 SmallVector<ParmVarDecl*, 16> Params;
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00006143 for (const auto &AI : FT->param_types()) {
6144 ParmVarDecl *Param = BuildParmVarDeclForTypedef(NewFD, Loc, AI);
Eli Friedmance3e2c82011-09-07 04:05:06 +00006145 Param->setScopeInfo(0, Params.size());
6146 Params.push_back(Param);
6147 }
David Blaikie9c70e042011-09-21 18:16:56 +00006148 NewFD->setParams(Params);
John McCall3e11ebe2010-03-15 10:12:16 +00006149 }
Ryan Flynn7d470f32009-07-30 03:15:39 +00006150 } else if (VarDecl *VD = dyn_cast<VarDecl>(ND)) {
6151 NewD = VarDecl::Create(VD->getASTContext(), VD->getDeclContext(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00006152 VD->getInnerLocStart(), VD->getLocation(), II,
John McCallbcd03502009-12-07 02:54:59 +00006153 VD->getType(), VD->getTypeSourceInfo(),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00006154 VD->getStorageClass());
John McCall3e11ebe2010-03-15 10:12:16 +00006155 if (VD->getQualifier()) {
6156 VarDecl *NewVD = cast<VarDecl>(NewD);
Douglas Gregor14454802011-02-25 02:25:35 +00006157 NewVD->setQualifierInfo(VD->getQualifierLoc());
John McCall3e11ebe2010-03-15 10:12:16 +00006158 }
Ryan Flynn7d470f32009-07-30 03:15:39 +00006159 }
6160 return NewD;
6161}
6162
James Dennett634962f2012-06-14 21:40:34 +00006163/// DeclApplyPragmaWeak - A declaration (maybe definition) needs \#pragma weak
Ryan Flynn7d470f32009-07-30 03:15:39 +00006164/// applied to it, possibly with an alias.
Ryan Flynnd963a492009-07-31 02:52:19 +00006165void Sema::DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W) {
Chris Lattnere6eab982009-09-08 18:10:11 +00006166 if (W.getUsed()) return; // only do this once
6167 W.setUsed(true);
6168 if (W.getAlias()) { // clone decl, impersonate __attribute(weak,alias(...))
6169 IdentifierInfo *NDId = ND->getIdentifier();
Eli Friedmance3e2c82011-09-07 04:05:06 +00006170 NamedDecl *NewD = DeclClonePragmaWeak(ND, W.getAlias(), W.getLocation());
Aaron Ballman36a53502014-01-16 13:03:14 +00006171 NewD->addAttr(AliasAttr::CreateImplicit(Context, NDId->getName(),
6172 W.getLocation()));
6173 NewD->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation()));
Chris Lattnere6eab982009-09-08 18:10:11 +00006174 WeakTopLevelDecl.push_back(NewD);
6175 // FIXME: "hideous" code from Sema::LazilyCreateBuiltin
6176 // to insert Decl at TU scope, sorry.
6177 DeclContext *SavedContext = CurContext;
6178 CurContext = Context.getTranslationUnitDecl();
Argyrios Kyrtzidis0098a4b2014-03-09 05:15:28 +00006179 NewD->setDeclContext(CurContext);
6180 NewD->setLexicalDeclContext(CurContext);
Chris Lattnere6eab982009-09-08 18:10:11 +00006181 PushOnScopeChains(NewD, S);
6182 CurContext = SavedContext;
6183 } else { // just add weak to existing
Aaron Ballman36a53502014-01-16 13:03:14 +00006184 ND->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation()));
Ryan Flynn7d470f32009-07-30 03:15:39 +00006185 }
6186}
6187
Rafael Espindolade6a39f2013-03-02 21:41:48 +00006188void Sema::ProcessPragmaWeak(Scope *S, Decl *D) {
6189 // It's valid to "forward-declare" #pragma weak, in which case we
6190 // have to do this.
6191 LoadExternalWeakUndeclaredIdentifiers();
6192 if (!WeakUndeclaredIdentifiers.empty()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006193 NamedDecl *ND = nullptr;
Rafael Espindolade6a39f2013-03-02 21:41:48 +00006194 if (VarDecl *VD = dyn_cast<VarDecl>(D))
6195 if (VD->isExternC())
6196 ND = VD;
6197 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
6198 if (FD->isExternC())
6199 ND = FD;
6200 if (ND) {
6201 if (IdentifierInfo *Id = ND->getIdentifier()) {
Chandler Carruthf85d9822015-03-26 08:32:49 +00006202 auto I = WeakUndeclaredIdentifiers.find(Id);
Rafael Espindolade6a39f2013-03-02 21:41:48 +00006203 if (I != WeakUndeclaredIdentifiers.end()) {
6204 WeakInfo W = I->second;
6205 DeclApplyPragmaWeak(S, ND, W);
6206 WeakUndeclaredIdentifiers[Id] = W;
6207 }
6208 }
6209 }
6210 }
6211}
6212
Chris Lattner9e2aafe2008-06-29 00:23:49 +00006213/// ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in
6214/// it, apply them to D. This is a bit tricky because PD can have attributes
6215/// specified in many different places, and we need to find and apply them all.
Richard Smithf8a75c32013-08-29 00:47:48 +00006216void Sema::ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD) {
Chris Lattner9e2aafe2008-06-29 00:23:49 +00006217 // Apply decl attributes from the DeclSpec if present.
John McCall53fa7142010-12-24 02:08:15 +00006218 if (const AttributeList *Attrs = PD.getDeclSpec().getAttributes().getList())
Richard Smithf8a75c32013-08-29 00:47:48 +00006219 ProcessDeclAttributeList(S, D, Attrs);
Mike Stumpd3bb5572009-07-24 19:02:52 +00006220
Chris Lattner9e2aafe2008-06-29 00:23:49 +00006221 // Walk the declarator structure, applying decl attributes that were in a type
6222 // position to the decl itself. This handles cases like:
6223 // int *__attr__(x)** D;
6224 // when X is a decl attribute.
6225 for (unsigned i = 0, e = PD.getNumTypeObjects(); i != e; ++i)
6226 if (const AttributeList *Attrs = PD.getTypeObject(i).getAttrs())
Richard Smithf8a75c32013-08-29 00:47:48 +00006227 ProcessDeclAttributeList(S, D, Attrs, /*IncludeCXX11Attributes=*/false);
Mike Stumpd3bb5572009-07-24 19:02:52 +00006228
Chris Lattner9e2aafe2008-06-29 00:23:49 +00006229 // Finally, apply any attributes on the decl itself.
6230 if (const AttributeList *Attrs = PD.getAttributes())
Richard Smithf8a75c32013-08-29 00:47:48 +00006231 ProcessDeclAttributeList(S, D, Attrs);
Chris Lattner9e2aafe2008-06-29 00:23:49 +00006232}
John McCall28a6aea2009-11-04 02:18:39 +00006233
John McCall31168b02011-06-15 23:02:42 +00006234/// Is the given declaration allowed to use a forbidden type?
John McCallb61e14e2015-10-27 04:54:50 +00006235/// If so, it'll still be annotated with an attribute that makes it
6236/// illegal to actually use.
6237static bool isForbiddenTypeAllowed(Sema &S, Decl *decl,
6238 const DelayedDiagnostic &diag,
John McCallc6af8c62015-10-28 05:03:19 +00006239 UnavailableAttr::ImplicitReason &reason) {
John McCall31168b02011-06-15 23:02:42 +00006240 // Private ivars are always okay. Unfortunately, people don't
6241 // always properly make their ivars private, even in system headers.
6242 // Plus we need to make fields okay, too.
Fariborz Jahanian6d5d6a22011-09-26 21:23:35 +00006243 if (!isa<FieldDecl>(decl) && !isa<ObjCPropertyDecl>(decl) &&
6244 !isa<FunctionDecl>(decl))
John McCall31168b02011-06-15 23:02:42 +00006245 return false;
6246
John McCallc6af8c62015-10-28 05:03:19 +00006247 // Silently accept unsupported uses of __weak in both user and system
6248 // declarations when it's been disabled, for ease of integration with
6249 // -fno-objc-arc files. We do have to take some care against attempts
6250 // to define such things; for now, we've only done that for ivars
6251 // and properties.
6252 if ((isa<ObjCIvarDecl>(decl) || isa<ObjCPropertyDecl>(decl))) {
6253 if (diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_disabled ||
6254 diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_no_runtime) {
6255 reason = UnavailableAttr::IR_ForbiddenWeak;
6256 return true;
6257 }
John McCallb61e14e2015-10-27 04:54:50 +00006258 }
6259
John McCallc6af8c62015-10-28 05:03:19 +00006260 // Allow all sorts of things in system headers.
6261 if (S.Context.getSourceManager().isInSystemHeader(decl->getLocation())) {
6262 // Currently, all the failures dealt with this way are due to ARC
6263 // restrictions.
6264 reason = UnavailableAttr::IR_ARCForbiddenType;
6265 return true;
John McCallb61e14e2015-10-27 04:54:50 +00006266 }
6267
6268 return false;
John McCall31168b02011-06-15 23:02:42 +00006269}
6270
6271/// Handle a delayed forbidden-type diagnostic.
6272static void handleDelayedForbiddenType(Sema &S, DelayedDiagnostic &diag,
6273 Decl *decl) {
John McCallc6af8c62015-10-28 05:03:19 +00006274 auto reason = UnavailableAttr::IR_None;
6275 if (decl && isForbiddenTypeAllowed(S, decl, diag, reason)) {
6276 assert(reason && "didn't set reason?");
6277 decl->addAttr(UnavailableAttr::CreateImplicit(S.Context, "", reason,
6278 diag.Loc));
John McCall31168b02011-06-15 23:02:42 +00006279 return;
6280 }
David Blaikiebbafb8a2012-03-11 07:00:24 +00006281 if (S.getLangOpts().ObjCAutoRefCount)
Fariborz Jahanianed1933b2011-10-03 22:11:57 +00006282 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(decl)) {
Benjamin Kramer474261a2012-06-02 10:20:41 +00006283 // FIXME: we may want to suppress diagnostics for all
Fariborz Jahanianed1933b2011-10-03 22:11:57 +00006284 // kind of forbidden type messages on unavailable functions.
6285 if (FD->hasAttr<UnavailableAttr>() &&
6286 diag.getForbiddenTypeDiagnostic() ==
6287 diag::err_arc_array_param_no_ownership) {
6288 diag.Triggered = true;
6289 return;
6290 }
6291 }
John McCall31168b02011-06-15 23:02:42 +00006292
6293 S.Diag(diag.Loc, diag.getForbiddenTypeDiagnostic())
6294 << diag.getForbiddenTypeOperand() << diag.getForbiddenTypeArgument();
6295 diag.Triggered = true;
6296}
6297
Aaron Ballmanfb237522014-10-15 15:37:51 +00006298static bool isDeclDeprecated(Decl *D) {
6299 do {
6300 if (D->isDeprecated())
6301 return true;
6302 // A category implicitly has the availability of the interface.
6303 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(D))
Ben Langmuirc91ac9e2015-01-20 20:41:36 +00006304 if (const ObjCInterfaceDecl *Interface = CatD->getClassInterface())
6305 return Interface->isDeprecated();
Aaron Ballmanfb237522014-10-15 15:37:51 +00006306 } while ((D = cast_or_null<Decl>(D->getDeclContext())));
6307 return false;
6308}
6309
6310static bool isDeclUnavailable(Decl *D) {
6311 do {
6312 if (D->isUnavailable())
6313 return true;
6314 // A category implicitly has the availability of the interface.
6315 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(D))
Ben Langmuirc91ac9e2015-01-20 20:41:36 +00006316 if (const ObjCInterfaceDecl *Interface = CatD->getClassInterface())
6317 return Interface->isUnavailable();
Aaron Ballmanfb237522014-10-15 15:37:51 +00006318 } while ((D = cast_or_null<Decl>(D->getDeclContext())));
6319 return false;
6320}
6321
Manman Ren45b1ab12016-05-06 19:57:16 +00006322static const AvailabilityAttr *getAttrForPlatform(ASTContext &Context,
6323 const Decl *D) {
6324 // Check each AvailabilityAttr to find the one for this platform.
6325 for (const auto *A : D->attrs()) {
6326 if (const auto *Avail = dyn_cast<AvailabilityAttr>(A)) {
6327 // FIXME: this is copied from CheckAvailability. We should try to
6328 // de-duplicate.
6329
6330 // Check if this is an App Extension "platform", and if so chop off
6331 // the suffix for matching with the actual platform.
6332 StringRef ActualPlatform = Avail->getPlatform()->getName();
6333 StringRef RealizedPlatform = ActualPlatform;
6334 if (Context.getLangOpts().AppExt) {
6335 size_t suffix = RealizedPlatform.rfind("_app_extension");
6336 if (suffix != StringRef::npos)
6337 RealizedPlatform = RealizedPlatform.slice(0, suffix);
6338 }
6339
6340 StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
6341
6342 // Match the platform name.
6343 if (RealizedPlatform == TargetPlatform)
6344 return Avail;
6345 }
6346 }
6347 return nullptr;
6348}
6349
Erik Pilkington796a3e22016-08-05 22:59:03 +00006350static void DoEmitAvailabilityWarning(Sema &S, AvailabilityResult K,
Aaron Ballmanfb237522014-10-15 15:37:51 +00006351 Decl *Ctx, const NamedDecl *D,
6352 StringRef Message, SourceLocation Loc,
6353 const ObjCInterfaceDecl *UnknownObjCClass,
6354 const ObjCPropertyDecl *ObjCProperty,
6355 bool ObjCPropertyAccess) {
6356 // Diagnostics for deprecated or unavailable.
6357 unsigned diag, diag_message, diag_fwdclass_message;
John McCallb61e14e2015-10-27 04:54:50 +00006358 unsigned diag_available_here = diag::note_availability_specified_here;
Aaron Ballmanfb237522014-10-15 15:37:51 +00006359
6360 // Matches 'diag::note_property_attribute' options.
6361 unsigned property_note_select;
6362
6363 // Matches diag::note_availability_specified_here.
6364 unsigned available_here_select_kind;
6365
6366 // Don't warn if our current context is deprecated or unavailable.
6367 switch (K) {
Erik Pilkington796a3e22016-08-05 22:59:03 +00006368 case AR_Deprecated:
Jordan Rosed17c03e2015-04-30 17:20:35 +00006369 if (isDeclDeprecated(Ctx) || isDeclUnavailable(Ctx))
Aaron Ballmanfb237522014-10-15 15:37:51 +00006370 return;
6371 diag = !ObjCPropertyAccess ? diag::warn_deprecated
6372 : diag::warn_property_method_deprecated;
6373 diag_message = diag::warn_deprecated_message;
6374 diag_fwdclass_message = diag::warn_deprecated_fwdclass_message;
6375 property_note_select = /* deprecated */ 0;
6376 available_here_select_kind = /* deprecated */ 2;
6377 break;
6378
Erik Pilkington796a3e22016-08-05 22:59:03 +00006379 case AR_Unavailable:
Aaron Ballmanfb237522014-10-15 15:37:51 +00006380 if (isDeclUnavailable(Ctx))
6381 return;
6382 diag = !ObjCPropertyAccess ? diag::err_unavailable
6383 : diag::err_property_method_unavailable;
6384 diag_message = diag::err_unavailable_message;
6385 diag_fwdclass_message = diag::warn_unavailable_fwdclass_message;
6386 property_note_select = /* unavailable */ 1;
6387 available_here_select_kind = /* unavailable */ 0;
John McCallb61e14e2015-10-27 04:54:50 +00006388
John McCallc6af8c62015-10-28 05:03:19 +00006389 if (auto attr = D->getAttr<UnavailableAttr>()) {
6390 if (attr->isImplicit() && attr->getImplicitReason()) {
6391 // Most of these failures are due to extra restrictions in ARC;
6392 // reflect that in the primary diagnostic when applicable.
6393 auto flagARCError = [&] {
6394 if (S.getLangOpts().ObjCAutoRefCount &&
6395 S.getSourceManager().isInSystemHeader(D->getLocation()))
6396 diag = diag::err_unavailable_in_arc;
6397 };
6398
6399 switch (attr->getImplicitReason()) {
6400 case UnavailableAttr::IR_None: break;
6401
6402 case UnavailableAttr::IR_ARCForbiddenType:
6403 flagARCError();
6404 diag_available_here = diag::note_arc_forbidden_type;
6405 break;
6406
6407 case UnavailableAttr::IR_ForbiddenWeak:
6408 if (S.getLangOpts().ObjCWeakRuntime)
6409 diag_available_here = diag::note_arc_weak_disabled;
6410 else
6411 diag_available_here = diag::note_arc_weak_no_runtime;
6412 break;
6413
6414 case UnavailableAttr::IR_ARCForbiddenConversion:
6415 flagARCError();
6416 diag_available_here = diag::note_performs_forbidden_arc_conversion;
6417 break;
6418
6419 case UnavailableAttr::IR_ARCInitReturnsUnrelated:
6420 flagARCError();
6421 diag_available_here = diag::note_arc_init_returns_unrelated;
6422 break;
6423
6424 case UnavailableAttr::IR_ARCFieldWithOwnership:
6425 flagARCError();
6426 diag_available_here = diag::note_arc_field_with_ownership;
6427 break;
6428 }
6429 }
John McCallb61e14e2015-10-27 04:54:50 +00006430 }
Aaron Ballmanfb237522014-10-15 15:37:51 +00006431 break;
6432
Erik Pilkington796a3e22016-08-05 22:59:03 +00006433 case AR_NotYetIntroduced:
Erik Pilkington5cd57172016-08-16 17:44:11 +00006434 assert(!S.getCurFunctionOrMethodDecl() &&
6435 "Function-level partial availablity should not be diagnosed here!");
6436
Nico Weber0055a192015-03-19 19:18:22 +00006437 diag = diag::warn_partial_availability;
6438 diag_message = diag::warn_partial_message;
6439 diag_fwdclass_message = diag::warn_partial_fwdclass_message;
6440 property_note_select = /* partial */ 2;
6441 available_here_select_kind = /* partial */ 3;
6442 break;
Erik Pilkington796a3e22016-08-05 22:59:03 +00006443
6444 case AR_Available:
6445 llvm_unreachable("Warning for availability of available declaration?");
Aaron Ballmanfb237522014-10-15 15:37:51 +00006446 }
6447
Manman Renc7890fe2016-03-16 18:50:49 +00006448 CharSourceRange UseRange;
6449 StringRef Replacement;
Erik Pilkington796a3e22016-08-05 22:59:03 +00006450 if (K == AR_Deprecated) {
Manman Renc7890fe2016-03-16 18:50:49 +00006451 if (auto attr = D->getAttr<DeprecatedAttr>())
6452 Replacement = attr->getReplacement();
Manman Ren45b1ab12016-05-06 19:57:16 +00006453 if (auto attr = getAttrForPlatform(S.Context, D))
Manman Ren75bc6762016-03-21 17:30:55 +00006454 Replacement = attr->getReplacement();
Manman Renc7890fe2016-03-16 18:50:49 +00006455
6456 if (!Replacement.empty())
6457 UseRange =
6458 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
6459 }
6460
Aaron Ballmanfb237522014-10-15 15:37:51 +00006461 if (!Message.empty()) {
Manman Renc7890fe2016-03-16 18:50:49 +00006462 S.Diag(Loc, diag_message) << D << Message
6463 << (UseRange.isValid() ?
6464 FixItHint::CreateReplacement(UseRange, Replacement) : FixItHint());
Aaron Ballmanfb237522014-10-15 15:37:51 +00006465 if (ObjCProperty)
6466 S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute)
6467 << ObjCProperty->getDeclName() << property_note_select;
6468 } else if (!UnknownObjCClass) {
Manman Renc7890fe2016-03-16 18:50:49 +00006469 S.Diag(Loc, diag) << D
6470 << (UseRange.isValid() ?
6471 FixItHint::CreateReplacement(UseRange, Replacement) : FixItHint());
Aaron Ballmanfb237522014-10-15 15:37:51 +00006472 if (ObjCProperty)
6473 S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute)
6474 << ObjCProperty->getDeclName() << property_note_select;
6475 } else {
Manman Renc7890fe2016-03-16 18:50:49 +00006476 S.Diag(Loc, diag_fwdclass_message) << D
6477 << (UseRange.isValid() ?
6478 FixItHint::CreateReplacement(UseRange, Replacement) : FixItHint());
Aaron Ballmanfb237522014-10-15 15:37:51 +00006479 S.Diag(UnknownObjCClass->getLocation(), diag::note_forward_class);
6480 }
6481
Manman Ren45b1ab12016-05-06 19:57:16 +00006482 // The declaration can have multiple availability attributes, we are looking
6483 // at one of them.
6484 const AvailabilityAttr *A = getAttrForPlatform(S.Context, D);
6485 if (A && A->isInherited()) {
6486 for (const Decl *Redecl = D->getMostRecentDecl(); Redecl;
6487 Redecl = Redecl->getPreviousDecl()) {
6488 const AvailabilityAttr *AForRedecl = getAttrForPlatform(S.Context,
6489 Redecl);
6490 if (AForRedecl && !AForRedecl->isInherited()) {
6491 // If D is a declaration with inherited attributes, the note should
6492 // point to the declaration with actual attributes.
6493 S.Diag(Redecl->getLocation(), diag_available_here) << D
6494 << available_here_select_kind;
6495 break;
6496 }
6497 }
6498 }
6499 else
6500 S.Diag(D->getLocation(), diag_available_here)
6501 << D << available_here_select_kind;
6502
Erik Pilkington796a3e22016-08-05 22:59:03 +00006503 if (K == AR_NotYetIntroduced)
Nico Weber0055a192015-03-19 19:18:22 +00006504 S.Diag(Loc, diag::note_partial_availability_silence) << D;
Aaron Ballmanfb237522014-10-15 15:37:51 +00006505}
6506
6507static void handleDelayedAvailabilityCheck(Sema &S, DelayedDiagnostic &DD,
6508 Decl *Ctx) {
Nico Weber0055a192015-03-19 19:18:22 +00006509 assert(DD.Kind == DelayedDiagnostic::Deprecation ||
Manman Rend8039df2016-02-22 04:47:24 +00006510 DD.Kind == DelayedDiagnostic::Unavailable);
Erik Pilkington796a3e22016-08-05 22:59:03 +00006511 AvailabilityResult AR = DD.Kind == DelayedDiagnostic::Deprecation
6512 ? AR_Deprecated
6513 : AR_Unavailable;
Aaron Ballmanfb237522014-10-15 15:37:51 +00006514 DD.Triggered = true;
Nico Weber0055a192015-03-19 19:18:22 +00006515 DoEmitAvailabilityWarning(
Erik Pilkington796a3e22016-08-05 22:59:03 +00006516 S, AR, Ctx, DD.getDeprecationDecl(), DD.getDeprecationMessage(), DD.Loc,
Nico Weber0055a192015-03-19 19:18:22 +00006517 DD.getUnknownObjCClass(), DD.getObjCProperty(), false);
Aaron Ballmanfb237522014-10-15 15:37:51 +00006518}
6519
John McCall2ec85372012-05-07 06:16:41 +00006520void Sema::PopParsingDeclaration(ParsingDeclState state, Decl *decl) {
6521 assert(DelayedDiagnostics.getCurrentPool());
John McCall6347b682012-05-07 06:16:58 +00006522 DelayedDiagnosticPool &poppedPool = *DelayedDiagnostics.getCurrentPool();
John McCall2ec85372012-05-07 06:16:41 +00006523 DelayedDiagnostics.popWithoutEmitting(state);
John McCallc1465822011-02-14 07:13:47 +00006524
John McCall2ec85372012-05-07 06:16:41 +00006525 // When delaying diagnostics to run in the context of a parsed
6526 // declaration, we only want to actually emit anything if parsing
6527 // succeeds.
6528 if (!decl) return;
John McCallc1465822011-02-14 07:13:47 +00006529
John McCall2ec85372012-05-07 06:16:41 +00006530 // We emit all the active diagnostics in this pool or any of its
6531 // parents. In general, we'll get one pool for the decl spec
6532 // and a child pool for each declarator; in a decl group like:
6533 // deprecated_typedef foo, *bar, baz();
6534 // only the declarator pops will be passed decls. This is correct;
6535 // we really do need to consider delayed diagnostics from the decl spec
6536 // for each of the different declarations.
John McCall6347b682012-05-07 06:16:58 +00006537 const DelayedDiagnosticPool *pool = &poppedPool;
John McCall2ec85372012-05-07 06:16:41 +00006538 do {
John McCall6347b682012-05-07 06:16:58 +00006539 for (DelayedDiagnosticPool::pool_iterator
John McCall2ec85372012-05-07 06:16:41 +00006540 i = pool->pool_begin(), e = pool->pool_end(); i != e; ++i) {
6541 // This const_cast is a bit lame. Really, Triggered should be mutable.
6542 DelayedDiagnostic &diag = const_cast<DelayedDiagnostic&>(*i);
John McCallc1465822011-02-14 07:13:47 +00006543 if (diag.Triggered)
John McCall86121512010-01-27 03:50:35 +00006544 continue;
6545
John McCallc1465822011-02-14 07:13:47 +00006546 switch (diag.Kind) {
John McCall86121512010-01-27 03:50:35 +00006547 case DelayedDiagnostic::Deprecation:
Ted Kremenekb79ee572013-12-18 23:30:06 +00006548 case DelayedDiagnostic::Unavailable:
6549 // Don't bother giving deprecation/unavailable diagnostics if
6550 // the decl is invalid.
John McCall18a962b2012-01-26 20:04:03 +00006551 if (!decl->isInvalidDecl())
Aaron Ballmanfb237522014-10-15 15:37:51 +00006552 handleDelayedAvailabilityCheck(*this, diag, decl);
John McCall86121512010-01-27 03:50:35 +00006553 break;
6554
6555 case DelayedDiagnostic::Access:
John McCall2ec85372012-05-07 06:16:41 +00006556 HandleDelayedAccessCheck(diag, decl);
John McCall86121512010-01-27 03:50:35 +00006557 break;
John McCall31168b02011-06-15 23:02:42 +00006558
6559 case DelayedDiagnostic::ForbiddenType:
John McCall2ec85372012-05-07 06:16:41 +00006560 handleDelayedForbiddenType(*this, diag, decl);
John McCall31168b02011-06-15 23:02:42 +00006561 break;
John McCall86121512010-01-27 03:50:35 +00006562 }
6563 }
John McCall2ec85372012-05-07 06:16:41 +00006564 } while ((pool = pool->getParent()));
John McCall28a6aea2009-11-04 02:18:39 +00006565}
6566
John McCall6347b682012-05-07 06:16:58 +00006567/// Given a set of delayed diagnostics, re-emit them as if they had
6568/// been delayed in the current context instead of in the given pool.
6569/// Essentially, this just moves them to the current pool.
6570void Sema::redelayDiagnostics(DelayedDiagnosticPool &pool) {
6571 DelayedDiagnosticPool *curPool = DelayedDiagnostics.getCurrentPool();
6572 assert(curPool && "re-emitting in undelayed context not supported");
6573 curPool->steal(pool);
6574}
6575
Erik Pilkington796a3e22016-08-05 22:59:03 +00006576void Sema::EmitAvailabilityWarning(AvailabilityResult AR,
Ted Kremenekb79ee572013-12-18 23:30:06 +00006577 NamedDecl *D, StringRef Message,
6578 SourceLocation Loc,
6579 const ObjCInterfaceDecl *UnknownObjCClass,
Fariborz Jahanian89ea9612014-06-16 17:25:41 +00006580 const ObjCPropertyDecl *ObjCProperty,
6581 bool ObjCPropertyAccess) {
John McCall28a6aea2009-11-04 02:18:39 +00006582 // Delay if we're currently parsing a declaration.
Erik Pilkington796a3e22016-08-05 22:59:03 +00006583 if (DelayedDiagnostics.shouldDelayDiagnostics() &&
6584 AR != AR_NotYetIntroduced) {
Nico Weber462fd1e2015-01-07 23:50:05 +00006585 DelayedDiagnostics.add(DelayedDiagnostic::makeAvailability(
Erik Pilkington796a3e22016-08-05 22:59:03 +00006586 AR, Loc, D, UnknownObjCClass, ObjCProperty, Message,
Nico Weber462fd1e2015-01-07 23:50:05 +00006587 ObjCPropertyAccess));
John McCall28a6aea2009-11-04 02:18:39 +00006588 return;
6589 }
6590
Ted Kremenekb79ee572013-12-18 23:30:06 +00006591 Decl *Ctx = cast<Decl>(getCurLexicalContext());
Erik Pilkington796a3e22016-08-05 22:59:03 +00006592 DoEmitAvailabilityWarning(*this, AR, Ctx, D, Message, Loc, UnknownObjCClass,
Nico Weber0055a192015-03-19 19:18:22 +00006593 ObjCProperty, ObjCPropertyAccess);
John McCall28a6aea2009-11-04 02:18:39 +00006594}
Erik Pilkington48c7cc92016-07-29 17:37:38 +00006595
6596VersionTuple Sema::getVersionForDecl(const Decl *D) const {
6597 assert(D && "Expected a declaration here!");
6598
6599 VersionTuple DeclVersion;
6600 if (const auto *AA = getAttrForPlatform(getASTContext(), D))
6601 DeclVersion = AA->getIntroduced();
6602
6603 const ObjCInterfaceDecl *Interface = nullptr;
6604
6605 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
6606 Interface = MD->getClassInterface();
6607 else if (const auto *ID = dyn_cast<ObjCImplementationDecl>(D))
6608 Interface = ID->getClassInterface();
6609
6610 if (Interface) {
6611 if (const auto *AA = getAttrForPlatform(getASTContext(), Interface))
6612 if (AA->getIntroduced() > DeclVersion)
6613 DeclVersion = AA->getIntroduced();
6614 }
6615
Erik Pilkington3f3fbf62016-08-01 20:19:49 +00006616 return std::max(DeclVersion, Context.getTargetInfo().getPlatformMinVersion());
Erik Pilkington48c7cc92016-07-29 17:37:38 +00006617}
Erik Pilkington5cd57172016-08-16 17:44:11 +00006618
6619namespace {
6620
6621/// \brief This class implements -Wunguarded-availability.
6622///
6623/// This is done with a traversal of the AST of a function that makes reference
6624/// to a partially available declaration. Whenever we encounter an \c if of the
6625/// form: \c if(@available(...)), we use the version from the condition to visit
6626/// the then statement.
6627class DiagnoseUnguardedAvailability
6628 : public RecursiveASTVisitor<DiagnoseUnguardedAvailability> {
6629 typedef RecursiveASTVisitor<DiagnoseUnguardedAvailability> Base;
6630
6631 Sema &SemaRef;
6632
6633 /// Stack of potentially nested 'if (@available(...))'s.
6634 SmallVector<VersionTuple, 8> AvailabilityStack;
6635
6636 void DiagnoseDeclAvailability(NamedDecl *D, SourceRange Range);
6637
6638public:
6639 DiagnoseUnguardedAvailability(Sema &SemaRef, VersionTuple BaseVersion)
6640 : SemaRef(SemaRef) {
6641 AvailabilityStack.push_back(BaseVersion);
6642 }
6643
6644 void IssueDiagnostics(Stmt *S) { TraverseStmt(S); }
6645
6646 bool TraverseIfStmt(IfStmt *If);
6647
6648 bool VisitObjCMessageExpr(ObjCMessageExpr *Msg) {
6649 if (ObjCMethodDecl *D = Msg->getMethodDecl())
6650 DiagnoseDeclAvailability(
6651 D, SourceRange(Msg->getSelectorStartLoc(), Msg->getLocEnd()));
6652 return true;
6653 }
6654
6655 bool VisitDeclRefExpr(DeclRefExpr *DRE) {
6656 DiagnoseDeclAvailability(DRE->getDecl(),
6657 SourceRange(DRE->getLocStart(), DRE->getLocEnd()));
6658 return true;
6659 }
6660
6661 bool VisitMemberExpr(MemberExpr *ME) {
6662 DiagnoseDeclAvailability(ME->getMemberDecl(),
6663 SourceRange(ME->getLocStart(), ME->getLocEnd()));
6664 return true;
6665 }
6666
6667 bool VisitTypeLoc(TypeLoc Ty);
6668};
6669
6670void DiagnoseUnguardedAvailability::DiagnoseDeclAvailability(
6671 NamedDecl *D, SourceRange Range) {
6672
6673 VersionTuple ContextVersion = AvailabilityStack.back();
6674 if (AvailabilityResult Result = SemaRef.ShouldDiagnoseAvailabilityOfDecl(
6675 D, ContextVersion, nullptr)) {
6676 // All other diagnostic kinds have already been handled in
6677 // DiagnoseAvailabilityOfDecl.
6678 if (Result != AR_NotYetIntroduced)
6679 return;
6680
6681 const AvailabilityAttr *AA = getAttrForPlatform(SemaRef.getASTContext(), D);
6682 VersionTuple Introduced = AA->getIntroduced();
6683
6684 SemaRef.Diag(Range.getBegin(), diag::warn_unguarded_availability)
6685 << Range << D
6686 << AvailabilityAttr::getPrettyPlatformName(
6687 SemaRef.getASTContext().getTargetInfo().getPlatformName())
6688 << Introduced.getAsString();
6689
6690 SemaRef.Diag(D->getLocation(), diag::note_availability_specified_here)
6691 << D << /* partial */ 3;
6692
6693 // FIXME: Replace this with a fixit diagnostic.
6694 SemaRef.Diag(Range.getBegin(), diag::note_unguarded_available_silence)
6695 << Range << D;
6696 }
6697}
6698
6699bool DiagnoseUnguardedAvailability::VisitTypeLoc(TypeLoc Ty) {
6700 const Type *TyPtr = Ty.getTypePtr();
6701 SourceRange Range{Ty.getBeginLoc(), Ty.getEndLoc()};
6702
6703 if (const TagType *TT = dyn_cast<TagType>(TyPtr)) {
6704 TagDecl *TD = TT->getDecl();
6705 DiagnoseDeclAvailability(TD, Range);
6706
6707 } else if (const TypedefType *TD = dyn_cast<TypedefType>(TyPtr)) {
6708 TypedefNameDecl *D = TD->getDecl();
6709 DiagnoseDeclAvailability(D, Range);
6710
6711 } else if (const auto *ObjCO = dyn_cast<ObjCObjectType>(TyPtr)) {
6712 if (NamedDecl *D = ObjCO->getInterface())
6713 DiagnoseDeclAvailability(D, Range);
6714 }
6715
6716 return true;
6717}
6718
6719bool DiagnoseUnguardedAvailability::TraverseIfStmt(IfStmt *If) {
6720 VersionTuple CondVersion;
6721 if (auto *E = dyn_cast<ObjCAvailabilityCheckExpr>(If->getCond())) {
6722 CondVersion = E->getVersion();
6723
6724 // If we're using the '*' case here or if this check is redundant, then we
6725 // use the enclosing version to check both branches.
6726 if (CondVersion.empty() || CondVersion <= AvailabilityStack.back())
6727 return Base::TraverseStmt(If->getThen()) &&
6728 Base::TraverseStmt(If->getElse());
6729 } else {
6730 // This isn't an availability checking 'if', we can just continue.
6731 return Base::TraverseIfStmt(If);
6732 }
6733
6734 AvailabilityStack.push_back(CondVersion);
6735 bool ShouldContinue = TraverseStmt(If->getThen());
6736 AvailabilityStack.pop_back();
6737
6738 return ShouldContinue && TraverseStmt(If->getElse());
6739}
6740
6741} // end anonymous namespace
6742
6743void Sema::DiagnoseUnguardedAvailabilityViolations(Decl *D) {
6744 Stmt *Body = nullptr;
6745
6746 if (auto *FD = D->getAsFunction()) {
6747 // FIXME: We only examine the pattern decl for availability violations now,
6748 // but we should also examine instantiated templates.
6749 if (FD->isTemplateInstantiation())
6750 return;
6751
6752 Body = FD->getBody();
6753 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(D))
6754 Body = MD->getBody();
6755
6756 assert(Body && "Need a body here!");
6757
6758 VersionTuple BaseVersion = getVersionForDecl(D);
6759 DiagnoseUnguardedAvailability(*this, BaseVersion).IssueDiagnostics(Body);
6760}