Coverage Report

Created: 2021-08-24 07:12

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Sema/SemaDeclAttr.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- SemaDeclAttr.cpp - Declaration Attribute Handling ----------------===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
//  This file implements decl-related attribute processing.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "clang/AST/ASTConsumer.h"
14
#include "clang/AST/ASTContext.h"
15
#include "clang/AST/ASTMutationListener.h"
16
#include "clang/AST/CXXInheritance.h"
17
#include "clang/AST/DeclCXX.h"
18
#include "clang/AST/DeclObjC.h"
19
#include "clang/AST/DeclTemplate.h"
20
#include "clang/AST/Expr.h"
21
#include "clang/AST/ExprCXX.h"
22
#include "clang/AST/Mangle.h"
23
#include "clang/AST/RecursiveASTVisitor.h"
24
#include "clang/AST/Type.h"
25
#include "clang/Basic/CharInfo.h"
26
#include "clang/Basic/DarwinSDKInfo.h"
27
#include "clang/Basic/SourceLocation.h"
28
#include "clang/Basic/SourceManager.h"
29
#include "clang/Basic/TargetBuiltins.h"
30
#include "clang/Basic/TargetInfo.h"
31
#include "clang/Lex/Preprocessor.h"
32
#include "clang/Sema/DeclSpec.h"
33
#include "clang/Sema/DelayedDiagnostic.h"
34
#include "clang/Sema/Initialization.h"
35
#include "clang/Sema/Lookup.h"
36
#include "clang/Sema/ParsedAttr.h"
37
#include "clang/Sema/Scope.h"
38
#include "clang/Sema/ScopeInfo.h"
39
#include "clang/Sema/SemaInternal.h"
40
#include "llvm/ADT/Optional.h"
41
#include "llvm/ADT/STLExtras.h"
42
#include "llvm/ADT/StringExtras.h"
43
#include "llvm/IR/Assumptions.h"
44
#include "llvm/MC/MCSectionMachO.h"
45
#include "llvm/Support/Error.h"
46
#include "llvm/Support/MathExtras.h"
47
#include "llvm/Support/raw_ostream.h"
48
49
using namespace clang;
50
using namespace sema;
51
52
namespace AttributeLangSupport {
53
  enum LANG {
54
    C,
55
    Cpp,
56
    ObjC
57
  };
58
} // end namespace AttributeLangSupport
59
60
//===----------------------------------------------------------------------===//
61
//  Helper functions
62
//===----------------------------------------------------------------------===//
63
64
/// isFunctionOrMethod - Return true if the given decl has function
65
/// type (function or function-typed variable) or an Objective-C
66
/// method.
67
66.6k
static bool isFunctionOrMethod(const Decl *D) {
68
66.6k
  return (D->getFunctionType() != nullptr) || 
isa<ObjCMethodDecl>(D)260
;
69
66.6k
}
70
71
/// Return true if the given decl has function type (function or
72
/// function-typed variable) or an Objective-C method or a block.
73
61.5k
static bool isFunctionOrMethodOrBlock(const Decl *D) {
74
61.5k
  return isFunctionOrMethod(D) || 
isa<BlockDecl>(D)1
;
75
61.5k
}
76
77
/// Return true if the given decl has a declarator that should have
78
/// been processed by Sema::GetTypeForDeclarator.
79
15.7k
static bool hasDeclarator(const Decl *D) {
80
  // In some sense, TypedefDecl really *ought* to be a DeclaratorDecl.
81
15.7k
  return isa<DeclaratorDecl>(D) || 
isa<BlockDecl>(D)364
||
isa<TypedefNameDecl>(D)355
||
82
15.7k
         
isa<ObjCPropertyDecl>(D)206
;
83
15.7k
}
84
85
/// hasFunctionProto - Return true if the given decl has a argument
86
/// information. This decl should have already passed
87
/// isFunctionOrMethod or isFunctionOrMethodOrBlock.
88
66.7k
static bool hasFunctionProto(const Decl *D) {
89
66.7k
  if (const FunctionType *FnTy = D->getFunctionType())
90
66.4k
    return isa<FunctionProtoType>(FnTy);
91
263
  return isa<ObjCMethodDecl>(D) || 
isa<BlockDecl>(D)9
;
92
66.7k
}
93
94
/// getFunctionOrMethodNumParams - Return number of function or method
95
/// parameters. It is an error to call this on a K&R function (use
96
/// hasFunctionProto first).
97
151k
static unsigned getFunctionOrMethodNumParams(const Decl *D) {
98
151k
  if (const FunctionType *FnTy = D->getFunctionType())
99
149k
    return cast<FunctionProtoType>(FnTy)->getNumParams();
100
2.93k
  if (const auto *BD = dyn_cast<BlockDecl>(D))
101
17
    return BD->getNumParams();
102
2.91k
  return cast<ObjCMethodDecl>(D)->param_size();
103
2.93k
}
104
105
static const ParmVarDecl *getFunctionOrMethodParam(const Decl *D,
106
54.8k
                                                   unsigned Idx) {
107
54.8k
  if (const auto *FD = dyn_cast<FunctionDecl>(D))
108
54.5k
    return FD->getParamDecl(Idx);
109
282
  if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
110
41
    return MD->getParamDecl(Idx);
111
241
  if (const auto *BD = dyn_cast<BlockDecl>(D))
112
16
    return BD->getParamDecl(Idx);
113
225
  return nullptr;
114
241
}
115
116
96.9k
static QualType getFunctionOrMethodParamType(const Decl *D, unsigned Idx) {
117
96.9k
  if (const FunctionType *FnTy = D->getFunctionType())
118
94.0k
    return cast<FunctionProtoType>(FnTy)->getParamType(Idx);
119
2.89k
  if (const auto *BD = dyn_cast<BlockDecl>(D))
120
8
    return BD->getParamDecl(Idx)->getType();
121
122
2.88k
  return cast<ObjCMethodDecl>(D)->parameters()[Idx]->getType();
123
2.89k
}
124
125
54.6k
static SourceRange getFunctionOrMethodParamRange(const Decl *D, unsigned Idx) {
126
54.6k
  if (auto *PVD = getFunctionOrMethodParam(D, Idx))
127
54.4k
    return PVD->getSourceRange();
128
225
  return SourceRange();
129
54.6k
}
130
131
17.9k
static QualType getFunctionOrMethodResultType(const Decl *D) {
132
17.9k
  if (const FunctionType *FnTy = D->getFunctionType())
133
17.7k
    return FnTy->getReturnType();
134
235
  return cast<ObjCMethodDecl>(D)->getReturnType();
135
17.9k
}
136
137
82
static SourceRange getFunctionOrMethodResultSourceRange(const Decl *D) {
138
82
  if (const auto *FD = dyn_cast<FunctionDecl>(D))
139
78
    return FD->getReturnTypeSourceRange();
140
4
  if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
141
4
    return MD->getReturnTypeSourceRange();
142
0
  return SourceRange();
143
4
}
144
145
79.2k
static bool isFunctionOrMethodVariadic(const Decl *D) {
146
79.2k
  if (const FunctionType *FnTy = D->getFunctionType())
147
77.0k
    return cast<FunctionProtoType>(FnTy)->isVariadic();
148
2.23k
  if (const auto *BD = dyn_cast<BlockDecl>(D))
149
6
    return BD->isVariadic();
150
2.23k
  return cast<ObjCMethodDecl>(D)->isVariadic();
151
2.23k
}
152
153
97.0k
static bool isInstanceMethod(const Decl *D) {
154
97.0k
  if (const auto *MethodDecl = dyn_cast<CXXMethodDecl>(D))
155
256
    return MethodDecl->isInstance();
156
96.8k
  return false;
157
97.0k
}
158
159
static inline bool isNSStringType(QualType T, ASTContext &Ctx,
160
5.18k
                                  bool AllowNSAttributedString = false) {
161
5.18k
  const auto *PT = T->getAs<ObjCObjectPointerType>();
162
5.18k
  if (!PT)
163
1.12k
    return false;
164
165
4.05k
  ObjCInterfaceDecl *Cls = PT->getObjectType()->getInterface();
166
4.05k
  if (!Cls)
167
0
    return false;
168
169
4.05k
  IdentifierInfo* ClsName = Cls->getIdentifier();
170
171
4.05k
  if (AllowNSAttributedString &&
172
4.05k
      
ClsName == &Ctx.Idents.get("NSAttributedString")3.39k
)
173
3
    return true;
174
  // FIXME: Should we walk the chain of classes?
175
4.05k
  return ClsName == &Ctx.Idents.get("NSString") ||
176
4.05k
         
ClsName == &Ctx.Idents.get("NSMutableString")0
;
177
4.05k
}
178
179
2.01k
static inline bool isCFStringType(QualType T, ASTContext &Ctx) {
180
2.01k
  const auto *PT = T->getAs<PointerType>();
181
2.01k
  if (!PT)
182
3
    return false;
183
184
2.01k
  const auto *RT = PT->getPointeeType()->getAs<RecordType>();
185
2.01k
  if (!RT)
186
454
    return false;
187
188
1.55k
  const RecordDecl *RD = RT->getDecl();
189
1.55k
  if (RD->getTagKind() != TTK_Struct)
190
0
    return false;
191
192
1.55k
  return RD->getIdentifier() == &Ctx.Idents.get("__CFString");
193
1.55k
}
194
195
314
static unsigned getNumAttributeArgs(const ParsedAttr &AL) {
196
  // FIXME: Include the type in the argument list.
197
314
  return AL.getNumArgs() + AL.hasParsedType();
198
314
}
199
200
/// A helper function to provide Attribute Location for the Attr types
201
/// AND the ParsedAttr.
202
template <typename AttrInfo>
203
static std::enable_if_t<std::is_base_of<Attr, AttrInfo>::value, SourceLocation>
204
23
getAttrLoc(const AttrInfo &AL) {
205
23
  return AL.getLocation();
206
23
}
SemaDeclAttr.cpp:std::__1::enable_if<std::is_base_of<clang::Attr, clang::AMDGPUFlatWorkGroupSizeAttr>::value, clang::SourceLocation>::type getAttrLoc<clang::AMDGPUFlatWorkGroupSizeAttr>(clang::AMDGPUFlatWorkGroupSizeAttr const&)
Line
Count
Source
204
9
getAttrLoc(const AttrInfo &AL) {
205
9
  return AL.getLocation();
206
9
}
SemaDeclAttr.cpp:std::__1::enable_if<std::is_base_of<clang::Attr, clang::AMDGPUWavesPerEUAttr>::value, clang::SourceLocation>::type getAttrLoc<clang::AMDGPUWavesPerEUAttr>(clang::AMDGPUWavesPerEUAttr const&)
Line
Count
Source
204
9
getAttrLoc(const AttrInfo &AL) {
205
9
  return AL.getLocation();
206
9
}
SemaDeclAttr.cpp:std::__1::enable_if<std::is_base_of<clang::Attr, clang::AllocAlignAttr>::value, clang::SourceLocation>::type getAttrLoc<clang::AllocAlignAttr>(clang::AllocAlignAttr const&)
Line
Count
Source
204
5
getAttrLoc(const AttrInfo &AL) {
205
5
  return AL.getLocation();
206
5
}
207
83
static SourceLocation getAttrLoc(const ParsedAttr &AL) { return AL.getLoc(); }
208
209
/// If Expr is a valid integer constant, get the value of the integer
210
/// expression and return success or failure. May output an error.
211
///
212
/// Negative argument is implicitly converted to unsigned, unless
213
/// \p StrictlyUnsigned is true.
214
template <typename AttrInfo>
215
static bool checkUInt32Argument(Sema &S, const AttrInfo &AI, const Expr *Expr,
216
                                uint32_t &Val, unsigned Idx = UINT_MAX,
217
1.11M
                                bool StrictlyUnsigned = false) {
218
1.11M
  Optional<llvm::APSInt> I = llvm::APSInt(32);
219
1.11M
  if (Expr->isTypeDependent() || Expr->isValueDependent() ||
220
1.11M
      !(I = Expr->getIntegerConstantExpr(S.Context))) {
221
32
    if (Idx != UINT_MAX)
222
22
      S.Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type)
223
22
          << &AI << Idx << AANT_ArgumentIntegerConstant
224
22
          << Expr->getSourceRange();
225
10
    else
226
10
      S.Diag(getAttrLoc(AI), diag::err_attribute_argument_type)
227
10
          << &AI << AANT_ArgumentIntegerConstant << Expr->getSourceRange();
228
32
    return false;
229
32
  }
230
231
1.11M
  if (!I->isIntN(32)) {
232
10
    S.Diag(Expr->getExprLoc(), diag::err_ice_too_large)
233
10
        << toString(*I, 10, false) << 32 << /* Unsigned */ 1;
234
10
    return false;
235
10
  }
236
237
1.11M
  if (StrictlyUnsigned && 
I->isSigned()89
&&
I->isNegative()89
) {
238
3
    S.Diag(getAttrLoc(AI), diag::err_attribute_requires_positive_integer)
239
3
        << &AI << /*non-negative*/ 1;
240
3
    return false;
241
3
  }
242
243
1.11M
  Val = (uint32_t)I->getZExtValue();
244
1.11M
  return true;
245
1.11M
}
SemaDeclAttr.cpp:bool checkUInt32Argument<clang::AMDGPUFlatWorkGroupSizeAttr>(clang::Sema&, clang::AMDGPUFlatWorkGroupSizeAttr const&, clang::Expr const*, unsigned int&, unsigned int, bool)
Line
Count
Source
217
205
                                bool StrictlyUnsigned = false) {
218
205
  Optional<llvm::APSInt> I = llvm::APSInt(32);
219
205
  if (Expr->isTypeDependent() || Expr->isValueDependent() ||
220
205
      !(I = Expr->getIntegerConstantExpr(S.Context))) {
221
9
    if (Idx != UINT_MAX)
222
9
      S.Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type)
223
9
          << &AI << Idx << AANT_ArgumentIntegerConstant
224
9
          << Expr->getSourceRange();
225
0
    else
226
0
      S.Diag(getAttrLoc(AI), diag::err_attribute_argument_type)
227
0
          << &AI << AANT_ArgumentIntegerConstant << Expr->getSourceRange();
228
9
    return false;
229
9
  }
230
231
196
  if (!I->isIntN(32)) {
232
3
    S.Diag(Expr->getExprLoc(), diag::err_ice_too_large)
233
3
        << toString(*I, 10, false) << 32 << /* Unsigned */ 1;
234
3
    return false;
235
3
  }
236
237
193
  if (StrictlyUnsigned && 
I->isSigned()0
&&
I->isNegative()0
) {
238
0
    S.Diag(getAttrLoc(AI), diag::err_attribute_requires_positive_integer)
239
0
        << &AI << /*non-negative*/ 1;
240
0
    return false;
241
0
  }
242
243
193
  Val = (uint32_t)I->getZExtValue();
244
193
  return true;
245
193
}
SemaDeclAttr.cpp:bool checkUInt32Argument<clang::AMDGPUWavesPerEUAttr>(clang::Sema&, clang::AMDGPUWavesPerEUAttr const&, clang::Expr const*, unsigned int&, unsigned int, bool)
Line
Count
Source
217
192
                                bool StrictlyUnsigned = false) {
218
192
  Optional<llvm::APSInt> I = llvm::APSInt(32);
219
192
  if (Expr->isTypeDependent() || Expr->isValueDependent() ||
220
192
      !(I = Expr->getIntegerConstantExpr(S.Context))) {
221
9
    if (Idx != UINT_MAX)
222
9
      S.Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type)
223
9
          << &AI << Idx << AANT_ArgumentIntegerConstant
224
9
          << Expr->getSourceRange();
225
0
    else
226
0
      S.Diag(getAttrLoc(AI), diag::err_attribute_argument_type)
227
0
          << &AI << AANT_ArgumentIntegerConstant << Expr->getSourceRange();
228
9
    return false;
229
9
  }
230
231
183
  if (!I->isIntN(32)) {
232
3
    S.Diag(Expr->getExprLoc(), diag::err_ice_too_large)
233
3
        << toString(*I, 10, false) << 32 << /* Unsigned */ 1;
234
3
    return false;
235
3
  }
236
237
180
  if (StrictlyUnsigned && 
I->isSigned()0
&&
I->isNegative()0
) {
238
0
    S.Diag(getAttrLoc(AI), diag::err_attribute_requires_positive_integer)
239
0
        << &AI << /*non-negative*/ 1;
240
0
    return false;
241
0
  }
242
243
180
  Val = (uint32_t)I->getZExtValue();
244
180
  return true;
245
180
}
SemaDeclAttr.cpp:bool checkUInt32Argument<clang::ParsedAttr>(clang::Sema&, clang::ParsedAttr const&, clang::Expr const*, unsigned int&, unsigned int, bool)
Line
Count
Source
217
1.11M
                                bool StrictlyUnsigned = false) {
218
1.11M
  Optional<llvm::APSInt> I = llvm::APSInt(32);
219
1.11M
  if (Expr->isTypeDependent() || Expr->isValueDependent() ||
220
1.11M
      !(I = Expr->getIntegerConstantExpr(S.Context))) {
221
14
    if (Idx != UINT_MAX)
222
4
      S.Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type)
223
4
          << &AI << Idx << AANT_ArgumentIntegerConstant
224
4
          << Expr->getSourceRange();
225
10
    else
226
10
      S.Diag(getAttrLoc(AI), diag::err_attribute_argument_type)
227
10
          << &AI << AANT_ArgumentIntegerConstant << Expr->getSourceRange();
228
14
    return false;
229
14
  }
230
231
1.11M
  if (!I->isIntN(32)) {
232
4
    S.Diag(Expr->getExprLoc(), diag::err_ice_too_large)
233
4
        << toString(*I, 10, false) << 32 << /* Unsigned */ 1;
234
4
    return false;
235
4
  }
236
237
1.11M
  if (StrictlyUnsigned && 
I->isSigned()89
&&
I->isNegative()89
) {
238
3
    S.Diag(getAttrLoc(AI), diag::err_attribute_requires_positive_integer)
239
3
        << &AI << /*non-negative*/ 1;
240
3
    return false;
241
3
  }
242
243
1.11M
  Val = (uint32_t)I->getZExtValue();
244
1.11M
  return true;
245
1.11M
}
246
247
/// Wrapper around checkUInt32Argument, with an extra check to be sure
248
/// that the result will fit into a regular (signed) int. All args have the same
249
/// purpose as they do in checkUInt32Argument.
250
template <typename AttrInfo>
251
static bool checkPositiveIntArgument(Sema &S, const AttrInfo &AI, const Expr *Expr,
252
5.80k
                                     int &Val, unsigned Idx = UINT_MAX) {
253
5.80k
  uint32_t UVal;
254
5.80k
  if (!checkUInt32Argument(S, AI, Expr, UVal, Idx))
255
2
    return false;
256
257
5.80k
  if (UVal > (uint32_t)std::numeric_limits<int>::max()) {
258
1
    llvm::APSInt I(32); // for toString
259
1
    I = UVal;
260
1
    S.Diag(Expr->getExprLoc(), diag::err_ice_too_large)
261
1
        << toString(I, 10, false) << 32 << /* Unsigned */ 0;
262
1
    return false;
263
1
  }
264
265
5.80k
  Val = UVal;
266
5.80k
  return true;
267
5.80k
}
268
269
/// Diagnose mutually exclusive attributes when present on a given
270
/// declaration. Returns true if diagnosed.
271
template <typename AttrTy>
272
66
static bool checkAttrMutualExclusion(Sema &S, Decl *D, const ParsedAttr &AL) {
273
66
  if (const auto *A = D->getAttr<AttrTy>()) {
274
3
    S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible) << AL << A;
275
3
    S.Diag(A->getLocation(), diag::note_conflicting_attribute);
276
3
    return true;
277
3
  }
278
63
  return false;
279
66
}
SemaDeclAttr.cpp:bool checkAttrMutualExclusion<clang::Mips16Attr>(clang::Sema&, clang::Decl*, clang::ParsedAttr const&)
Line
Count
Source
272
23
static bool checkAttrMutualExclusion(Sema &S, Decl *D, const ParsedAttr &AL) {
273
23
  if (const auto *A = D->getAttr<AttrTy>()) {
274
2
    S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible) << AL << A;
275
2
    S.Diag(A->getLocation(), diag::note_conflicting_attribute);
276
2
    return true;
277
2
  }
278
21
  return false;
279
23
}
SemaDeclAttr.cpp:bool checkAttrMutualExclusion<clang::PointerAttr>(clang::Sema&, clang::Decl*, clang::ParsedAttr const&)
Line
Count
Source
272
28
static bool checkAttrMutualExclusion(Sema &S, Decl *D, const ParsedAttr &AL) {
273
28
  if (const auto *A = D->getAttr<AttrTy>()) {
274
1
    S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible) << AL << A;
275
1
    S.Diag(A->getLocation(), diag::note_conflicting_attribute);
276
1
    return true;
277
1
  }
278
27
  return false;
279
28
}
SemaDeclAttr.cpp:bool checkAttrMutualExclusion<clang::OwnerAttr>(clang::Sema&, clang::Decl*, clang::ParsedAttr const&)
Line
Count
Source
272
15
static bool checkAttrMutualExclusion(Sema &S, Decl *D, const ParsedAttr &AL) {
273
15
  if (const auto *A = D->getAttr<AttrTy>()) {
274
0
    S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible) << AL << A;
275
0
    S.Diag(A->getLocation(), diag::note_conflicting_attribute);
276
0
    return true;
277
0
  }
278
15
  return false;
279
15
}
280
281
template <typename AttrTy>
282
static bool checkAttrMutualExclusion(Sema &S, Decl *D, const Attr &AL) {
283
  if (const auto *A = D->getAttr<AttrTy>()) {
284
    S.Diag(AL.getLocation(), diag::err_attributes_are_not_compatible) << &AL
285
                                                                      << A;
286
    S.Diag(A->getLocation(), diag::note_conflicting_attribute);
287
    return true;
288
  }
289
  return false;
290
}
291
292
/// Check if IdxExpr is a valid parameter index for a function or
293
/// instance method D.  May output an error.
294
///
295
/// \returns true if IdxExpr is a valid index.
296
template <typename AttrInfo>
297
static bool checkFunctionOrMethodParameterIndex(
298
    Sema &S, const Decl *D, const AttrInfo &AI, unsigned AttrArgNum,
299
61.5k
    const Expr *IdxExpr, ParamIdx &Idx, bool CanIndexImplicitThis = false) {
300
61.5k
  assert(isFunctionOrMethodOrBlock(D));
301
302
  // In C++ the implicit 'this' function parameter also counts.
303
  // Parameters are counted from one.
304
0
  bool HP = hasFunctionProto(D);
305
61.5k
  bool HasImplicitThisParam = isInstanceMethod(D);
306
61.5k
  bool IV = HP && 
isFunctionOrMethodVariadic(D)61.5k
;
307
61.5k
  unsigned NumParams =
308
61.5k
      (HP ? 
getFunctionOrMethodNumParams(D)61.5k
:
05
) + HasImplicitThisParam;
309
310
61.5k
  Optional<llvm::APSInt> IdxInt;
311
61.5k
  if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent() ||
312
61.5k
      
!(IdxInt = IdxExpr->getIntegerConstantExpr(S.Context))61.5k
) {
313
13
    S.Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type)
314
13
        << &AI << AttrArgNum << AANT_ArgumentIntegerConstant
315
13
        << IdxExpr->getSourceRange();
316
13
    return false;
317
13
  }
318
319
61.5k
  unsigned IdxSource = IdxInt->getLimitedValue(UINT_MAX);
320
61.5k
  if (IdxSource < 1 || 
(61.5k
!IV61.5k
&&
IdxSource > NumParams61.0k
)) {
321
51
    S.Diag(getAttrLoc(AI), diag::err_attribute_argument_out_of_bounds)
322
51
        << &AI << AttrArgNum << IdxExpr->getSourceRange();
323
51
    return false;
324
51
  }
325
61.5k
  if (HasImplicitThisParam && 
!CanIndexImplicitThis75
) {
326
72
    if (IdxSource == 1) {
327
6
      S.Diag(getAttrLoc(AI), diag::err_attribute_invalid_implicit_this_argument)
328
6
          << &AI << IdxExpr->getSourceRange();
329
6
      return false;
330
6
    }
331
72
  }
332
333
61.5k
  Idx = ParamIdx(IdxSource, D);
334
61.5k
  return true;
335
61.5k
}
SemaDeclAttr.cpp:bool checkFunctionOrMethodParameterIndex<clang::ParsedAttr>(clang::Sema&, clang::Decl const*, clang::ParsedAttr const&, unsigned int, clang::Expr const*, clang::ParamIdx&, bool)
Line
Count
Source
299
61.5k
    const Expr *IdxExpr, ParamIdx &Idx, bool CanIndexImplicitThis = false) {
300
61.5k
  assert(isFunctionOrMethodOrBlock(D));
301
302
  // In C++ the implicit 'this' function parameter also counts.
303
  // Parameters are counted from one.
304
0
  bool HP = hasFunctionProto(D);
305
61.5k
  bool HasImplicitThisParam = isInstanceMethod(D);
306
61.5k
  bool IV = HP && 
isFunctionOrMethodVariadic(D)61.5k
;
307
61.5k
  unsigned NumParams =
308
61.5k
      (HP ? 
getFunctionOrMethodNumParams(D)61.5k
:
05
) + HasImplicitThisParam;
309
310
61.5k
  Optional<llvm::APSInt> IdxInt;
311
61.5k
  if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent() ||
312
61.5k
      
!(IdxInt = IdxExpr->getIntegerConstantExpr(S.Context))61.5k
) {
313
11
    S.Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type)
314
11
        << &AI << AttrArgNum << AANT_ArgumentIntegerConstant
315
11
        << IdxExpr->getSourceRange();
316
11
    return false;
317
11
  }
318
319
61.5k
  unsigned IdxSource = IdxInt->getLimitedValue(UINT_MAX);
320
61.5k
  if (IdxSource < 1 || 
(61.5k
!IV61.5k
&&
IdxSource > NumParams60.9k
)) {
321
49
    S.Diag(getAttrLoc(AI), diag::err_attribute_argument_out_of_bounds)
322
49
        << &AI << AttrArgNum << IdxExpr->getSourceRange();
323
49
    return false;
324
49
  }
325
61.4k
  if (HasImplicitThisParam && 
!CanIndexImplicitThis64
) {
326
61
    if (IdxSource == 1) {
327
5
      S.Diag(getAttrLoc(AI), diag::err_attribute_invalid_implicit_this_argument)
328
5
          << &AI << IdxExpr->getSourceRange();
329
5
      return false;
330
5
    }
331
61
  }
332
333
61.4k
  Idx = ParamIdx(IdxSource, D);
334
61.4k
  return true;
335
61.4k
}
SemaDeclAttr.cpp:bool checkFunctionOrMethodParameterIndex<clang::AllocAlignAttr>(clang::Sema&, clang::Decl const*, clang::AllocAlignAttr const&, unsigned int, clang::Expr const*, clang::ParamIdx&, bool)
Line
Count
Source
299
42
    const Expr *IdxExpr, ParamIdx &Idx, bool CanIndexImplicitThis = false) {
300
42
  assert(isFunctionOrMethodOrBlock(D));
301
302
  // In C++ the implicit 'this' function parameter also counts.
303
  // Parameters are counted from one.
304
0
  bool HP = hasFunctionProto(D);
305
42
  bool HasImplicitThisParam = isInstanceMethod(D);
306
42
  bool IV = HP && isFunctionOrMethodVariadic(D);
307
42
  unsigned NumParams =
308
42
      (HP ? getFunctionOrMethodNumParams(D) : 
00
) + HasImplicitThisParam;
309
310
42
  Optional<llvm::APSInt> IdxInt;
311
42
  if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent() ||
312
42
      
!(IdxInt = IdxExpr->getIntegerConstantExpr(S.Context))41
) {
313
2
    S.Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type)
314
2
        << &AI << AttrArgNum << AANT_ArgumentIntegerConstant
315
2
        << IdxExpr->getSourceRange();
316
2
    return false;
317
2
  }
318
319
40
  unsigned IdxSource = IdxInt->getLimitedValue(UINT_MAX);
320
40
  if (IdxSource < 1 || 
(39
!IV39
&&
IdxSource > NumParams39
)) {
321
2
    S.Diag(getAttrLoc(AI), diag::err_attribute_argument_out_of_bounds)
322
2
        << &AI << AttrArgNum << IdxExpr->getSourceRange();
323
2
    return false;
324
2
  }
325
38
  if (HasImplicitThisParam && 
!CanIndexImplicitThis11
) {
326
11
    if (IdxSource == 1) {
327
1
      S.Diag(getAttrLoc(AI), diag::err_attribute_invalid_implicit_this_argument)
328
1
          << &AI << IdxExpr->getSourceRange();
329
1
      return false;
330
1
    }
331
11
  }
332
333
37
  Idx = ParamIdx(IdxSource, D);
334
37
  return true;
335
38
}
336
337
/// Check if the argument \p ArgNum of \p Attr is a ASCII string literal.
338
/// If not emit an error and return false. If the argument is an identifier it
339
/// will emit an error with a fixit hint and treat it as if it was a string
340
/// literal.
341
bool Sema::checkStringLiteralArgumentAttr(const ParsedAttr &AL, unsigned ArgNum,
342
                                          StringRef &Str,
343
2.78M
                                          SourceLocation *ArgLocation) {
344
  // Look for identifiers. If we have one emit a hint to fix it to a literal.
345
2.78M
  if (AL.isArgIdent(ArgNum)) {
346
11
    IdentifierLoc *Loc = AL.getArgAsIdent(ArgNum);
347
11
    Diag(Loc->Loc, diag::err_attribute_argument_type)
348
11
        << AL << AANT_ArgumentString
349
11
        << FixItHint::CreateInsertion(Loc->Loc, "\"")
350
11
        << FixItHint::CreateInsertion(getLocForEndOfToken(Loc->Loc), "\"");
351
11
    Str = Loc->Ident->getName();
352
11
    if (ArgLocation)
353
8
      *ArgLocation = Loc->Loc;
354
11
    return true;
355
11
  }
356
357
  // Now check for an actual string literal.
358
2.78M
  Expr *ArgExpr = AL.getArgAsExpr(ArgNum);
359
2.78M
  const auto *Literal = dyn_cast<StringLiteral>(ArgExpr->IgnoreParenCasts());
360
2.78M
  if (ArgLocation)
361
2.75M
    *ArgLocation = ArgExpr->getBeginLoc();
362
363
2.78M
  if (!Literal || 
!Literal->isAscii()2.78M
) {
364
31
    Diag(ArgExpr->getBeginLoc(), diag::err_attribute_argument_type)
365
31
        << AL << AANT_ArgumentString;
366
31
    return false;
367
31
  }
368
369
2.78M
  Str = Literal->getString();
370
2.78M
  return true;
371
2.78M
}
372
373
/// Applies the given attribute to the Decl without performing any
374
/// additional semantic checking.
375
template <typename AttrType>
376
static void handleSimpleAttribute(Sema &S, Decl *D,
377
202k
                                  const AttributeCommonInfo &CI) {
378
202k
  D->addAttr(::new (S.Context) AttrType(S.Context, CI));
379
202k
}
SemaDeclAttr.cpp:void handleSimpleAttribute<clang::AVRInterruptAttr>(clang::Sema&, clang::Decl*, clang::AttributeCommonInfo const&)
Line
Count
Source
377
2
                                  const AttributeCommonInfo &CI) {
378
2
  D->addAttr(::new (S.Context) AttrType(S.Context, CI));
379
2
}
SemaDeclAttr.cpp:void handleSimpleAttribute<clang::AVRSignalAttr>(clang::Sema&, clang::Decl*, clang::AttributeCommonInfo const&)
Line
Count
Source
377
2
                                  const AttributeCommonInfo &CI) {
378
2
  D->addAttr(::new (S.Context) AttrType(S.Context, CI));
379
2
}
SemaDeclAttr.cpp:void handleSimpleAttribute<clang::SYCLKernelAttr>(clang::Sema&, clang::Decl*, clang::AttributeCommonInfo const&)
Line
Count
Source
377
20
                                  const AttributeCommonInfo &CI) {
378
20
  D->addAttr(::new (S.Context) AttrType(S.Context, CI));
379
20
}
SemaDeclAttr.cpp:void handleSimpleAttribute<clang::AnyX86NoCfCheckAttr>(clang::Sema&, clang::Decl*, clang::AttributeCommonInfo const&)
Line
Count
Source
377
19
                                  const AttributeCommonInfo &CI) {
378
19
  D->addAttr(::new (S.Context) AttrType(S.Context, CI));
379
19
}
SemaDeclAttr.cpp:void handleSimpleAttribute<clang::NoThrowAttr>(clang::Sema&, clang::Decl*, clang::AttributeCommonInfo const&)
Line
Count
Source
377
26.4k
                                  const AttributeCommonInfo &CI) {
378
26.4k
  D->addAttr(::new (S.Context) AttrType(S.Context, CI));
379
26.4k
}
SemaDeclAttr.cpp:void handleSimpleAttribute<clang::OSReturnsRetainedOnZeroAttr>(clang::Sema&, clang::Decl*, clang::AttributeCommonInfo const&)
Line
Count
Source
377
3
                                  const AttributeCommonInfo &CI) {
378
3
  D->addAttr(::new (S.Context) AttrType(S.Context, CI));
379
3
}
SemaDeclAttr.cpp:void handleSimpleAttribute<clang::OSReturnsRetainedOnNonZeroAttr>(clang::Sema&, clang::Decl*, clang::AttributeCommonInfo const&)
Line
Count
Source
377
2
                                  const AttributeCommonInfo &CI) {
378
2
  D->addAttr(::new (S.Context) AttrType(S.Context, CI));
379
2
}
SemaDeclAttr.cpp:void handleSimpleAttribute<clang::NSReturnsAutoreleasedAttr>(clang::Sema&, clang::Decl*, clang::AttributeCommonInfo const&)
Line
Count
Source
377
6
                                  const AttributeCommonInfo &CI) {
378
6
  D->addAttr(::new (S.Context) AttrType(S.Context, CI));
379
6
}
SemaDeclAttr.cpp:void handleSimpleAttribute<clang::CFReturnsNotRetainedAttr>(clang::Sema&, clang::Decl*, clang::AttributeCommonInfo const&)
Line
Count
Source
377
533
                                  const AttributeCommonInfo &CI) {
378
533
  D->addAttr(::new (S.Context) AttrType(S.Context, CI));
379
533
}
SemaDeclAttr.cpp:void handleSimpleAttribute<clang::NSReturnsNotRetainedAttr>(clang::Sema&, clang::Decl*, clang::AttributeCommonInfo const&)
Line
Count
Source
377
113
                                  const AttributeCommonInfo &CI) {
378
113
  D->addAttr(::new (S.Context) AttrType(S.Context, CI));
379
113
}
SemaDeclAttr.cpp:void handleSimpleAttribute<clang::CFReturnsRetainedAttr>(clang::Sema&, clang::Decl*, clang::AttributeCommonInfo const&)
Line
Count
Source
377
32.1k
                                  const AttributeCommonInfo &CI) {
378
32.1k
  D->addAttr(::new (S.Context) AttrType(S.Context, CI));
379
32.1k
}
SemaDeclAttr.cpp:void handleSimpleAttribute<clang::NSReturnsRetainedAttr>(clang::Sema&, clang::Decl*, clang::AttributeCommonInfo const&)
Line
Count
Source
377
23.9k
                                  const AttributeCommonInfo &CI) {
378
23.9k
  D->addAttr(::new (S.Context) AttrType(S.Context, CI));
379
23.9k
}
SemaDeclAttr.cpp:void handleSimpleAttribute<clang::OSReturnsRetainedAttr>(clang::Sema&, clang::Decl*, clang::AttributeCommonInfo const&)
Line
Count
Source
377
19
                                  const AttributeCommonInfo &CI) {
378
19
  D->addAttr(::new (S.Context) AttrType(S.Context, CI));
379
19
}
SemaDeclAttr.cpp:void handleSimpleAttribute<clang::OSReturnsNotRetainedAttr>(clang::Sema&, clang::Decl*, clang::AttributeCommonInfo const&)
Line
Count
Source
377
11
                                  const AttributeCommonInfo &CI) {
378
11
  D->addAttr(::new (S.Context) AttrType(S.Context, CI));
379
11
}
SemaDeclAttr.cpp:void handleSimpleAttribute<clang::ObjCDirectAttr>(clang::Sema&, clang::Decl*, clang::AttributeCommonInfo const&)
Line
Count
Source
377
113
                                  const AttributeCommonInfo &CI) {
378
113
  D->addAttr(::new (S.Context) AttrType(S.Context, CI));
379
113
}
SemaDeclAttr.cpp:void handleSimpleAttribute<clang::ObjCDirectMembersAttr>(clang::Sema&, clang::Decl*, clang::AttributeCommonInfo const&)
Line
Count
Source
377
22
                                  const AttributeCommonInfo &CI) {
378
22
  D->addAttr(::new (S.Context) AttrType(S.Context, CI));
379
22
}
SemaDeclAttr.cpp:void handleSimpleAttribute<clang::AlwaysDestroyAttr>(clang::Sema&, clang::Decl*, clang::AttributeCommonInfo const&)
Line
Count
Source
377
24
                                  const AttributeCommonInfo &CI) {
378
24
  D->addAttr(::new (S.Context) AttrType(S.Context, CI));
379
24
}
SemaDeclAttr.cpp:void handleSimpleAttribute<clang::NoDestroyAttr>(clang::Sema&, clang::Decl*, clang::AttributeCommonInfo const&)
Line
Count
Source
377
38
                                  const AttributeCommonInfo &CI) {
378
38
  D->addAttr(::new (S.Context) AttrType(S.Context, CI));
379
38
}
SemaDeclAttr.cpp:void handleSimpleAttribute<clang::ObjCExternallyRetainedAttr>(clang::Sema&, clang::Decl*, clang::AttributeCommonInfo const&)
Line
Count
Source
377
51
                                  const AttributeCommonInfo &CI) {
378
51
  D->addAttr(::new (S.Context) AttrType(S.Context, CI));
379
51
}
SemaDeclAttr.cpp:void handleSimpleAttribute<clang::MIGServerRoutineAttr>(clang::Sema&, clang::Decl*, clang::AttributeCommonInfo const&)
Line
Count
Source
377
26
                                  const AttributeCommonInfo &CI) {
378
26
  D->addAttr(::new (S.Context) AttrType(S.Context, CI));
379
26
}
SemaDeclAttr.cpp:void handleSimpleAttribute<clang::MSAllocatorAttr>(clang::Sema&, clang::Decl*, clang::AttributeCommonInfo const&)
Line
Count
Source
377
5
                                  const AttributeCommonInfo &CI) {
378
5
  D->addAttr(::new (S.Context) AttrType(S.Context, CI));
379
5
}
SemaDeclAttr.cpp:void handleSimpleAttribute<clang::UsingIfExistsAttr>(clang::Sema&, clang::Decl*, clang::AttributeCommonInfo const&)
Line
Count
Source
377
116k
                                  const AttributeCommonInfo &CI) {
378
116k
  D->addAttr(::new (S.Context) AttrType(S.Context, CI));
379
116k
}
SemaDeclAttr.cpp:void handleSimpleAttribute<clang::OSConsumedAttr>(clang::Sema&, clang::Decl*, clang::AttributeCommonInfo const&)
Line
Count
Source
377
9
                                  const AttributeCommonInfo &CI) {
378
9
  D->addAttr(::new (S.Context) AttrType(S.Context, CI));
379
9
}
SemaDeclAttr.cpp:void handleSimpleAttribute<clang::NSConsumedAttr>(clang::Sema&, clang::Decl*, clang::AttributeCommonInfo const&)
Line
Count
Source
377
420
                                  const AttributeCommonInfo &CI) {
378
420
  D->addAttr(::new (S.Context) AttrType(S.Context, CI));
379
420
}
SemaDeclAttr.cpp:void handleSimpleAttribute<clang::CFConsumedAttr>(clang::Sema&, clang::Decl*, clang::AttributeCommonInfo const&)
Line
Count
Source
377
1.90k
                                  const AttributeCommonInfo &CI) {
378
1.90k
  D->addAttr(::new (S.Context) AttrType(S.Context, CI));
379
1.90k
}
380
381
template <typename... DiagnosticArgs>
382
static const Sema::SemaDiagnosticBuilder&
383
4
appendDiagnostics(const Sema::SemaDiagnosticBuilder &Bldr) {
384
4
  return Bldr;
385
4
}
386
387
template <typename T, typename... DiagnosticArgs>
388
static const Sema::SemaDiagnosticBuilder&
389
appendDiagnostics(const Sema::SemaDiagnosticBuilder &Bldr, T &&ExtraArg,
390
12
                  DiagnosticArgs &&... ExtraArgs) {
391
12
  return appendDiagnostics(Bldr << std::forward<T>(ExtraArg),
392
12
                           std::forward<DiagnosticArgs>(ExtraArgs)...);
393
12
}
SemaDeclAttr.cpp:clang::Sema::SemaDiagnosticBuilder const& appendDiagnostics<clang::ParsedAttr const&, int, clang::SourceRange>(clang::Sema::SemaDiagnosticBuilder const&, clang::ParsedAttr const&, int&&, clang::SourceRange&&)
Line
Count
Source
390
2
                  DiagnosticArgs &&... ExtraArgs) {
391
2
  return appendDiagnostics(Bldr << std::forward<T>(ExtraArg),
392
2
                           std::forward<DiagnosticArgs>(ExtraArgs)...);
393
2
}
SemaDeclAttr.cpp:clang::Sema::SemaDiagnosticBuilder const& appendDiagnostics<int, clang::SourceRange>(clang::Sema::SemaDiagnosticBuilder const&, int&&, clang::SourceRange&&)
Line
Count
Source
390
2
                  DiagnosticArgs &&... ExtraArgs) {
391
2
  return appendDiagnostics(Bldr << std::forward<T>(ExtraArg),
392
2
                           std::forward<DiagnosticArgs>(ExtraArgs)...);
393
2
}
SemaDeclAttr.cpp:clang::Sema::SemaDiagnosticBuilder const& appendDiagnostics<clang::SourceRange>(clang::Sema::SemaDiagnosticBuilder const&, clang::SourceRange&&)
Line
Count
Source
390
2
                  DiagnosticArgs &&... ExtraArgs) {
391
2
  return appendDiagnostics(Bldr << std::forward<T>(ExtraArg),
392
2
                           std::forward<DiagnosticArgs>(ExtraArgs)...);
393
2
}
SemaDeclAttr.cpp:clang::Sema::SemaDiagnosticBuilder const& appendDiagnostics<clang::SourceRange, char const (&) [12], int>(clang::Sema::SemaDiagnosticBuilder const&, clang::SourceRange&&, char const (&) [12], int&&)
Line
Count
Source
390
2
                  DiagnosticArgs &&... ExtraArgs) {
391
2
  return appendDiagnostics(Bldr << std::forward<T>(ExtraArg),
392
2
                           std::forward<DiagnosticArgs>(ExtraArgs)...);
393
2
}
SemaDeclAttr.cpp:clang::Sema::SemaDiagnosticBuilder const& appendDiagnostics<char const (&) [12], int>(clang::Sema::SemaDiagnosticBuilder const&, char const (&) [12], int&&)
Line
Count
Source
390
2
                  DiagnosticArgs &&... ExtraArgs) {
391
2
  return appendDiagnostics(Bldr << std::forward<T>(ExtraArg),
392
2
                           std::forward<DiagnosticArgs>(ExtraArgs)...);
393
2
}
SemaDeclAttr.cpp:clang::Sema::SemaDiagnosticBuilder const& appendDiagnostics<int>(clang::Sema::SemaDiagnosticBuilder const&, int&&)
Line
Count
Source
390
2
                  DiagnosticArgs &&... ExtraArgs) {
391
2
  return appendDiagnostics(Bldr << std::forward<T>(ExtraArg),
392
2
                           std::forward<DiagnosticArgs>(ExtraArgs)...);
393
2
}
394
395
/// Add an attribute @c AttrType to declaration @c D, provided that
396
/// @c PassesCheck is true.
397
/// Otherwise, emit diagnostic @c DiagID, passing in all parameters
398
/// specified in @c ExtraArgs.
399
template <typename AttrType, typename... DiagnosticArgs>
400
static void handleSimpleAttributeOrDiagnose(Sema &S, Decl *D,
401
                                            const AttributeCommonInfo &CI,
402
                                            bool PassesCheck, unsigned DiagID,
403
2.34k
                                            DiagnosticArgs &&... ExtraArgs) {
404
2.34k
  if (!PassesCheck) {
405
4
    Sema::SemaDiagnosticBuilder DB = S.Diag(D->getBeginLoc(), DiagID);
406
4
    appendDiagnostics(DB, std::forward<DiagnosticArgs>(ExtraArgs)...);
407
4
    return;
408
4
  }
409
2.34k
  handleSimpleAttribute<AttrType>(S, D, CI);
410
2.34k
}
SemaDeclAttr.cpp:void handleSimpleAttributeOrDiagnose<clang::OSReturnsRetainedOnZeroAttr, clang::ParsedAttr const&, int, clang::SourceRange>(clang::Sema&, clang::Decl*, clang::AttributeCommonInfo const&, bool, unsigned int, clang::ParsedAttr const&, int&&, clang::SourceRange&&)
Line
Count
Source
403
4
                                            DiagnosticArgs &&... ExtraArgs) {
404
4
  if (!PassesCheck) {
405
1
    Sema::SemaDiagnosticBuilder DB = S.Diag(D->getBeginLoc(), DiagID);
406
1
    appendDiagnostics(DB, std::forward<DiagnosticArgs>(ExtraArgs)...);
407
1
    return;
408
1
  }
409
3
  handleSimpleAttribute<AttrType>(S, D, CI);
410
3
}
SemaDeclAttr.cpp:void handleSimpleAttributeOrDiagnose<clang::OSReturnsRetainedOnNonZeroAttr, clang::ParsedAttr const&, int, clang::SourceRange>(clang::Sema&, clang::Decl*, clang::AttributeCommonInfo const&, bool, unsigned int, clang::ParsedAttr const&, int&&, clang::SourceRange&&)
Line
Count
Source
403
3
                                            DiagnosticArgs &&... ExtraArgs) {
404
3
  if (!PassesCheck) {
405
1
    Sema::SemaDiagnosticBuilder DB = S.Diag(D->getBeginLoc(), DiagID);
406
1
    appendDiagnostics(DB, std::forward<DiagnosticArgs>(ExtraArgs)...);
407
1
    return;
408
1
  }
409
2
  handleSimpleAttribute<AttrType>(S, D, CI);
410
2
}
SemaDeclAttr.cpp:void handleSimpleAttributeOrDiagnose<clang::OSConsumedAttr, clang::SourceRange, char const (&) [12], int>(clang::Sema&, clang::Decl*, clang::AttributeCommonInfo const&, bool, unsigned int, clang::SourceRange&&, char const (&) [12], int&&)
Line
Count
Source
403
10
                                            DiagnosticArgs &&... ExtraArgs) {
404
10
  if (!PassesCheck) {
405
1
    Sema::SemaDiagnosticBuilder DB = S.Diag(D->getBeginLoc(), DiagID);
406
1
    appendDiagnostics(DB, std::forward<DiagnosticArgs>(ExtraArgs)...);
407
1
    return;
408
1
  }
409
9
  handleSimpleAttribute<AttrType>(S, D, CI);
410
9
}
SemaDeclAttr.cpp:void handleSimpleAttributeOrDiagnose<clang::NSConsumedAttr, clang::SourceRange, char const (&) [12], int>(clang::Sema&, clang::Decl*, clang::AttributeCommonInfo const&, bool, unsigned int, clang::SourceRange&&, char const (&) [12], int&&)
Line
Count
Source
403
421
                                            DiagnosticArgs &&... ExtraArgs) {
404
421
  if (!PassesCheck) {
405
1
    Sema::SemaDiagnosticBuilder DB = S.Diag(D->getBeginLoc(), DiagID);
406
1
    appendDiagnostics(DB, std::forward<DiagnosticArgs>(ExtraArgs)...);
407
1
    return;
408
1
  }
409
420
  handleSimpleAttribute<AttrType>(S, D, CI);
410
420
}
SemaDeclAttr.cpp:void handleSimpleAttributeOrDiagnose<clang::CFConsumedAttr, clang::SourceRange, char const (&) [12], int>(clang::Sema&, clang::Decl*, clang::AttributeCommonInfo const&, bool, unsigned int, clang::SourceRange&&, char const (&) [12], int&&)
Line
Count
Source
403
1.90k
                                            DiagnosticArgs &&... ExtraArgs) {
404
1.90k
  if (!PassesCheck) {
405
0
    Sema::SemaDiagnosticBuilder DB = S.Diag(D->getBeginLoc(), DiagID);
406
0
    appendDiagnostics(DB, std::forward<DiagnosticArgs>(ExtraArgs)...);
407
0
    return;
408
0
  }
409
1.90k
  handleSimpleAttribute<AttrType>(S, D, CI);
410
1.90k
}
411
412
/// Check if the passed-in expression is of type int or bool.
413
176
static bool isIntOrBool(Expr *Exp) {
414
176
  QualType QT = Exp->getType();
415
176
  return QT->isBooleanType() || 
QT->isIntegerType()120
;
416
176
}
417
418
419
// Check to see if the type is a smart pointer of some kind.  We assume
420
// it's a smart pointer if it defines both operator-> and operator*.
421
2.77k
static bool threadSafetyCheckIsSmartPointer(Sema &S, const RecordType* RT) {
422
2.77k
  auto IsOverloadedOperatorPresent = [&S](const RecordDecl *Record,
423
5.64k
                                          OverloadedOperatorKind Op) {
424
5.64k
    DeclContextLookupResult Result =
425
5.64k
        Record->lookup(S.Context.DeclarationNames.getCXXOperatorName(Op));
426
5.64k
    return !Result.empty();
427
5.64k
  };
428
429
2.77k
  const RecordDecl *Record = RT->getDecl();
430
2.77k
  bool foundStarOperator = IsOverloadedOperatorPresent(Record, OO_Star);
431
2.77k
  bool foundArrowOperator = IsOverloadedOperatorPresent(Record, OO_Arrow);
432
2.77k
  if (foundStarOperator && 
foundArrowOperator46
)
433
46
    return true;
434
435
2.73k
  const CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record);
436
2.73k
  if (!CXXRecord)
437
21
    return false;
438
439
2.70k
  for (auto BaseSpecifier : CXXRecord->bases()) {
440
44
    if (!foundStarOperator)
441
44
      foundStarOperator = IsOverloadedOperatorPresent(
442
44
          BaseSpecifier.getType()->getAsRecordDecl(), OO_Star);
443
44
    if (!foundArrowOperator)
444
44
      foundArrowOperator = IsOverloadedOperatorPresent(
445
44
          BaseSpecifier.getType()->getAsRecordDecl(), OO_Arrow);
446
44
  }
447
448
2.70k
  if (foundStarOperator && 
foundArrowOperator16
)
449
16
    return true;
450
451
2.69k
  return false;
452
2.70k
}
453
454
/// Check if passed in Decl is a pointer type.
455
/// Note that this function may produce an error message.
456
/// \return true if the Decl is a pointer type; false otherwise
457
static bool threadSafetyCheckIsPointer(Sema &S, const Decl *D,
458
153
                                       const ParsedAttr &AL) {
459
153
  const auto *VD = cast<ValueDecl>(D);
460
153
  QualType QT = VD->getType();
461
153
  if (QT->isAnyPointerType())
462
114
    return true;
463
464
39
  if (const auto *RT = QT->getAs<RecordType>()) {
465
    // If it's an incomplete type, it could be a smart pointer; skip it.
466
    // (We don't want to force template instantiation if we can avoid it,
467
    // since that would alter the order in which templates are instantiated.)
468
22
    if (RT->isIncompleteType())
469
3
      return true;
470
471
19
    if (threadSafetyCheckIsSmartPointer(S, RT))
472
19
      return true;
473
19
  }
474
475
17
  S.Diag(AL.getLoc(), diag::warn_thread_attribute_decl_not_pointer) << AL << QT;
476
17
  return false;
477
39
}
478
479
/// Checks that the passed in QualType either is of RecordType or points
480
/// to RecordType. Returns the relevant RecordType, null if it does not exit.
481
5.56k
static const RecordType *getRecordType(QualType QT) {
482
5.56k
  if (const auto *RT = QT->getAs<RecordType>())
483
4.50k
    return RT;
484
485
  // Now check if we point to record type.
486
1.05k
  if (const auto *PT = QT->getAs<PointerType>())
487
804
    return PT->getPointeeType()->getAs<RecordType>();
488
489
253
  return nullptr;
490
1.05k
}
491
492
template <typename AttrType>
493
3.26k
static bool checkRecordDeclForAttr(const RecordDecl *RD) {
494
  // Check if the record itself has the attribute.
495
3.26k
  if (RD->hasAttr<AttrType>())
496
2.92k
    return true;
497
498
  // Else check if any base classes have the attribute.
499
331
  if (const auto *CRD = dyn_cast<CXXRecordDecl>(RD)) {
500
329
    if (!CRD->forallBases([](const CXXRecordDecl *Base) {
501
58
          return !Base->hasAttr<AttrType>();
502
58
        }))
SemaDeclAttr.cpp:bool checkRecordDeclForAttr<clang::CapabilityAttr>(clang::RecordDecl const*)::'lambda'(clang::CXXRecordDecl const*)::operator()(clang::CXXRecordDecl const*) const
Line
Count
Source
500
46
    if (!CRD->forallBases([](const CXXRecordDecl *Base) {
501
46
          return !Base->hasAttr<AttrType>();
502
46
        }))
SemaDeclAttr.cpp:bool checkRecordDeclForAttr<clang::ScopedLockableAttr>(clang::RecordDecl const*)::'lambda'(clang::CXXRecordDecl const*)::operator()(clang::CXXRecordDecl const*) const
Line
Count
Source
500
12
    if (!CRD->forallBases([](const CXXRecordDecl *Base) {
501
12
          return !Base->hasAttr<AttrType>();
502
12
        }))
503
22
      return true;
504
329
  }
505
309
  return false;
506
331
}
SemaDeclAttr.cpp:bool checkRecordDeclForAttr<clang::CapabilityAttr>(clang::RecordDecl const*)
Line
Count
Source
493
3.09k
static bool checkRecordDeclForAttr(const RecordDecl *RD) {
494
  // Check if the record itself has the attribute.
495
3.09k
  if (RD->hasAttr<AttrType>())
496
2.79k
    return true;
497
498
  // Else check if any base classes have the attribute.
499
300
  if (const auto *CRD = dyn_cast<CXXRecordDecl>(RD)) {
500
298
    if (!CRD->forallBases([](const CXXRecordDecl *Base) {
501
298
          return !Base->hasAttr<AttrType>();
502
298
        }))
503
19
      return true;
504
298
  }
505
281
  return false;
506
300
}
SemaDeclAttr.cpp:bool checkRecordDeclForAttr<clang::ScopedLockableAttr>(clang::RecordDecl const*)
Line
Count
Source
493
170
static bool checkRecordDeclForAttr(const RecordDecl *RD) {
494
  // Check if the record itself has the attribute.
495
170
  if (RD->hasAttr<AttrType>())
496
139
    return true;
497
498
  // Else check if any base classes have the attribute.
499
31
  if (const auto *CRD = dyn_cast<CXXRecordDecl>(RD)) {
500
31
    if (!CRD->forallBases([](const CXXRecordDecl *Base) {
501
31
          return !Base->hasAttr<AttrType>();
502
31
        }))
503
3
      return true;
504
31
  }
505
28
  return false;
506
31
}
507
508
2.92k
static bool checkRecordTypeForCapability(Sema &S, QualType Ty) {
509
2.92k
  const RecordType *RT = getRecordType(Ty);
510
511
2.92k
  if (!RT)
512
172
    return false;
513
514
  // Don't check for the capability if the class hasn't been defined yet.
515
2.75k
  if (RT->isIncompleteType())
516
0
    return true;
517
518
  // Allow smart pointers to be used as capability objects.
519
  // FIXME -- Check the type that the smart pointer points to.
520
2.75k
  if (threadSafetyCheckIsSmartPointer(S, RT))
521
43
    return true;
522
523
2.71k
  return checkRecordDeclForAttr<CapabilityAttr>(RT->getDecl());
524
2.75k
}
525
526
2.98k
static bool checkTypedefTypeForCapability(QualType Ty) {
527
2.98k
  const auto *TD = Ty->getAs<TypedefType>();
528
2.98k
  if (!TD)
529
2.92k
    return false;
530
531
60
  TypedefNameDecl *TN = TD->getDecl();
532
60
  if (!TN)
533
0
    return false;
534
535
60
  return TN->hasAttr<CapabilityAttr>();
536
60
}
537
538
2.98k
static bool typeHasCapability(Sema &S, QualType Ty) {
539
2.98k
  if (checkTypedefTypeForCapability(Ty))
540
60
    return true;
541
542
2.92k
  if (checkRecordTypeForCapability(S, Ty))
543
2.64k
    return true;
544
545
283
  return false;
546
2.92k
}
547
548
251
static bool isCapabilityExpr(Sema &S, const Expr *Ex) {
549
  // Capability expressions are simple expressions involving the boolean logic
550
  // operators &&, || or !, a simple DeclRefExpr, CastExpr or a ParenExpr. Once
551
  // a DeclRefExpr is found, its type should be checked to determine whether it
552
  // is a capability or not.
553
554
251
  if (const auto *E = dyn_cast<CastExpr>(Ex))
555
50
    return isCapabilityExpr(S, E->getSubExpr());
556
201
  else if (const auto *E = dyn_cast<ParenExpr>(Ex))
557
1
    return isCapabilityExpr(S, E->getSubExpr());
558
200
  else if (const auto *E = dyn_cast<UnaryOperator>(Ex)) {
559
38
    if (E->getOpcode() == UO_LNot || 
E->getOpcode() == UO_AddrOf12
||
560
38
        
E->getOpcode() == UO_Deref3
)
561
38
      return isCapabilityExpr(S, E->getSubExpr());
562
0
    return false;
563
162
  } else if (const auto *E = dyn_cast<BinaryOperator>(Ex)) {
564
5
    if (E->getOpcode() == BO_LAnd || 
E->getOpcode() == BO_LOr2
)
565
5
      return isCapabilityExpr(S, E->getLHS()) &&
566
5
             isCapabilityExpr(S, E->getRHS());
567
0
    return false;
568
5
  }
569
570
157
  return typeHasCapability(S, Ex->getType());
571
251
}
572
573
/// Checks that all attribute arguments, starting from Sidx, resolve to
574
/// a capability object.
575
/// \param Sidx The attribute argument index to start checking with.
576
/// \param ParamIdxOk Whether an argument can be indexing into a function
577
/// parameter list.
578
static void checkAttrArgsAreCapabilityObjs(Sema &S, Decl *D,
579
                                           const ParsedAttr &AL,
580
                                           SmallVectorImpl<Expr *> &Args,
581
                                           unsigned Sidx = 0,
582
3.01k
                                           bool ParamIdxOk = false) {
583
3.01k
  if (Sidx == AL.getNumArgs()) {
584
    // If we don't have any capability arguments, the attribute implicitly
585
    // refers to 'this'. So we need to make sure that 'this' exists, i.e. we're
586
    // a non-static method, and that the class is a (scoped) capability.
587
421
    const auto *MD = dyn_cast<const CXXMethodDecl>(D);
588
421
    if (MD && 
!MD->isStatic()376
) {
589
376
      const CXXRecordDecl *RD = MD->getParent();
590
      // FIXME -- need to check this again on template instantiation
591
376
      if (!checkRecordDeclForAttr<CapabilityAttr>(RD) &&
592
376
          
!checkRecordDeclForAttr<ScopedLockableAttr>(RD)170
)
593
28
        S.Diag(AL.getLoc(),
594
28
               diag::warn_thread_attribute_not_on_capability_member)
595
28
            << AL << MD->getParent();
596
376
    } else {
597
45
      S.Diag(AL.getLoc(), diag::warn_thread_attribute_not_on_non_static_member)
598
45
          << AL;
599
45
    }
600
421
  }
601
602
5.80k
  for (unsigned Idx = Sidx; Idx < AL.getNumArgs(); 
++Idx2.79k
) {
603
2.79k
    Expr *ArgExp = AL.getArgAsExpr(Idx);
604
605
2.79k
    if (ArgExp->isTypeDependent()) {
606
      // FIXME -- need to check this again on template instantiation
607
54
      Args.push_back(ArgExp);
608
54
      continue;
609
54
    }
610
611
2.73k
    if (const auto *StrLit = dyn_cast<StringLiteral>(ArgExp)) {
612
104
      if (StrLit->getLength() == 0 ||
613
104
          
(70
StrLit->isAscii()70
&&
StrLit->getString() == StringRef("*")67
)) {
614
        // Pass empty strings to the analyzer without warnings.
615
        // Treat "*" as the universal lock.
616
62
        Args.push_back(ArgExp);
617
62
        continue;
618
62
      }
619
620
      // We allow constant strings to be used as a placeholder for expressions
621
      // that are not valid C++ syntax, but warn that they are ignored.
622
42
      S.Diag(AL.getLoc(), diag::warn_thread_attribute_ignored) << AL;
623
42
      Args.push_back(ArgExp);
624
42
      continue;
625
104
    }
626
627
2.63k
    QualType ArgTy = ArgExp->getType();
628
629
    // A pointer to member expression of the form  &MyClass::mu is treated
630
    // specially -- we need to look at the type of the member.
631
2.63k
    if (const auto *UOp = dyn_cast<UnaryOperator>(ArgExp))
632
140
      if (UOp->getOpcode() == UO_AddrOf)
633
76
        if (const auto *DRE = dyn_cast<DeclRefExpr>(UOp->getSubExpr()))
634
76
          if (DRE->getDecl()->isCXXInstanceMember())
635
37
            ArgTy = DRE->getDecl()->getType();
636
637
    // First see if we can just cast to record type, or pointer to record type.
638
2.63k
    const RecordType *RT = getRecordType(ArgTy);
639
640
    // Now check if we index into a record type function param.
641
2.63k
    if(!RT && 
ParamIdxOk198
) {
642
89
      const auto *FD = dyn_cast<FunctionDecl>(D);
643
89
      const auto *IL = dyn_cast<IntegerLiteral>(ArgExp);
644
89
      if(FD && IL) {
645
63
        unsigned int NumParams = FD->getNumParams();
646
63
        llvm::APInt ArgValue = IL->getValue();
647
63
        uint64_t ParamIdxFromOne = ArgValue.getZExtValue();
648
63
        uint64_t ParamIdxFromZero = ParamIdxFromOne - 1;
649
63
        if (!ArgValue.isStrictlyPositive() || 
ParamIdxFromOne > NumParams36
) {
650
36
          S.Diag(AL.getLoc(),
651
36
                 diag::err_attribute_argument_out_of_bounds_extra_info)
652
36
              << AL << Idx + 1 << NumParams;
653
36
          continue;
654
36
        }
655
27
        ArgTy = FD->getParamDecl(ParamIdxFromZero)->getType();
656
27
      }
657
89
    }
658
659
    // If the type does not have a capability, see if the components of the
660
    // expression have capabilities. This allows for writing C code where the
661
    // capability may be on the type, and the expression is a capability
662
    // boolean logic expression. Eg) requires_capability(A || B && !C)
663
2.59k
    if (!typeHasCapability(S, ArgTy) && 
!isCapabilityExpr(S, ArgExp)152
)
664
125
      S.Diag(AL.getLoc(), diag::warn_thread_attribute_argument_not_lockable)
665
125
          << AL << ArgTy;
666
667
2.59k
    Args.push_back(ArgExp);
668
2.59k
  }
669
3.01k
}
670
671
//===----------------------------------------------------------------------===//
672
// Attribute Implementations
673
//===----------------------------------------------------------------------===//
674
675
21
static void handlePtGuardedVarAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
676
21
  if (!threadSafetyCheckIsPointer(S, D, AL))
677
10
    return;
678
679
11
  D->addAttr(::new (S.Context) PtGuardedVarAttr(S.Context, AL));
680
11
}
681
682
static bool checkGuardedByAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
683
682
                                     Expr *&Arg) {
684
682
  SmallVector<Expr *, 1> Args;
685
  // check that all arguments are lockable objects
686
682
  checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
687
682
  unsigned Size = Args.size();
688
682
  if (Size != 1)
689
0
    return false;
690
691
682
  Arg = Args[0];
692
693
682
  return true;
694
682
}
695
696
550
static void handleGuardedByAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
697
550
  Expr *Arg = nullptr;
698
550
  if (!checkGuardedByAttrCommon(S, D, AL, Arg))
699
0
    return;
700
701
550
  D->addAttr(::new (S.Context) GuardedByAttr(S.Context, AL, Arg));
702
550
}
703
704
132
static void handlePtGuardedByAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
705
132
  Expr *Arg = nullptr;
706
132
  if (!checkGuardedByAttrCommon(S, D, AL, Arg))
707
0
    return;
708
709
132
  if (!threadSafetyCheckIsPointer(S, D, AL))
710
7
    return;
711
712
125
  D->addAttr(::new (S.Context) PtGuardedByAttr(S.Context, AL, Arg));
713
125
}
714
715
static bool checkAcquireOrderAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
716
246
                                        SmallVectorImpl<Expr *> &Args) {
717
246
  if (!AL.checkAtLeastNumArgs(S, 1))
718
12
    return false;
719
720
  // Check that this attribute only applies to lockable types.
721
234
  QualType QT = cast<ValueDecl>(D)->getType();
722
234
  if (!QT->isDependentType() && !typeHasCapability(S, QT)) {
723
6
    S.Diag(AL.getLoc(), diag::warn_thread_attribute_decl_not_lockable) << AL;
724
6
    return false;
725
6
  }
726
727
  // Check that all arguments are lockable objects.
728
228
  checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
729
228
  if (Args.empty())
730
0
    return false;
731
732
228
  return true;
733
228
}
734
735
143
static void handleAcquiredAfterAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
736
143
  SmallVector<Expr *, 1> Args;
737
143
  if (!checkAcquireOrderAttrCommon(S, D, AL, Args))
738
9
    return;
739
740
134
  Expr **StartArg = &Args[0];
741
134
  D->addAttr(::new (S.Context)
742
134
                 AcquiredAfterAttr(S.Context, AL, StartArg, Args.size()));
743
134
}
744
745
103
static void handleAcquiredBeforeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
746
103
  SmallVector<Expr *, 1> Args;
747
103
  if (!checkAcquireOrderAttrCommon(S, D, AL, Args))
748
9
    return;
749
750
94
  Expr **StartArg = &Args[0];
751
94
  D->addAttr(::new (S.Context)
752
94
                 AcquiredBeforeAttr(S.Context, AL, StartArg, Args.size()));
753
94
}
754
755
static bool checkLockFunAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
756
551
                                   SmallVectorImpl<Expr *> &Args) {
757
  // zero or more arguments ok
758
  // check that all arguments are lockable objects
759
551
  checkAttrArgsAreCapabilityObjs(S, D, AL, Args, 0, /*ParamIdxOk=*/true);
760
761
551
  return true;
762
551
}
763
764
13
static void handleAssertSharedLockAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
765
13
  SmallVector<Expr *, 1> Args;
766
13
  if (!checkLockFunAttrCommon(S, D, AL, Args))
767
0
    return;
768
769
13
  unsigned Size = Args.size();
770
13
  Expr **StartArg = Size == 0 ? 
nullptr7
:
&Args[0]6
;
771
13
  D->addAttr(::new (S.Context)
772
13
                 AssertSharedLockAttr(S.Context, AL, StartArg, Size));
773
13
}
774
775
static void handleAssertExclusiveLockAttr(Sema &S, Decl *D,
776
15
                                          const ParsedAttr &AL) {
777
15
  SmallVector<Expr *, 1> Args;
778
15
  if (!checkLockFunAttrCommon(S, D, AL, Args))
779
0
    return;
780
781
15
  unsigned Size = Args.size();
782
15
  Expr **StartArg = Size == 0 ? 
nullptr7
:
&Args[0]8
;
783
15
  D->addAttr(::new (S.Context)
784
15
                 AssertExclusiveLockAttr(S.Context, AL, StartArg, Size));
785
15
}
786
787
/// Checks to be sure that the given parameter number is in bounds, and
788
/// is an integral type. Will emit appropriate diagnostics if this returns
789
/// false.
790
///
791
/// AttrArgNo is used to actually retrieve the argument, so it's base-0.
792
template <typename AttrInfo>
793
static bool checkParamIsIntegerType(Sema &S, const Decl *D, const AttrInfo &AI,
794
5.80k
                                    unsigned AttrArgNo) {
795
5.80k
  assert(AI.isArgExpr(AttrArgNo) && "Expected expression argument");
796
0
  Expr *AttrArg = AI.getArgAsExpr(AttrArgNo);
797
5.80k
  ParamIdx Idx;
798
5.80k
  if (!checkFunctionOrMethodParameterIndex(S, D, AI, AttrArgNo + 1, AttrArg,
799
5.80k
                                           Idx))
800
6
    return false;
801
802
5.80k
  QualType ParamTy = getFunctionOrMethodParamType(D, Idx.getASTIndex());
803
5.80k
  if (!ParamTy->isIntegerType() && 
!ParamTy->isCharType()1
) {
804
1
    SourceLocation SrcLoc = AttrArg->getBeginLoc();
805
1
    S.Diag(SrcLoc, diag::err_attribute_integers_only)
806
1
        << AI << getFunctionOrMethodParamRange(D, Idx.getASTIndex());
807
1
    return false;
808
1
  }
809
5.79k
  return true;
810
5.80k
}
811
812
4.87k
static void handleAllocSizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
813
4.87k
  if (!AL.checkAtLeastNumArgs(S, 1) || !AL.checkAtMostNumArgs(S, 2))
814
0
    return;
815
816
4.87k
  assert(isFunctionOrMethod(D) && hasFunctionProto(D));
817
818
0
  QualType RetTy = getFunctionOrMethodResultType(D);
819
4.87k
  if (!RetTy->isPointerType()) {
820
1
    S.Diag(AL.getLoc(), diag::warn_attribute_return_pointers_only) << AL;
821
1
    return;
822
1
  }
823
824
4.87k
  const Expr *SizeExpr = AL.getArgAsExpr(0);
825
4.87k
  int SizeArgNoVal;
826
  // Parameter indices are 1-indexed, hence Index=1
827
4.87k
  if (!checkPositiveIntArgument(S, AL, SizeExpr, SizeArgNoVal, /*Idx=*/1))
828
2
    return;
829
4.86k
  if (!checkParamIsIntegerType(S, D, AL, /*AttrArgNo=*/0))
830
5
    return;
831
4.86k
  ParamIdx SizeArgNo(SizeArgNoVal, D);
832
833
4.86k
  ParamIdx NumberArgNo;
834
4.86k
  if (AL.getNumArgs() == 2) {
835
939
    const Expr *NumberExpr = AL.getArgAsExpr(1);
836
939
    int Val;
837
    // Parameter indices are 1-based, hence Index=2
838
939
    if (!checkPositiveIntArgument(S, AL, NumberExpr, Val, /*Idx=*/2))
839
1
      return;
840
938
    if (!checkParamIsIntegerType(S, D, AL, /*AttrArgNo=*/1))
841
2
      return;
842
936
    NumberArgNo = ParamIdx(Val, D);
843
936
  }
844
845
4.86k
  D->addAttr(::new (S.Context)
846
4.86k
                 AllocSizeAttr(S.Context, AL, SizeArgNo, NumberArgNo));
847
4.86k
}
848
849
static bool checkTryLockFunAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
850
176
                                      SmallVectorImpl<Expr *> &Args) {
851
176
  if (!AL.checkAtLeastNumArgs(S, 1))
852
0
    return false;
853
854
176
  if (!isIntOrBool(AL.getArgAsExpr(0))) {
855
18
    S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
856
18
        << AL << 1 << AANT_ArgumentIntOrBool;
857
18
    return false;
858
18
  }
859
860
  // check that all arguments are lockable objects
861
158
  checkAttrArgsAreCapabilityObjs(S, D, AL, Args, 1);
862
863
158
  return true;
864
176
}
865
866
static void handleSharedTrylockFunctionAttr(Sema &S, Decl *D,
867
70
                                            const ParsedAttr &AL) {
868
70
  SmallVector<Expr*, 2> Args;
869
70
  if (!checkTryLockFunAttrCommon(S, D, AL, Args))
870
9
    return;
871
872
61
  D->addAttr(::new (S.Context) SharedTrylockFunctionAttr(
873
61
      S.Context, AL, AL.getArgAsExpr(0), Args.data(), Args.size()));
874
61
}
875
876
static void handleExclusiveTrylockFunctionAttr(Sema &S, Decl *D,
877
78
                                               const ParsedAttr &AL) {
878
78
  SmallVector<Expr*, 2> Args;
879
78
  if (!checkTryLockFunAttrCommon(S, D, AL, Args))
880
9
    return;
881
882
69
  D->addAttr(::new (S.Context) ExclusiveTrylockFunctionAttr(
883
69
      S.Context, AL, AL.getArgAsExpr(0), Args.data(), Args.size()));
884
69
}
885
886
80
static void handleLockReturnedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
887
  // check that the argument is lockable object
888
80
  SmallVector<Expr*, 1> Args;
889
80
  checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
890
80
  unsigned Size = Args.size();
891
80
  if (Size == 0)
892
0
    return;
893
894
80
  D->addAttr(::new (S.Context) LockReturnedAttr(S.Context, AL, Args[0]));
895
80
}
896
897
142
static void handleLocksExcludedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
898
142
  if (!AL.checkAtLeastNumArgs(S, 1))
899
3
    return;
900
901
  // check that all arguments are lockable objects
902
139
  SmallVector<Expr*, 1> Args;
903
139
  checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
904
139
  unsigned Size = Args.size();
905
139
  if (Size == 0)
906
0
    return;
907
139
  Expr **StartArg = &Args[0];
908
909
139
  D->addAttr(::new (S.Context)
910
139
                 LocksExcludedAttr(S.Context, AL, StartArg, Size));
911
139
}
912
913
static bool checkFunctionConditionAttr(Sema &S, Decl *D, const ParsedAttr &AL,
914
19.2k
                                       Expr *&Cond, StringRef &Msg) {
915
19.2k
  Cond = AL.getArgAsExpr(0);
916
19.2k
  if (!Cond->isTypeDependent()) {
917
19.1k
    ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
918
19.1k
    if (Converted.isInvalid())
919
0
      return false;
920
19.1k
    Cond = Converted.get();
921
19.1k
  }
922
923
19.2k
  if (!S.checkStringLiteralArgumentAttr(AL, 1, Msg))
924
2
    return false;
925
926
19.2k
  if (Msg.empty())
927
9.31k
    Msg = "<no message provided>";
928
929
19.2k
  SmallVector<PartialDiagnosticAt, 8> Diags;
930
19.2k
  if (isa<FunctionDecl>(D) && 
!Cond->isValueDependent()19.2k
&&
931
19.2k
      !Expr::isPotentialConstantExprUnevaluated(Cond, cast<FunctionDecl>(D),
932
19.1k
                                                Diags)) {
933
3
    S.Diag(AL.getLoc(), diag::err_attr_cond_never_constant_expr) << AL;
934
3
    for (const PartialDiagnosticAt &PDiag : Diags)
935
3
      S.Diag(PDiag.first, PDiag.second);
936
3
    return false;
937
3
  }
938
19.2k
  return true;
939
19.2k
}
940
941
11.2k
static void handleEnableIfAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
942
11.2k
  S.Diag(AL.getLoc(), diag::ext_clang_enable_if);
943
944
11.2k
  Expr *Cond;
945
11.2k
  StringRef Msg;
946
11.2k
  if (checkFunctionConditionAttr(S, D, AL, Cond, Msg))
947
11.2k
    D->addAttr(::new (S.Context) EnableIfAttr(S.Context, AL, Cond, Msg));
948
11.2k
}
949
950
namespace {
951
/// Determines if a given Expr references any of the given function's
952
/// ParmVarDecls, or the function's implicit `this` parameter (if applicable).
953
class ArgumentDependenceChecker
954
    : public RecursiveASTVisitor<ArgumentDependenceChecker> {
955
#ifndef NDEBUG
956
  const CXXRecordDecl *ClassType;
957
#endif
958
  llvm::SmallPtrSet<const ParmVarDecl *, 16> Parms;
959
  bool Result;
960
961
public:
962
7.93k
  ArgumentDependenceChecker(const FunctionDecl *FD) {
963
7.93k
#ifndef NDEBUG
964
7.93k
    if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
965
3.41k
      ClassType = MD->getParent();
966
4.52k
    else
967
4.52k
      ClassType = nullptr;
968
7.93k
#endif
969
7.93k
    Parms.insert(FD->param_begin(), FD->param_end());
970
7.93k
  }
971
972
7.93k
  bool referencesArgs(Expr *E) {
973
7.93k
    Result = false;
974
7.93k
    TraverseStmt(E);
975
7.93k
    return Result;
976
7.93k
  }
977
978
27
  bool VisitCXXThisExpr(CXXThisExpr *E) {
979
27
    assert(E->getType()->getPointeeCXXRecordDecl() == ClassType &&
980
27
           "`this` doesn't refer to the enclosing class?");
981
0
    Result = true;
982
27
    return false;
983
27
  }
984
985
8.03k
  bool VisitDeclRefExpr(DeclRefExpr *DRE) {
986
8.03k
    if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
987
7.81k
      if (Parms.count(PVD)) {
988
7.81k
        Result = true;
989
7.81k
        return false;
990
7.81k
      }
991
220
    return true;
992
8.03k
  }
993
};
994
}
995
996
7.93k
static void handleDiagnoseIfAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
997
7.93k
  S.Diag(AL.getLoc(), diag::ext_clang_diagnose_if);
998
999
7.93k
  Expr *Cond;
1000
7.93k
  StringRef Msg;
1001
7.93k
  if (!checkFunctionConditionAttr(S, D, AL, Cond, Msg))
1002
3
    return;
1003
1004
7.93k
  StringRef DiagTypeStr;
1005
7.93k
  if (!S.checkStringLiteralArgumentAttr(AL, 2, DiagTypeStr))
1006
0
    return;
1007
1008
7.93k
  DiagnoseIfAttr::DiagnosticType DiagType;
1009
7.93k
  if (!DiagnoseIfAttr::ConvertStrToDiagnosticType(DiagTypeStr, DiagType)) {
1010
3
    S.Diag(AL.getArgAsExpr(2)->getBeginLoc(),
1011
3
           diag::err_diagnose_if_invalid_diagnostic_type);
1012
3
    return;
1013
3
  }
1014
1015
7.93k
  bool ArgDependent = false;
1016
7.93k
  if (const auto *FD = dyn_cast<FunctionDecl>(D))
1017
7.93k
    ArgDependent = ArgumentDependenceChecker(FD).referencesArgs(Cond);
1018
7.93k
  D->addAttr(::new (S.Context) DiagnoseIfAttr(
1019
7.93k
      S.Context, AL, Cond, Msg, DiagType, ArgDependent, cast<NamedDecl>(D)));
1020
7.93k
}
1021
1022
31
static void handleNoBuiltinAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1023
31
  static constexpr const StringRef kWildcard = "*";
1024
1025
31
  llvm::SmallVector<StringRef, 16> Names;
1026
31
  bool HasWildcard = false;
1027
1028
41
  const auto AddBuiltinName = [&Names, &HasWildcard](StringRef Name) {
1029
41
    if (Name == kWildcard)
1030
12
      HasWildcard = true;
1031
41
    Names.push_back(Name);
1032
41
  };
1033
1034
  // Add previously defined attributes.
1035
31
  if (const auto *NBA = D->getAttr<NoBuiltinAttr>())
1036
8
    for (StringRef BuiltinName : NBA->builtinNames())
1037
8
      AddBuiltinName(BuiltinName);
1038
1039
  // Add current attributes.
1040
31
  if (AL.getNumArgs() == 0)
1041
10
    AddBuiltinName(kWildcard);
1042
21
  else
1043
45
    
for (unsigned I = 0, E = AL.getNumArgs(); 21
I != E;
++I24
) {
1044
24
      StringRef BuiltinName;
1045
24
      SourceLocation LiteralLoc;
1046
24
      if (!S.checkStringLiteralArgumentAttr(AL, I, BuiltinName, &LiteralLoc))
1047
0
        return;
1048
1049
24
      if (Builtin::Context::isBuiltinFunc(BuiltinName))
1050
23
        AddBuiltinName(BuiltinName);
1051
1
      else
1052
1
        S.Diag(LiteralLoc, diag::warn_attribute_no_builtin_invalid_builtin_name)
1053
1
            << BuiltinName << AL;
1054
24
    }
1055
1056
  // Repeating the same attribute is fine.
1057
31
  llvm::sort(Names);
1058
31
  Names.erase(std::unique(Names.begin(), Names.end()), Names.end());
1059
1060
  // Empty no_builtin must be on its own.
1061
31
  if (HasWildcard && 
Names.size() > 111
)
1062
1
    S.Diag(D->getLocation(),
1063
1
           diag::err_attribute_no_builtin_wildcard_or_builtin_name)
1064
1
        << AL;
1065
1066
31
  if (D->hasAttr<NoBuiltinAttr>())
1067
8
    D->dropAttr<NoBuiltinAttr>();
1068
31
  D->addAttr(::new (S.Context)
1069
31
                 NoBuiltinAttr(S.Context, AL, Names.data(), Names.size()));
1070
31
}
1071
1072
134
static void handlePassObjectSizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1073
134
  if (D->hasAttr<PassObjectSizeAttr>()) {
1074
1
    S.Diag(D->getBeginLoc(), diag::err_attribute_only_once_per_parameter) << AL;
1075
1
    return;
1076
1
  }
1077
1078
133
  Expr *E = AL.getArgAsExpr(0);
1079
133
  uint32_t Type;
1080
133
  if (!checkUInt32Argument(S, AL, E, Type, /*Idx=*/1))
1081
2
    return;
1082
1083
  // pass_object_size's argument is passed in as the second argument of
1084
  // __builtin_object_size. So, it has the same constraints as that second
1085
  // argument; namely, it must be in the range [0, 3].
1086
131
  if (Type > 3) {
1087
2
    S.Diag(E->getBeginLoc(), diag::err_attribute_argument_out_of_range)
1088
2
        << AL << 0 << 3 << E->getSourceRange();
1089
2
    return;
1090
2
  }
1091
1092
  // pass_object_size is only supported on constant pointer parameters; as a
1093
  // kindness to users, we allow the parameter to be non-const for declarations.
1094
  // At this point, we have no clue if `D` belongs to a function declaration or
1095
  // definition, so we defer the constness check until later.
1096
129
  if (!cast<ParmVarDecl>(D)->getType()->isPointerType()) {
1097
3
    S.Diag(D->getBeginLoc(), diag::err_attribute_pointers_only) << AL << 1;
1098
3
    return;
1099
3
  }
1100
1101
126
  D->addAttr(::new (S.Context) PassObjectSizeAttr(S.Context, AL, (int)Type));
1102
126
}
1103
1104
7
static void handleConsumableAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1105
7
  ConsumableAttr::ConsumedState DefaultState;
1106
1107
7
  if (AL.isArgIdent(0)) {
1108
6
    IdentifierLoc *IL = AL.getArgAsIdent(0);
1109
6
    if (!ConsumableAttr::ConvertStrToConsumedState(IL->Ident->getName(),
1110
6
                                                   DefaultState)) {
1111
0
      S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << AL
1112
0
                                                               << IL->Ident;
1113
0
      return;
1114
0
    }
1115
6
  } else {
1116
1
    S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1117
1
        << AL << AANT_ArgumentIdentifier;
1118
1
    return;
1119
1
  }
1120
1121
6
  D->addAttr(::new (S.Context) ConsumableAttr(S.Context, AL, DefaultState));
1122
6
}
1123
1124
static bool checkForConsumableClass(Sema &S, const CXXMethodDecl *MD,
1125
31
                                    const ParsedAttr &AL) {
1126
31
  QualType ThisType = MD->getThisType()->getPointeeType();
1127
1128
31
  if (const CXXRecordDecl *RD = ThisType->getAsCXXRecordDecl()) {
1129
31
    if (!RD->hasAttr<ConsumableAttr>()) {
1130
3
      S.Diag(AL.getLoc(), diag::warn_attr_on_unconsumable_class) << RD;
1131
1132
3
      return false;
1133
3
    }
1134
31
  }
1135
1136
28
  return true;
1137
31
}
1138
1139
16
static void handleCallableWhenAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1140
16
  if (!AL.checkAtLeastNumArgs(S, 1))
1141
1
    return;
1142
1143
15
  if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), AL))
1144
1
    return;
1145
1146
14
  SmallVector<CallableWhenAttr::ConsumedState, 3> States;
1147
32
  for (unsigned ArgIndex = 0; ArgIndex < AL.getNumArgs(); 
++ArgIndex18
) {
1148
20
    CallableWhenAttr::ConsumedState CallableState;
1149
1150
20
    StringRef StateString;
1151
20
    SourceLocation Loc;
1152
20
    if (AL.isArgIdent(ArgIndex)) {
1153
1
      IdentifierLoc *Ident = AL.getArgAsIdent(ArgIndex);
1154
1
      StateString = Ident->Ident->getName();
1155
1
      Loc = Ident->Loc;
1156
19
    } else {
1157
19
      if (!S.checkStringLiteralArgumentAttr(AL, ArgIndex, StateString, &Loc))
1158
1
        return;
1159
19
    }
1160
1161
19
    if (!CallableWhenAttr::ConvertStrToConsumedState(StateString,
1162
19
                                                     CallableState)) {
1163
1
      S.Diag(Loc, diag::warn_attribute_type_not_supported) << AL << StateString;
1164
1
      return;
1165
1
    }
1166
1167
18
    States.push_back(CallableState);
1168
18
  }
1169
1170
12
  D->addAttr(::new (S.Context)
1171
12
                 CallableWhenAttr(S.Context, AL, States.data(), States.size()));
1172
12
}
1173
1174
7
static void handleParamTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1175
7
  ParamTypestateAttr::ConsumedState ParamState;
1176
1177
7
  if (AL.isArgIdent(0)) {
1178
7
    IdentifierLoc *Ident = AL.getArgAsIdent(0);
1179
7
    StringRef StateString = Ident->Ident->getName();
1180
1181
7
    if (!ParamTypestateAttr::ConvertStrToConsumedState(StateString,
1182
7
                                                       ParamState)) {
1183
0
      S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
1184
0
          << AL << StateString;
1185
0
      return;
1186
0
    }
1187
7
  } else {
1188
0
    S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1189
0
        << AL << AANT_ArgumentIdentifier;
1190
0
    return;
1191
0
  }
1192
1193
  // FIXME: This check is currently being done in the analysis.  It can be
1194
  //        enabled here only after the parser propagates attributes at
1195
  //        template specialization definition, not declaration.
1196
  //QualType ReturnType = cast<ParmVarDecl>(D)->getType();
1197
  //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
1198
  //
1199
  //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
1200
  //    S.Diag(AL.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
1201
  //      ReturnType.getAsString();
1202
  //    return;
1203
  //}
1204
1205
7
  D->addAttr(::new (S.Context) ParamTypestateAttr(S.Context, AL, ParamState));
1206
7
}
1207
1208
15
static void handleReturnTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1209
15
  ReturnTypestateAttr::ConsumedState ReturnState;
1210
1211
15
  if (AL.isArgIdent(0)) {
1212
14
    IdentifierLoc *IL = AL.getArgAsIdent(0);
1213
14
    if (!ReturnTypestateAttr::ConvertStrToConsumedState(IL->Ident->getName(),
1214
14
                                                        ReturnState)) {
1215
1
      S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << AL
1216
1
                                                               << IL->Ident;
1217
1
      return;
1218
1
    }
1219
14
  } else {
1220
1
    S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1221
1
        << AL << AANT_ArgumentIdentifier;
1222
1
    return;
1223
1
  }
1224
1225
  // FIXME: This check is currently being done in the analysis.  It can be
1226
  //        enabled here only after the parser propagates attributes at
1227
  //        template specialization definition, not declaration.
1228
  //QualType ReturnType;
1229
  //
1230
  //if (const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D)) {
1231
  //  ReturnType = Param->getType();
1232
  //
1233
  //} else if (const CXXConstructorDecl *Constructor =
1234
  //             dyn_cast<CXXConstructorDecl>(D)) {
1235
  //  ReturnType = Constructor->getThisType()->getPointeeType();
1236
  //
1237
  //} else {
1238
  //
1239
  //  ReturnType = cast<FunctionDecl>(D)->getCallResultType();
1240
  //}
1241
  //
1242
  //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
1243
  //
1244
  //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
1245
  //    S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
1246
  //      ReturnType.getAsString();
1247
  //    return;
1248
  //}
1249
1250
13
  D->addAttr(::new (S.Context) ReturnTypestateAttr(S.Context, AL, ReturnState));
1251
13
}
1252
1253
10
static void handleSetTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1254
10
  if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), AL))
1255
1
    return;
1256
1257
9
  SetTypestateAttr::ConsumedState NewState;
1258
9
  if (AL.isArgIdent(0)) {
1259
9
    IdentifierLoc *Ident = AL.getArgAsIdent(0);
1260
9
    StringRef Param = Ident->Ident->getName();
1261
9
    if (!SetTypestateAttr::ConvertStrToConsumedState(Param, NewState)) {
1262
0
      S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported) << AL
1263
0
                                                                  << Param;
1264
0
      return;
1265
0
    }
1266
9
  } else {
1267
0
    S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1268
0
        << AL << AANT_ArgumentIdentifier;
1269
0
    return;
1270
0
  }
1271
1272
9
  D->addAttr(::new (S.Context) SetTypestateAttr(S.Context, AL, NewState));
1273
9
}
1274
1275
6
static void handleTestTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1276
6
  if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), AL))
1277
1
    return;
1278
1279
5
  TestTypestateAttr::ConsumedState TestState;
1280
5
  if (AL.isArgIdent(0)) {
1281
5
    IdentifierLoc *Ident = AL.getArgAsIdent(0);
1282
5
    StringRef Param = Ident->Ident->getName();
1283
5
    if (!TestTypestateAttr::ConvertStrToConsumedState(Param, TestState)) {
1284
0
      S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported) << AL
1285
0
                                                                  << Param;
1286
0
      return;
1287
0
    }
1288
5
  } else {
1289
0
    S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1290
0
        << AL << AANT_ArgumentIdentifier;
1291
0
    return;
1292
0
  }
1293
1294
5
  D->addAttr(::new (S.Context) TestTypestateAttr(S.Context, AL, TestState));
1295
5
}
1296
1297
4.17k
static void handleExtVectorTypeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1298
  // Remember this typedef decl, we will need it later for diagnostics.
1299
4.17k
  S.ExtVectorDecls.push_back(cast<TypedefNameDecl>(D));
1300
4.17k
}
1301
1302
35.9k
static void handlePackedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1303
35.9k
  if (auto *TD = dyn_cast<TagDecl>(D))
1304
34.7k
    TD->addAttr(::new (S.Context) PackedAttr(S.Context, AL));
1305
1.20k
  else if (auto *FD = dyn_cast<FieldDecl>(D)) {
1306
1.19k
    bool BitfieldByteAligned = (!FD->getType()->isDependentType() &&
1307
1.19k
                                
!FD->getType()->isIncompleteType()1.19k
&&
1308
1.19k
                                
FD->isBitField()1.00k
&&
1309
1.19k
                                
S.Context.getTypeAlign(FD->getType()) <= 830
);
1310
1311
1.19k
    if (S.getASTContext().getTargetInfo().getTriple().isPS4()) {
1312
6
      if (BitfieldByteAligned)
1313
        // The PS4 target needs to maintain ABI backwards compatibility.
1314
1
        S.Diag(AL.getLoc(), diag::warn_attribute_ignored_for_field_of_type)
1315
1
            << AL << FD->getType();
1316
5
      else
1317
5
        FD->addAttr(::new (S.Context) PackedAttr(S.Context, AL));
1318
1.19k
    } else {
1319
      // Report warning about changed offset in the newer compiler versions.
1320
1.19k
      if (BitfieldByteAligned)
1321
2
        S.Diag(AL.getLoc(), diag::warn_attribute_packed_for_bitfield);
1322
1323
1.19k
      FD->addAttr(::new (S.Context) PackedAttr(S.Context, AL));
1324
1.19k
    }
1325
1326
1.19k
  } else
1327
10
    S.Diag(AL.getLoc(), diag::warn_attribute_ignored) << AL;
1328
35.9k
}
1329
1330
14.3k
static void handlePreferredName(Sema &S, Decl *D, const ParsedAttr &AL) {
1331
14.3k
  auto *RD = cast<CXXRecordDecl>(D);
1332
14.3k
  ClassTemplateDecl *CTD = RD->getDescribedClassTemplate();
1333
14.3k
  assert(CTD && "attribute does not appertain to this declaration");
1334
1335
0
  ParsedType PT = AL.getTypeArg();
1336
14.3k
  TypeSourceInfo *TSI = nullptr;
1337
14.3k
  QualType T = S.GetTypeFromParser(PT, &TSI);
1338
14.3k
  if (!TSI)
1339
0
    TSI = S.Context.getTrivialTypeSourceInfo(T, AL.getLoc());
1340
1341
14.3k
  if (!T.hasQualifiers() && 
T->isTypedefNameType()14.3k
) {
1342
    // Find the template name, if this type names a template specialization.
1343
14.3k
    const TemplateDecl *Template = nullptr;
1344
14.3k
    if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
1345
14.3k
            T->getAsCXXRecordDecl())) {
1346
14.3k
      Template = CTSD->getSpecializedTemplate();
1347
14.3k
    } else 
if (const auto *32
TST32
= T->getAs<TemplateSpecializationType>()) {
1348
8
      while (TST && TST->isTypeAlias())
1349
2
        TST = TST->getAliasedType()->getAs<TemplateSpecializationType>();
1350
6
      if (TST)
1351
6
        Template = TST->getTemplateName().getAsTemplateDecl();
1352
6
    }
1353
1354
14.3k
    if (Template && 
declaresSameEntity(Template, CTD)14.3k
) {
1355
14.3k
      D->addAttr(::new (S.Context) PreferredNameAttr(S.Context, AL, TSI));
1356
14.3k
      return;
1357
14.3k
    }
1358
14.3k
  }
1359
1360
34
  S.Diag(AL.getLoc(), diag::err_attribute_preferred_name_arg_invalid)
1361
34
      << T << CTD;
1362
34
  if (const auto *TT = T->getAs<TypedefType>())
1363
30
    S.Diag(TT->getDecl()->getLocation(), diag::note_entity_declared_at)
1364
30
        << TT->getDecl();
1365
34
}
1366
1367
146
static bool checkIBOutletCommon(Sema &S, Decl *D, const ParsedAttr &AL) {
1368
  // The IBOutlet/IBOutletCollection attributes only apply to instance
1369
  // variables or properties of Objective-C classes.  The outlet must also
1370
  // have an object reference type.
1371
146
  if (const auto *VD = dyn_cast<ObjCIvarDecl>(D)) {
1372
39
    if (!VD->getType()->getAs<ObjCObjectPointerType>()) {
1373
10
      S.Diag(AL.getLoc(), diag::warn_iboutlet_object_type)
1374
10
          << AL << VD->getType() << 0;
1375
10
      return false;
1376
10
    }
1377
39
  }
1378
107
  else if (const auto *PD = dyn_cast<ObjCPropertyDecl>(D)) {
1379
107
    if (!PD->getType()->getAs<ObjCObjectPointerType>()) {
1380
8
      S.Diag(AL.getLoc(), diag::warn_iboutlet_object_type)
1381
8
          << AL << PD->getType() << 1;
1382
8
      return false;
1383
8
    }
1384
107
  }
1385
0
  else {
1386
0
    S.Diag(AL.getLoc(), diag::warn_attribute_iboutlet) << AL;
1387
0
    return false;
1388
0
  }
1389
1390
128
  return true;
1391
146
}
1392
1393
111
static void handleIBOutlet(Sema &S, Decl *D, const ParsedAttr &AL) {
1394
111
  if (!checkIBOutletCommon(S, D, AL))
1395
14
    return;
1396
1397
97
  D->addAttr(::new (S.Context) IBOutletAttr(S.Context, AL));
1398
97
}
1399
1400
35
static void handleIBOutletCollection(Sema &S, Decl *D, const ParsedAttr &AL) {
1401
1402
  // The iboutletcollection attribute can have zero or one arguments.
1403
35
  if (AL.getNumArgs() > 1) {
1404
0
    S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
1405
0
    return;
1406
0
  }
1407
1408
35
  if (!checkIBOutletCommon(S, D, AL))
1409
4
    return;
1410
1411
31
  ParsedType PT;
1412
1413
31
  if (AL.hasParsedType())
1414
23
    PT = AL.getTypeArg();
1415
8
  else {
1416
8
    PT = S.getTypeName(S.Context.Idents.get("NSObject"), AL.getLoc(),
1417
8
                       S.getScopeForContext(D->getDeclContext()->getParent()));
1418
8
    if (!PT) {
1419
0
      S.Diag(AL.getLoc(), diag::err_iboutletcollection_type) << "NSObject";
1420
0
      return;
1421
0
    }
1422
8
  }
1423
1424
31
  TypeSourceInfo *QTLoc = nullptr;
1425
31
  QualType QT = S.GetTypeFromParser(PT, &QTLoc);
1426
31
  if (!QTLoc)
1427
8
    QTLoc = S.Context.getTrivialTypeSourceInfo(QT, AL.getLoc());
1428
1429
  // Diagnose use of non-object type in iboutletcollection attribute.
1430
  // FIXME. Gnu attribute extension ignores use of builtin types in
1431
  // attributes. So, __attribute__((iboutletcollection(char))) will be
1432
  // treated as __attribute__((iboutletcollection())).
1433
31
  if (!QT->isObjCIdType() && 
!QT->isObjCObjectType()26
) {
1434
4
    S.Diag(AL.getLoc(),
1435
4
           QT->isBuiltinType() ? 
diag::err_iboutletcollection_builtintype2
1436
4
                               : 
diag::err_iboutletcollection_type2
) << QT;
1437
4
    return;
1438
4
  }
1439
1440
27
  D->addAttr(::new (S.Context) IBOutletCollectionAttr(S.Context, AL, QTLoc));
1441
27
}
1442
1443
79.8k
bool Sema::isValidPointerAttrType(QualType T, bool RefOkay) {
1444
79.8k
  if (RefOkay) {
1445
24.3k
    if (T->isReferenceType())
1446
20
      return true;
1447
55.5k
  } else {
1448
55.5k
    T = T.getNonReferenceType();
1449
55.5k
  }
1450
1451
  // The nonnull attribute, and other similar attributes, can be applied to a
1452
  // transparent union that contains a pointer type.
1453
79.8k
  if (const RecordType *UT = T->getAsUnionType()) {
1454
18
    if (UT && UT->getDecl()->hasAttr<TransparentUnionAttr>()) {
1455
18
      RecordDecl *UD = UT->getDecl();
1456
23
      for (const auto *I : UD->fields()) {
1457
23
        QualType QT = I->getType();
1458
23
        if (QT->isAnyPointerType() || 
QT->isBlockPointerType()5
)
1459
18
          return true;
1460
23
      }
1461
18
    }
1462
18
  }
1463
1464
79.8k
  return T->isAnyPointerType() || 
T->isBlockPointerType()25.9k
;
1465
79.8k
}
1466
1467
static bool attrNonNullArgCheck(Sema &S, QualType T, const ParsedAttr &AL,
1468
                                SourceRange AttrParmRange,
1469
                                SourceRange TypeRange,
1470
54.7k
                                bool isReturnValue = false) {
1471
54.7k
  if (!S.isValidPointerAttrType(T)) {
1472
17
    if (isReturnValue)
1473
6
      S.Diag(AL.getLoc(), diag::warn_attribute_return_pointers_only)
1474
6
          << AL << AttrParmRange << TypeRange;
1475
11
    else
1476
11
      S.Diag(AL.getLoc(), diag::warn_attribute_pointers_only)
1477
11
          << AL << AttrParmRange << TypeRange << 0;
1478
17
    return false;
1479
17
  }
1480
54.6k
  return true;
1481
54.7k
}
1482
1483
71.4k
static void handleNonNullAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1484
71.4k
  SmallVector<ParamIdx, 8> NonNullArgs;
1485
126k
  for (unsigned I = 0; I < AL.getNumArgs(); 
++I54.6k
) {
1486
54.6k
    Expr *Ex = AL.getArgAsExpr(I);
1487
54.6k
    ParamIdx Idx;
1488
54.6k
    if (!checkFunctionOrMethodParameterIndex(S, D, AL, I + 1, Ex, Idx))
1489
5
      return;
1490
1491
    // Is the function argument a pointer type?
1492
54.6k
    if (Idx.getASTIndex() < getFunctionOrMethodNumParams(D) &&
1493
54.6k
        !attrNonNullArgCheck(
1494
54.6k
            S, getFunctionOrMethodParamType(D, Idx.getASTIndex()), AL,
1495
54.6k
            Ex->getSourceRange(),
1496
54.6k
            getFunctionOrMethodParamRange(D, Idx.getASTIndex())))
1497
7
      continue;
1498
1499
54.6k
    NonNullArgs.push_back(Idx);
1500
54.6k
  }
1501
1502
  // If no arguments were specified to __attribute__((nonnull)) then all pointer
1503
  // arguments have a nonnull attribute; warn if there aren't any. Skip this
1504
  // check if the attribute came from a macro expansion or a template
1505
  // instantiation.
1506
71.4k
  if (NonNullArgs.empty() && 
AL.getLoc().isFileID()19.1k
&&
1507
71.4k
      
!S.inTemplateInstantiation()65
) {
1508
65
    bool AnyPointers = isFunctionOrMethodVariadic(D);
1509
65
    for (unsigned I = 0, E = getFunctionOrMethodNumParams(D);
1510
120
         I != E && 
!AnyPointers82
;
++I55
) {
1511
55
      QualType T = getFunctionOrMethodParamType(D, I);
1512
55
      if (T->isDependentType() || 
S.isValidPointerAttrType(T)53
)
1513
47
        AnyPointers = true;
1514
55
    }
1515
1516
65
    if (!AnyPointers)
1517
6
      S.Diag(AL.getLoc(), diag::warn_attribute_nonnull_no_pointers);
1518
65
  }
1519
1520
71.4k
  ParamIdx *Start = NonNullArgs.data();
1521
71.4k
  unsigned Size = NonNullArgs.size();
1522
71.4k
  llvm::array_pod_sort(Start, Start + Size);
1523
71.4k
  D->addAttr(::new (S.Context) NonNullAttr(S.Context, AL, Start, Size));
1524
71.4k
}
1525
1526
static void handleNonNullAttrParameter(Sema &S, ParmVarDecl *D,
1527
47
                                       const ParsedAttr &AL) {
1528
47
  if (AL.getNumArgs() > 0) {
1529
6
    if (D->getFunctionType()) {
1530
3
      handleNonNullAttr(S, D, AL);
1531
3
    } else {
1532
3
      S.Diag(AL.getLoc(), diag::warn_attribute_nonnull_parm_no_args)
1533
3
        << D->getSourceRange();
1534
3
    }
1535
6
    return;
1536
6
  }
1537
1538
  // Is the argument a pointer type?
1539
41
  if (!attrNonNullArgCheck(S, D->getType(), AL, SourceRange(),
1540
41
                           D->getSourceRange()))
1541
4
    return;
1542
1543
37
  D->addAttr(::new (S.Context) NonNullAttr(S.Context, AL, nullptr, 0));
1544
37
}
1545
1546
30
static void handleReturnsNonNullAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1547
30
  QualType ResultType = getFunctionOrMethodResultType(D);
1548
30
  SourceRange SR = getFunctionOrMethodResultSourceRange(D);
1549
30
  if (!attrNonNullArgCheck(S, ResultType, AL, SourceRange(), SR,
1550
30
                           /* isReturnValue */ true))
1551
6
    return;
1552
1553
24
  D->addAttr(::new (S.Context) ReturnsNonNullAttr(S.Context, AL));
1554
24
}
1555
1556
24.2k
static void handleNoEscapeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1557
24.2k
  if (D->isInvalidDecl())
1558
0
    return;
1559
1560
  // noescape only applies to pointer types.
1561
24.2k
  QualType T = cast<ParmVarDecl>(D)->getType();
1562
24.2k
  if (!S.isValidPointerAttrType(T, /* RefOkay */ true)) {
1563
8
    S.Diag(AL.getLoc(), diag::warn_attribute_pointers_only)
1564
8
        << AL << AL.getRange() << 0;
1565
8
    return;
1566
8
  }
1567
1568
24.2k
  D->addAttr(::new (S.Context) NoEscapeAttr(S.Context, AL));
1569
24.2k
}
1570
1571
27
static void handleAssumeAlignedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1572
27
  Expr *E = AL.getArgAsExpr(0),
1573
27
       *OE = AL.getNumArgs() > 1 ? 
AL.getArgAsExpr(1)9
:
nullptr18
;
1574
27
  S.AddAssumeAlignedAttr(D, AL, E, OE);
1575
27
}
1576
1577
36
static void handleAllocAlignAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1578
36
  S.AddAllocAlignAttr(D, AL, AL.getArgAsExpr(0));
1579
36
}
1580
1581
void Sema::AddAssumeAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
1582
35
                                Expr *OE) {
1583
35
  QualType ResultType = getFunctionOrMethodResultType(D);
1584
35
  SourceRange SR = getFunctionOrMethodResultSourceRange(D);
1585
1586
35
  AssumeAlignedAttr TmpAttr(Context, CI, E, OE);
1587
35
  SourceLocation AttrLoc = TmpAttr.getLocation();
1588
1589
35
  if (!isValidPointerAttrType(ResultType, /* RefOkay */ true)) {
1590
3
    Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only)
1591
3
        << &TmpAttr << TmpAttr.getRange() << SR;
1592
3
    return;
1593
3
  }
1594
1595
32
  if (!E->isValueDependent()) {
1596
28
    Optional<llvm::APSInt> I = llvm::APSInt(64);
1597
28
    if (!(I = E->getIntegerConstantExpr(Context))) {
1598
0
      if (OE)
1599
0
        Diag(AttrLoc, diag::err_attribute_argument_n_type)
1600
0
          << &TmpAttr << 1 << AANT_ArgumentIntegerConstant
1601
0
          << E->getSourceRange();
1602
0
      else
1603
0
        Diag(AttrLoc, diag::err_attribute_argument_type)
1604
0
          << &TmpAttr << AANT_ArgumentIntegerConstant
1605
0
          << E->getSourceRange();
1606
0
      return;
1607
0
    }
1608
1609
28
    if (!I->isPowerOf2()) {
1610
5
      Diag(AttrLoc, diag::err_alignment_not_power_of_two)
1611
5
        << E->getSourceRange();
1612
5
      return;
1613
5
    }
1614
1615
23
    if (*I > Sema::MaximumAlignment)
1616
5
      Diag(CI.getLoc(), diag::warn_assume_aligned_too_great)
1617
5
          << CI.getRange() << Sema::MaximumAlignment;
1618
23
  }
1619
1620
27
  if (OE && 
!OE->isValueDependent()10
&&
!OE->isIntegerConstantExpr(Context)8
) {
1621
0
    Diag(AttrLoc, diag::err_attribute_argument_n_type)
1622
0
        << &TmpAttr << 2 << AANT_ArgumentIntegerConstant
1623
0
        << OE->getSourceRange();
1624
0
    return;
1625
0
  }
1626
1627
27
  D->addAttr(::new (Context) AssumeAlignedAttr(Context, CI, E, OE));
1628
27
}
1629
1630
void Sema::AddAllocAlignAttr(Decl *D, const AttributeCommonInfo &CI,
1631
44
                             Expr *ParamExpr) {
1632
44
  QualType ResultType = getFunctionOrMethodResultType(D);
1633
1634
44
  AllocAlignAttr TmpAttr(Context, CI, ParamIdx());
1635
44
  SourceLocation AttrLoc = CI.getLoc();
1636
1637
44
  if (!ResultType->isDependentType() &&
1638
44
      
!isValidPointerAttrType(ResultType, /* RefOkay */ true)42
) {
1639
2
    Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only)
1640
2
        << &TmpAttr << CI.getRange() << getFunctionOrMethodResultSourceRange(D);
1641
2
    return;
1642
2
  }
1643
1644
42
  ParamIdx Idx;
1645
42
  const auto *FuncDecl = cast<FunctionDecl>(D);
1646
42
  if (!checkFunctionOrMethodParameterIndex(*this, FuncDecl, TmpAttr,
1647
42
                                           /*AttrArgNum=*/1, ParamExpr, Idx))
1648
5
    return;
1649
1650
37
  QualType Ty = getFunctionOrMethodParamType(D, Idx.getASTIndex());
1651
37
  if (!Ty->isDependentType() && 
!Ty->isIntegralType(Context)35
&&
1652
37
      
!Ty->isAlignValT()9
) {
1653
3
    Diag(ParamExpr->getBeginLoc(), diag::err_attribute_integers_only)
1654
3
        << &TmpAttr
1655
3
        << FuncDecl->getParamDecl(Idx.getASTIndex())->getSourceRange();
1656
3
    return;
1657
3
  }
1658
1659
34
  D->addAttr(::new (Context) AllocAlignAttr(Context, CI, Idx));
1660
34
}
1661
1662
/// Check if \p AssumptionStr is a known assumption and warn if not.
1663
static void checkAssumptionAttr(Sema &S, SourceLocation Loc,
1664
87
                                StringRef AssumptionStr) {
1665
87
  if (llvm::KnownAssumptionStrings.count(AssumptionStr))
1666
7
    return;
1667
1668
80
  unsigned BestEditDistance = 3;
1669
80
  StringRef Suggestion;
1670
320
  for (const auto &KnownAssumptionIt : llvm::KnownAssumptionStrings) {
1671
320
    unsigned EditDistance =
1672
320
        AssumptionStr.edit_distance(KnownAssumptionIt.getKey());
1673
320
    if (EditDistance < BestEditDistance) {
1674
3
      Suggestion = KnownAssumptionIt.getKey();
1675
3
      BestEditDistance = EditDistance;
1676
3
    }
1677
320
  }
1678
1679
80
  if (!Suggestion.empty())
1680
3
    S.Diag(Loc, diag::warn_assume_attribute_string_unknown_suggested)
1681
3
        << AssumptionStr << Suggestion;
1682
77
  else
1683
77
    S.Diag(Loc, diag::warn_assume_attribute_string_unknown) << AssumptionStr;
1684
80
}
1685
1686
88
static void handleAssumumptionAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1687
  // Handle the case where the attribute has a text message.
1688
88
  StringRef Str;
1689
88
  SourceLocation AttrStrLoc;
1690
88
  if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &AttrStrLoc))
1691
1
    return;
1692
1693
87
  checkAssumptionAttr(S, AttrStrLoc, Str);
1694
1695
87
  D->addAttr(::new (S.Context) AssumptionAttr(S.Context, AL, Str));
1696
87
}
1697
1698
/// Normalize the attribute, __foo__ becomes foo.
1699
/// Returns true if normalization was applied.
1700
35.7k
static bool normalizeName(StringRef &AttrName) {
1701
35.7k
  if (AttrName.size() > 4 && 
AttrName.startswith("__")35.4k
&&
1702
35.7k
      
AttrName.endswith("__")33.2k
) {
1703
33.2k
    AttrName = AttrName.drop_front(2).drop_back(2);
1704
33.2k
    return true;
1705
33.2k
  }
1706
2.46k
  return false;
1707
35.7k
}
1708
1709
52
static void handleOwnershipAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1710
  // This attribute must be applied to a function declaration. The first
1711
  // argument to the attribute must be an identifier, the name of the resource,
1712
  // for example: malloc. The following arguments must be argument indexes, the
1713
  // arguments must be of integer type for Returns, otherwise of pointer type.
1714
  // The difference between Holds and Takes is that a pointer may still be used
1715
  // after being held. free() should be __attribute((ownership_takes)), whereas
1716
  // a list append function may well be __attribute((ownership_holds)).
1717
1718
52
  if (!AL.isArgIdent(0)) {
1719
1
    S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
1720
1
        << AL << 1 << AANT_ArgumentIdentifier;
1721
1
    return;
1722
1
  }
1723
1724
  // Figure out our Kind.
1725
51
  OwnershipAttr::OwnershipKind K =
1726
51
      OwnershipAttr(S.Context, AL, nullptr, nullptr, 0).getOwnKind();
1727
1728
  // Check arguments.
1729
51
  switch (K) {
1730
12
  case OwnershipAttr::Takes:
1731
32
  case OwnershipAttr::Holds:
1732
32
    if (AL.getNumArgs() < 2) {
1733
2
      S.Diag(AL.getLoc(), diag::err_attribute_too_few_arguments) << AL << 2;
1734
2
      return;
1735
2
    }
1736
30
    break;
1737
30
  case OwnershipAttr::Returns:
1738
19
    if (AL.getNumArgs() > 2) {
1739
1
      S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments) << AL << 1;
1740
1
      return;
1741
1
    }
1742
18
    break;
1743
51
  }
1744
1745
48
  IdentifierInfo *Module = AL.getArgAsIdent(0)->Ident;
1746
1747
48
  StringRef ModuleName = Module->getName();
1748
48
  if (normalizeName(ModuleName)) {
1749
0
    Module = &S.PP.getIdentifierTable().get(ModuleName);
1750
0
  }
1751
1752
48
  SmallVector<ParamIdx, 8> OwnershipArgs;
1753
91
  for (unsigned i = 1; i < AL.getNumArgs(); 
++i43
) {
1754
52
    Expr *Ex = AL.getArgAsExpr(i);
1755
52
    ParamIdx Idx;
1756
52
    if (!checkFunctionOrMethodParameterIndex(S, D, AL, i, Ex, Idx))
1757
3
      return;
1758
1759
    // Is the function argument a pointer type?
1760
49
    QualType T = getFunctionOrMethodParamType(D, Idx.getASTIndex());
1761
49
    int Err = -1;  // No error
1762
49
    switch (K) {
1763
15
      case OwnershipAttr::Takes:
1764
38
      case OwnershipAttr::Holds:
1765
38
        if (!T->isAnyPointerType() && 
!T->isBlockPointerType()1
)
1766
1
          Err = 0;
1767
38
        break;
1768
11
      case OwnershipAttr::Returns:
1769
11
        if (!T->isIntegerType())
1770
2
          Err = 1;
1771
11
        break;
1772
49
    }
1773
49
    if (-1 != Err) {
1774
3
      S.Diag(AL.getLoc(), diag::err_ownership_type) << AL << Err
1775
3
                                                    << Ex->getSourceRange();
1776
3
      return;
1777
3
    }
1778
1779
    // Check we don't have a conflict with another ownership attribute.
1780
46
    for (const auto *I : D->specific_attrs<OwnershipAttr>()) {
1781
      // Cannot have two ownership attributes of different kinds for the same
1782
      // index.
1783
8
      if (I->getOwnKind() != K && I->args_end() !=
1784
2
          std::find(I->args_begin(), I->args_end(), Idx)) {
1785
1
        S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible) << AL << I;
1786
1
        return;
1787
7
      } else if (K == OwnershipAttr::Returns &&
1788
7
                 
I->getOwnKind() == OwnershipAttr::Returns2
) {
1789
        // A returns attribute conflicts with any other returns attribute using
1790
        // a different index.
1791
2
        if (std::find(I->args_begin(), I->args_end(), Idx) == I->args_end()) {
1792
2
          S.Diag(I->getLocation(), diag::err_ownership_returns_index_mismatch)
1793
2
              << I->args_begin()->getSourceIndex();
1794
2
          if (I->args_size())
1795
2
            S.Diag(AL.getLoc(), diag::note_ownership_returns_index_mismatch)
1796
2
                << Idx.getSourceIndex() << Ex->getSourceRange();
1797
2
          return;
1798
2
        }
1799
2
      }
1800
8
    }
1801
43
    OwnershipArgs.push_back(Idx);
1802
43
  }
1803
1804
39
  ParamIdx *Start = OwnershipArgs.data();
1805
39
  unsigned Size = OwnershipArgs.size();
1806
39
  llvm::array_pod_sort(Start, Start + Size);
1807
39
  D->addAttr(::new (S.Context)
1808
39
                 OwnershipAttr(S.Context, AL, Module, Start, Size));
1809
39
}
1810
1811
48
static void handleWeakRefAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1812
  // Check the attribute arguments.
1813
48
  if (AL.getNumArgs() > 1) {
1814
0
    S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
1815
0
    return;
1816
0
  }
1817
1818
  // gcc rejects
1819
  // class c {
1820
  //   static int a __attribute__((weakref ("v2")));
1821
  //   static int b() __attribute__((weakref ("f3")));
1822
  // };
1823
  // and ignores the attributes of
1824
  // void f(void) {
1825
  //   static int a __attribute__((weakref ("v2")));
1826
  // }
1827
  // we reject them
1828
48
  const DeclContext *Ctx = D->getDeclContext()->getRedeclContext();
1829
48
  if (!Ctx->isFileContext()) {
1830
3
    S.Diag(AL.getLoc(), diag::err_attribute_weakref_not_global_context)
1831
3
        << cast<NamedDecl>(D);
1832
3
    return;
1833
3
  }
1834
1835
  // The GCC manual says
1836
  //
1837
  // At present, a declaration to which `weakref' is attached can only
1838
  // be `static'.
1839
  //
1840
  // It also says
1841
  //
1842
  // Without a TARGET,
1843
  // given as an argument to `weakref' or to `alias', `weakref' is
1844
  // equivalent to `weak'.
1845
  //
1846
  // gcc 4.4.1 will accept
1847
  // int a7 __attribute__((weakref));
1848
  // as
1849
  // int a7 __attribute__((weak));
1850
  // This looks like a bug in gcc. We reject that for now. We should revisit
1851
  // it if this behaviour is actually used.
1852
1853
  // GCC rejects
1854
  // static ((alias ("y"), weakref)).
1855
  // Should we? How to check that weakref is before or after alias?
1856
1857
  // FIXME: it would be good for us to keep the WeakRefAttr as-written instead
1858
  // of transforming it into an AliasAttr.  The WeakRefAttr never uses the
1859
  // StringRef parameter it was given anyway.
1860
45
  StringRef Str;
1861
45
  if (AL.getNumArgs() && 
S.checkStringLiteralArgumentAttr(AL, 0, Str)36
)
1862
    // GCC will accept anything as the argument of weakref. Should we
1863
    // check for an existing decl?
1864
35
    D->addAttr(::new (S.Context) AliasAttr(S.Context, AL, Str));
1865
1866
45
  D->addAttr(::new (S.Context) WeakRefAttr(S.Context, AL));
1867
45
}
1868
1869
15
static void handleIFuncAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1870
15
  StringRef Str;
1871
15
  if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
1872
0
    return;
1873
1874
  // Aliases should be on declarations, not definitions.
1875
15
  const auto *FD = cast<FunctionDecl>(D);
1876
15
  if (FD->isThisDeclarationADefinition()) {
1877
0
    S.Diag(AL.getLoc(), diag::err_alias_is_definition) << FD << 1;
1878
0
    return;
1879
0
  }
1880
1881
15
  D->addAttr(::new (S.Context) IFuncAttr(S.Context, AL, Str));
1882
15
}
1883
1884
155
static void handleAliasAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1885
155
  StringRef Str;
1886
155
  if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
1887
0
    return;
1888
1889
155
  if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
1890
1
    S.Diag(AL.getLoc(), diag::err_alias_not_supported_on_darwin);
1891
1
    return;
1892
1
  }
1893
154
  if (S.Context.getTargetInfo().getTriple().isNVPTX()) {
1894
1
    S.Diag(AL.getLoc(), diag::err_alias_not_supported_on_nvptx);
1895
1
  }
1896
1897
  // Aliases should be on declarations, not definitions.
1898
154
  if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
1899
106
    if (FD->isThisDeclarationADefinition()) {
1900
0
      S.Diag(AL.getLoc(), diag::err_alias_is_definition) << FD << 0;
1901
0
      return;
1902
0
    }
1903
106
  } else {
1904
48
    const auto *VD = cast<VarDecl>(D);
1905
48
    if (VD->isThisDeclarationADefinition() && 
VD->isExternallyVisible()11
) {
1906
1
      S.Diag(AL.getLoc(), diag::err_alias_is_definition) << VD << 0;
1907
1
      return;
1908
1
    }
1909
48
  }
1910
1911
  // Mark target used to prevent unneeded-internal-declaration warnings.
1912
153
  if (!S.LangOpts.CPlusPlus) {
1913
    // FIXME: demangle Str for C++, as the attribute refers to the mangled
1914
    // linkage name, not the pre-mangled identifier.
1915
117
    const DeclarationNameInfo target(&S.Context.Idents.get(Str), AL.getLoc());
1916
117
    LookupResult LR(S, target, Sema::LookupOrdinaryName);
1917
117
    if (S.LookupQualifiedName(LR, S.getCurLexicalContext()))
1918
96
      for (NamedDecl *ND : LR)
1919
96
        ND->markUsed(S.Context);
1920
117
  }
1921
1922
153
  D->addAttr(::new (S.Context) AliasAttr(S.Context, AL, Str));
1923
153
}
1924
1925
33
static void handleTLSModelAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1926
33
  StringRef Model;
1927
33
  SourceLocation LiteralLoc;
1928
  // Check that it is a string.
1929
33
  if (!S.checkStringLiteralArgumentAttr(AL, 0, Model, &LiteralLoc))
1930
1
    return;
1931
1932
  // Check that the value.
1933
32
  if (Model != "global-dynamic" && 
Model != "local-dynamic"26
1934
32
      && 
Model != "initial-exec"21
&&
Model != "local-exec"7
) {
1935
1
    S.Diag(LiteralLoc, diag::err_attr_tlsmodel_arg);
1936
1
    return;
1937
1
  }
1938
1939
31
  if (S.Context.getTargetInfo().getTriple().isOSAIX() &&
1940
31
      
Model != "global-dynamic"8
) {
1941
6
    S.Diag(LiteralLoc, diag::err_aix_attr_unsupported_tls_model) << Model;
1942
6
    return;
1943
6
  }
1944
1945
25
  D->addAttr(::new (S.Context) TLSModelAttr(S.Context, AL, Model));
1946
25
}
1947
1948
11.9k
static void handleRestrictAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1949
11.9k
  QualType ResultType = getFunctionOrMethodResultType(D);
1950
11.9k
  if (ResultType->isAnyPointerType() || 
ResultType->isBlockPointerType()5
) {
1951
11.9k
    D->addAttr(::new (S.Context) RestrictAttr(S.Context, AL));
1952
11.9k
    return;
1953
11.9k
  }
1954
1955
4
  S.Diag(AL.getLoc(), diag::warn_attribute_return_pointers_only)
1956
4
      << AL << getFunctionOrMethodResultSourceRange(D);
1957
4
}
1958
1959
130
static void handleCPUSpecificAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1960
130
  FunctionDecl *FD = cast<FunctionDecl>(D);
1961
1962
130
  if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
1963
38
    if (MD->getParent()->isLambda()) {
1964
1
      S.Diag(AL.getLoc(), diag::err_attribute_dll_lambda) << AL;
1965
1
      return;
1966
1
    }
1967
38
  }
1968
1969
129
  if (!AL.checkAtLeastNumArgs(S, 1))
1970
2
    return;
1971
1972
127
  SmallVector<IdentifierInfo *, 8> CPUs;
1973
314
  for (unsigned ArgNo = 0; ArgNo < getNumAttributeArgs(AL); 
++ArgNo187
) {
1974
191
    if (!AL.isArgIdent(ArgNo)) {
1975
0
      S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1976
0
          << AL << AANT_ArgumentIdentifier;
1977
0
      return;
1978
0
    }
1979
1980
191
    IdentifierLoc *CPUArg = AL.getArgAsIdent(ArgNo);
1981
191
    StringRef CPUName = CPUArg->Ident->getName().trim();
1982
1983
191
    if (!S.Context.getTargetInfo().validateCPUSpecificCPUDispatch(CPUName)) {
1984
2
      S.Diag(CPUArg->Loc, diag::err_invalid_cpu_specific_dispatch_value)
1985
2
          << CPUName << (AL.getKind() == ParsedAttr::AT_CPUDispatch);
1986
2
      return;
1987
2
    }
1988
1989
189
    const TargetInfo &Target = S.Context.getTargetInfo();
1990
189
    if (llvm::any_of(CPUs, [CPUName, &Target](const IdentifierInfo *Cur) {
1991
93
          return Target.CPUSpecificManglingCharacter(CPUName) ==
1992
93
                 Target.CPUSpecificManglingCharacter(Cur->getName());
1993
93
        })) {
1994
2
      S.Diag(AL.getLoc(), diag::warn_multiversion_duplicate_entries);
1995
2
      return;
1996
2
    }
1997
187
    CPUs.push_back(CPUArg->Ident);
1998
187
  }
1999
2000
123
  FD->setIsMultiVersion(true);
2001
123
  if (AL.getKind() == ParsedAttr::AT_CPUSpecific)
2002
84
    D->addAttr(::new (S.Context)
2003
84
                   CPUSpecificAttr(S.Context, AL, CPUs.data(), CPUs.size()));
2004
39
  else
2005
39
    D->addAttr(::new (S.Context)
2006
39
                   CPUDispatchAttr(S.Context, AL, CPUs.data(), CPUs.size()));
2007
123
}
2008
2009
9
static void handleCommonAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2010
9
  if (S.LangOpts.CPlusPlus) {
2011
1
    S.Diag(AL.getLoc(), diag::err_attribute_not_supported_in_lang)
2012
1
        << AL << AttributeLangSupport::Cpp;
2013
1
    return;
2014
1
  }
2015
2016
8
  D->addAttr(::new (S.Context) CommonAttr(S.Context, AL));
2017
8
}
2018
2019
100
static void handleCmseNSEntryAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2020
100
  if (S.LangOpts.CPlusPlus && 
!D->getDeclContext()->isExternCContext()2
) {
2021
1
    S.Diag(AL.getLoc(), diag::err_attribute_not_clinkage) << AL;
2022
1
    return;
2023
1
  }
2024
2025
99
  const auto *FD = cast<FunctionDecl>(D);
2026
99
  if (!FD->isExternallyVisible()) {
2027
1
    S.Diag(AL.getLoc(), diag::warn_attribute_cmse_entry_static);
2028
1
    return;
2029
1
  }
2030
2031
98
  D->addAttr(::new (S.Context) CmseNSEntryAttr(S.Context, AL));
2032
98
}
2033
2034
32
static void handleNakedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2035
32
  if (AL.isDeclspecAttribute()) {
2036
9
    const auto &Triple = S.getASTContext().getTargetInfo().getTriple();
2037
9
    const auto &Arch = Triple.getArch();
2038
9
    if (Arch != llvm::Triple::x86 &&
2039
9
        
(2
Arch != llvm::Triple::arm2
&&
Arch != llvm::Triple::thumb2
)) {
2040
1
      S.Diag(AL.getLoc(), diag::err_attribute_not_supported_on_arch)
2041
1
          << AL << Triple.getArchName();
2042
1
      return;
2043
1
    }
2044
9
  }
2045
2046
31
  D->addAttr(::new (S.Context) NakedAttr(S.Context, AL));
2047
31
}
2048
2049
7.30k
static void handleNoReturnAttr(Sema &S, Decl *D, const ParsedAttr &Attrs) {
2050
7.30k
  if (hasDeclarator(D)) 
return7.29k
;
2051
2052
19
  if (!isa<ObjCMethodDecl>(D)) {
2053
4
    S.Diag(Attrs.getLoc(), diag::warn_attribute_wrong_decl_type)
2054
4
        << Attrs << ExpectedFunctionOrMethod;
2055
4
    return;
2056
4
  }
2057
2058
15
  D->addAttr(::new (S.Context) NoReturnAttr(S.Context, Attrs));
2059
15
}
2060
2061
19
static void handleNoCfCheckAttr(Sema &S, Decl *D, const ParsedAttr &Attrs) {
2062
19
  if (!S.getLangOpts().CFProtectionBranch)
2063
0
    S.Diag(Attrs.getLoc(), diag::warn_nocf_check_attribute_ignored);
2064
19
  else
2065
19
    handleSimpleAttribute<AnyX86NoCfCheckAttr>(S, D, Attrs);
2066
19
}
2067
2068
89.1k
bool Sema::CheckAttrNoArgs(const ParsedAttr &Attrs) {
2069
89.1k
  if (!Attrs.checkExactlyNumArgs(*this, 0)) {
2070
6
    Attrs.setInvalid();
2071
6
    return true;
2072
6
  }
2073
2074
89.1k
  return false;
2075
89.1k
}
2076
2077
107M
bool Sema::CheckAttrTarget(const ParsedAttr &AL) {
2078
  // Check whether the attribute is valid on the current target.
2079
107M
  if (!AL.existsInTarget(Context.getTargetInfo())) {
2080
11
    Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored)
2081
11
        << AL << AL.getRange();
2082
11
    AL.setInvalid();
2083
11
    return true;
2084
11
  }
2085
2086
107M
  return false;
2087
107M
}
2088
2089
7
static void handleAnalyzerNoReturnAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2090
2091
  // The checking path for 'noreturn' and 'analyzer_noreturn' are different
2092
  // because 'analyzer_noreturn' does not impact the type.
2093
7
  if (!isFunctionOrMethodOrBlock(D)) {
2094
0
    ValueDecl *VD = dyn_cast<ValueDecl>(D);
2095
0
    if (!VD || (!VD->getType()->isBlockPointerType() &&
2096
0
                !VD->getType()->isFunctionPointerType())) {
2097
0
      S.Diag(AL.getLoc(), AL.isStandardAttributeSyntax()
2098
0
                              ? diag::err_attribute_wrong_decl_type
2099
0
                              : diag::warn_attribute_wrong_decl_type)
2100
0
          << AL << ExpectedFunctionMethodOrBlock;
2101
0
      return;
2102
0
    }
2103
0
  }
2104
2105
7
  D->addAttr(::new (S.Context) AnalyzerNoReturnAttr(S.Context, AL));
2106
7
}
2107
2108
// PS3 PPU-specific.
2109
17
static void handleVecReturnAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2110
  /*
2111
    Returning a Vector Class in Registers
2112
2113
    According to the PPU ABI specifications, a class with a single member of
2114
    vector type is returned in memory when used as the return value of a
2115
    function.
2116
    This results in inefficient code when implementing vector classes. To return
2117
    the value in a single vector register, add the vecreturn attribute to the
2118
    class definition. This attribute is also applicable to struct types.
2119
2120
    Example:
2121
2122
    struct Vector
2123
    {
2124
      __vector float xyzw;
2125
    } __attribute__((vecreturn));
2126
2127
    Vector Add(Vector lhs, Vector rhs)
2128
    {
2129
      Vector result;
2130
      result.xyzw = vec_add(lhs.xyzw, rhs.xyzw);
2131
      return result; // This will be returned in a register
2132
    }
2133
  */
2134
17
  if (VecReturnAttr *A = D->getAttr<VecReturnAttr>()) {
2135
1
    S.Diag(AL.getLoc(), diag::err_repeat_attribute) << A;
2136
1
    return;
2137
1
  }
2138
2139
16
  const auto *R = cast<RecordDecl>(D);
2140
16
  int count = 0;
2141
2142
16
  if (!isa<CXXRecordDecl>(R)) {
2143
0
    S.Diag(AL.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
2144
0
    return;
2145
0
  }
2146
2147
16
  if (!cast<CXXRecordDecl>(R)->isPOD()) {
2148
5
    S.Diag(AL.getLoc(), diag::err_attribute_vecreturn_only_pod_record);
2149
5
    return;
2150
5
  }
2151
2152
16
  
for (const auto *I : R->fields())11
{
2153
16
    if ((count == 1) || 
!I->getType()->isVectorType()11
) {
2154
5
      S.Diag(AL.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
2155
5
      return;
2156
5
    }
2157
11
    count++;
2158
11
  }
2159
2160
6
  D->addAttr(::new (S.Context) VecReturnAttr(S.Context, AL));
2161
6
}
2162
2163
static void handleDependencyAttr(Sema &S, Scope *Scope, Decl *D,
2164
27
                                 const ParsedAttr &AL) {
2165
27
  if (isa<ParmVarDecl>(D)) {
2166
    // [[carries_dependency]] can only be applied to a parameter if it is a
2167
    // parameter of a function declaration or lambda.
2168
14
    if (!(Scope->getFlags() & clang::Scope::FunctionDeclarationScope)) {
2169
6
      S.Diag(AL.getLoc(),
2170
6
             diag::err_carries_dependency_param_not_function_decl);
2171
6
      return;
2172
6
    }
2173
14
  }
2174
2175
21
  D->addAttr(::new (S.Context) CarriesDependencyAttr(S.Context, AL));
2176
21
}
2177
2178
109k
static void handleUnusedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2179
109k
  bool IsCXX17Attr = AL.isCXX11Attribute() && 
!AL.getScopeName()29
;
2180
2181
  // If this is spelled as the standard C++17 attribute, but not in C++17, warn
2182
  // about using it as an extension.
2183
109k
  if (!S.getLangOpts().CPlusPlus17 && 
IsCXX17Attr108k
)
2184
8
    S.Diag(AL.getLoc(), diag::ext_cxx17_attr) << AL;
2185
2186
109k
  D->addAttr(::new (S.Context) UnusedAttr(S.Context, AL));
2187
109k
}
2188
2189
37
static void handleConstructorAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2190
37
  uint32_t priority = ConstructorAttr::DefaultPriority;
2191
37
  if (AL.getNumArgs() &&
2192
37
      
!checkUInt32Argument(S, AL, AL.getArgAsExpr(0), priority)19
)
2193
4
    return;
2194
2195
33
  D->addAttr(::new (S.Context) ConstructorAttr(S.Context, AL, priority));
2196
33
}
2197
2198
48
static void handleDestructorAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2199
48
  uint32_t priority = DestructorAttr::DefaultPriority;
2200
48
  if (AL.getNumArgs() &&
2201
48
      
!checkUInt32Argument(S, AL, AL.getArgAsExpr(0), priority)35
)
2202
1
    return;
2203
2204
47
  D->addAttr(::new (S.Context) DestructorAttr(S.Context, AL, priority));
2205
47
}
2206
2207
template <typename AttrTy>
2208
6.62k
static void handleAttrWithMessage(Sema &S, Decl *D, const ParsedAttr &AL) {
2209
  // Handle the case where the attribute has a text message.
2210
6.62k
  StringRef Str;
2211
6.62k
  if (AL.getNumArgs() == 1 && 
!S.checkStringLiteralArgumentAttr(AL, 0, Str)1.64k
)
2212
1
    return;
2213
2214
6.62k
  D->addAttr(::new (S.Context) AttrTy(S.Context, AL, Str));
2215
6.62k
}
2216
2217
static void handleObjCSuppresProtocolAttr(Sema &S, Decl *D,
2218
107
                                          const ParsedAttr &AL) {
2219
107
  if (!cast<ObjCProtocolDecl>(D)->isThisDeclarationADefinition()) {
2220
1
    S.Diag(AL.getLoc(), diag::err_objc_attr_protocol_requires_definition)
2221
1
        << AL << AL.getRange();
2222
1
    return;
2223
1
  }
2224
2225
106
  D->addAttr(::new (S.Context) ObjCExplicitProtocolImplAttr(S.Context, AL));
2226
106
}
2227
2228
static bool checkAvailabilityAttr(Sema &S, SourceRange Range,
2229
                                  IdentifierInfo *Platform,
2230
                                  VersionTuple Introduced,
2231
                                  VersionTuple Deprecated,
2232
6.11M
                                  VersionTuple Obsoleted) {
2233
6.11M
  StringRef PlatformName
2234
6.11M
    = AvailabilityAttr::getPrettyPlatformName(Platform->getName());
2235
6.11M
  if (PlatformName.empty())
2236
494
    PlatformName = Platform->getName();
2237
2238
  // Ensure that Introduced <= Deprecated <= Obsoleted (although not all
2239
  // of these steps are needed).
2240
6.11M
  if (!Introduced.empty() && 
!Deprecated.empty()4.78M
&&
2241
6.11M
      
!(Introduced <= Deprecated)1.03M
) {
2242
7
    S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2243
7
      << 1 << PlatformName << Deprecated.getAsString()
2244
7
      << 0 << Introduced.getAsString();
2245
7
    return true;
2246
7
  }
2247
2248
6.11M
  if (!Introduced.empty() && 
!Obsoleted.empty()4.78M
&&
2249
6.11M
      
!(Introduced <= Obsoleted)51
) {
2250
0
    S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2251
0
      << 2 << PlatformName << Obsoleted.getAsString()
2252
0
      << 0 << Introduced.getAsString();
2253
0
    return true;
2254
0
  }
2255
2256
6.11M
  if (!Deprecated.empty() && 
!Obsoleted.empty()1.07M
&&
2257
6.11M
      
!(Deprecated <= Obsoleted)28
) {
2258
3
    S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2259
3
      << 2 << PlatformName << Obsoleted.getAsString()
2260
3
      << 1 << Deprecated.getAsString();
2261
3
    return true;
2262
3
  }
2263
2264
6.11M
  return false;
2265
6.11M
}
2266
2267
/// Check whether the two versions match.
2268
///
2269
/// If either version tuple is empty, then they are assumed to match. If
2270
/// \p BeforeIsOkay is true, then \p X can be less than or equal to \p Y.
2271
static bool versionsMatch(const VersionTuple &X, const VersionTuple &Y,
2272
422k
                          bool BeforeIsOkay) {
2273
422k
  if (X.empty() || 
Y.empty()144k
)
2274
286k
    return true;
2275
2276
136k
  if (X == Y)
2277
135k
    return true;
2278
2279
748
  if (BeforeIsOkay && 
X < Y127
)
2280
25
    return true;
2281
2282
723
  return false;
2283
748
}
2284
2285
AvailabilityAttr *Sema::mergeAvailabilityAttr(
2286
    NamedDecl *D, const AttributeCommonInfo &CI, IdentifierInfo *Platform,
2287
    bool Implicit, VersionTuple Introduced, VersionTuple Deprecated,
2288
    VersionTuple Obsoleted, bool IsUnavailable, StringRef Message,
2289
    bool IsStrict, StringRef Replacement, AvailabilityMergeKind AMK,
2290
6.10M
    int Priority) {
2291
6.10M
  VersionTuple MergedIntroduced = Introduced;
2292
6.10M
  VersionTuple MergedDeprecated = Deprecated;
2293
6.10M
  VersionTuple MergedObsoleted = Obsoleted;
2294
6.10M
  bool FoundAny = false;
2295
6.10M
  bool OverrideOrImpl = false;
2296
6.10M
  switch (AMK) {
2297
5.93M
  case AMK_None:
2298
5.96M
  case AMK_Redeclaration:
2299
5.96M
    OverrideOrImpl = false;
2300
5.96M
    break;
2301
2302
134k
  case AMK_Override:
2303
134k
  case AMK_ProtocolImplementation:
2304
135k
  case AMK_OptionalProtocolImplementation:
2305
135k
    OverrideOrImpl = true;
2306
135k
    break;
2307
6.10M
  }
2308
2309
6.10M
  if (D->hasAttrs()) {
2310
4.18M
    AttrVec &Attrs = D->getAttrs();
2311
12.6M
    for (unsigned i = 0, e = Attrs.size(); i != e;) {
2312
8.49M
      const auto *OldAA = dyn_cast<AvailabilityAttr>(Attrs[i]);
2313
8.49M
      if (!OldAA) {
2314
1.32M
        ++i;
2315
1.32M
        continue;
2316
1.32M
      }
2317
2318
7.17M
      IdentifierInfo *OldPlatform = OldAA->getPlatform();
2319
7.17M
      if (OldPlatform != Platform) {
2320
7.02M
        ++i;
2321
7.02M
        continue;
2322
7.02M
      }
2323
2324
      // If there is an existing availability attribute for this platform that
2325
      // has a lower priority use the existing one and discard the new
2326
      // attribute.
2327
141k
      if (OldAA->getPriority() < Priority)
2328
609
        return nullptr;
2329
2330
      // If there is an existing attribute for this platform that has a higher
2331
      // priority than the new attribute then erase the old one and continue
2332
      // processing the attributes.
2333
141k
      if (OldAA->getPriority() > Priority) {
2334
16
        Attrs.erase(Attrs.begin() + i);
2335
16
        --e;
2336
16
        continue;
2337
16
      }
2338
2339
141k
      FoundAny = true;
2340
141k
      VersionTuple OldIntroduced = OldAA->getIntroduced();
2341
141k
      VersionTuple OldDeprecated = OldAA->getDeprecated();
2342
141k
      VersionTuple OldObsoleted = OldAA->getObsoleted();
2343
141k
      bool OldIsUnavailable = OldAA->getUnavailable();
2344
2345
141k
      if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl) ||
2346
141k
          
!versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl)140k
||
2347
141k
          
!versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl)140k
||
2348
141k
          
!(140k
OldIsUnavailable == IsUnavailable140k
||
2349
140k
            
(11
OverrideOrImpl11
&&
!OldIsUnavailable11
&&
IsUnavailable5
))) {
2350
678
        if (OverrideOrImpl) {
2351
57
          int Which = -1;
2352
57
          VersionTuple FirstVersion;
2353
57
          VersionTuple SecondVersion;
2354
57
          if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl)) {
2355
43
            Which = 0;
2356
43
            FirstVersion = OldIntroduced;
2357
43
            SecondVersion = Introduced;
2358
43
          } else 
if (14
!versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl)14
) {
2359
6
            Which = 1;
2360
6
            FirstVersion = Deprecated;
2361
6
            SecondVersion = OldDeprecated;
2362
8
          } else if (!versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl)) {
2363
2
            Which = 2;
2364
2
            FirstVersion = Obsoleted;
2365
2
            SecondVersion = OldObsoleted;
2366
2
          }
2367
2368
57
          if (Which == -1) {
2369
6
            Diag(OldAA->getLocation(),
2370
6
                 diag::warn_mismatched_availability_override_unavail)
2371
6
              << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
2372
6
              << (AMK == AMK_Override);
2373
51
          } else if (Which != 1 && 
AMK == AMK_OptionalProtocolImplementation45
) {
2374
            // Allow different 'introduced' / 'obsoleted' availability versions
2375
            // on a method that implements an optional protocol requirement. It
2376
            // makes less sense to allow this for 'deprecated' as the user can't
2377
            // see if the method is 'deprecated' as 'respondsToSelector' will
2378
            // still return true when the method is deprecated.
2379
8
            ++i;
2380
8
            continue;
2381
43
          } else {
2382
43
            Diag(OldAA->getLocation(),
2383
43
                 diag::warn_mismatched_availability_override)
2384
43
              << Which
2385
43
              << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
2386
43
              << FirstVersion.getAsString() << SecondVersion.getAsString()
2387
43
              << (AMK == AMK_Override);
2388
43
          }
2389
49
          if (AMK == AMK_Override)
2390
15
            Diag(CI.getLoc(), diag::note_overridden_method);
2391
34
          else
2392
34
            Diag(CI.getLoc(), diag::note_protocol_method);
2393
621
        } else {
2394
621
          Diag(OldAA->getLocation(), diag::warn_mismatched_availability);
2395
621
          Diag(CI.getLoc(), diag::note_previous_attribute);
2396
621
        }
2397
2398
670
        Attrs.erase(Attrs.begin() + i);
2399
670
        --e;
2400
670
        continue;
2401
678
      }
2402
2403
140k
      VersionTuple MergedIntroduced2 = MergedIntroduced;
2404
140k
      VersionTuple MergedDeprecated2 = MergedDeprecated;
2405
140k
      VersionTuple MergedObsoleted2 = MergedObsoleted;
2406
2407
140k
      if (MergedIntroduced2.empty())
2408
16.6k
        MergedIntroduced2 = OldIntroduced;
2409
140k
      if (MergedDeprecated2.empty())
2410
114k
        MergedDeprecated2 = OldDeprecated;
2411
140k
      if (MergedObsoleted2.empty())
2412
140k
        MergedObsoleted2 = OldObsoleted;
2413
2414
140k
      if (checkAvailabilityAttr(*this, OldAA->getRange(), Platform,
2415
140k
                                MergedIntroduced2, MergedDeprecated2,
2416
140k
                                MergedObsoleted2)) {
2417
4
        Attrs.erase(Attrs.begin() + i);
2418
4
        --e;
2419
4
        continue;
2420
4
      }
2421
2422
140k
      MergedIntroduced = MergedIntroduced2;
2423
140k
      MergedDeprecated = MergedDeprecated2;
2424
140k
      MergedObsoleted = MergedObsoleted2;
2425
140k
      ++i;
2426
140k
    }
2427
4.18M
  }
2428
2429
6.10M
  if (FoundAny &&
2430
6.10M
      
MergedIntroduced == Introduced141k
&&
2431
6.10M
      
MergedDeprecated == Deprecated137k
&&
2432
6.10M
      
MergedObsoleted == Obsoleted127k
)
2433
127k
    return nullptr;
2434
2435
  // Only create a new attribute if !OverrideOrImpl, but we want to do
2436
  // the checking.
2437
5.97M
  if (!checkAvailabilityAttr(*this, CI.getRange(), Platform, MergedIntroduced,
2438
5.97M
                             MergedDeprecated, MergedObsoleted) &&
2439
5.97M
      
!OverrideOrImpl5.97M
) {
2440
5.96M
    auto *Avail = ::new (Context) AvailabilityAttr(
2441
5.96M
        Context, CI, Platform, Introduced, Deprecated, Obsoleted, IsUnavailable,
2442
5.96M
        Message, IsStrict, Replacement, Priority);
2443
5.96M
    Avail->setImplicit(Implicit);
2444
5.96M
    return Avail;
2445
5.96M
  }
2446
10.5k
  return nullptr;
2447
5.97M
}
2448
2449
5.93M
static void handleAvailabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2450
5.93M
  if (isa<UsingDecl, UnresolvedUsingTypenameDecl, UnresolvedUsingValueDecl>(
2451
5.93M
          D)) {
2452
2
    S.Diag(AL.getRange().getBegin(), diag::warn_deprecated_ignored_on_using)
2453
2
        << AL;
2454
2
    return;
2455
2
  }
2456
2457
5.93M
  if (!AL.checkExactlyNumArgs(S, 1))
2458
0
    return;
2459
5.93M
  IdentifierLoc *Platform = AL.getArgAsIdent(0);
2460
2461
5.93M
  IdentifierInfo *II = Platform->Ident;
2462
5.93M
  if (AvailabilityAttr::getPrettyPlatformName(II->getName()).empty())
2463
494
    S.Diag(Platform->Loc, diag::warn_availability_unknown_platform)
2464
494
      << Platform->Ident;
2465
2466
5.93M
  auto *ND = dyn_cast<NamedDecl>(D);
2467
5.93M
  if (!ND) // We warned about this already, so just return.
2468
0
    return;
2469
2470
5.93M
  AvailabilityChange Introduced = AL.getAvailabilityIntroduced();
2471
5.93M
  AvailabilityChange Deprecated = AL.getAvailabilityDeprecated();
2472
5.93M
  AvailabilityChange Obsoleted = AL.getAvailabilityObsoleted();
2473
5.93M
  bool IsUnavailable = AL.getUnavailableLoc().isValid();
2474
5.93M
  bool IsStrict = AL.getStrictLoc().isValid();
2475
5.93M
  StringRef Str;
2476
5.93M
  if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getMessageExpr()))
2477
516k
    Str = SE->getString();
2478
5.93M
  StringRef Replacement;
2479
5.93M
  if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getReplacementExpr()))
2480
80.1k
    Replacement = SE->getString();
2481
2482
5.93M
  if (II->isStr("swift")) {
2483
36.0k
    if (Introduced.isValid() || 
Obsoleted.isValid()36.0k
||
2484
36.0k
        
(36.0k
!IsUnavailable36.0k
&&
!Deprecated.isValid()3
)) {
2485
2
      S.Diag(AL.getLoc(),
2486
2
             diag::warn_availability_swift_unavailable_deprecated_only);
2487
2
      return;
2488
2
    }
2489
36.0k
  }
2490
2491
5.93M
  int PriorityModifier = AL.isPragmaClangAttribute()
2492
5.93M
                             ? 
Sema::AP_PragmaClangAttribute79.8k
2493
5.93M
                             : 
Sema::AP_Explicit5.85M
;
2494
5.93M
  AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
2495
5.93M
      ND, AL, II, false /*Implicit*/, Introduced.Version, Deprecated.Version,
2496
5.93M
      Obsoleted.Version, IsUnavailable, Str, IsStrict, Replacement,
2497
5.93M
      Sema::AMK_None, PriorityModifier);
2498
5.93M
  if (NewAttr)
2499
5.93M
    D->addAttr(NewAttr);
2500
2501
  // Transcribe "ios" to "watchos" (and add a new attribute) if the versioning
2502
  // matches before the start of the watchOS platform.
2503
5.93M
  if (S.Context.getTargetInfo().getTriple().isWatchOS()) {
2504
53
    IdentifierInfo *NewII = nullptr;
2505
53
    if (II->getName() == "ios")
2506
17
      NewII = &S.Context.Idents.get("watchos");
2507
36
    else if (II->getName() == "ios_app_extension")
2508
0
      NewII = &S.Context.Idents.get("watchos_app_extension");
2509
2510
53
    if (NewII) {
2511
51
        auto adjustWatchOSVersion = [](VersionTuple Version) -> VersionTuple {
2512
51
          if (Version.empty())
2513
28
            return Version;
2514
23
          auto Major = Version.getMajor();
2515
23
          auto NewMajor = Major >= 9 ? 
Major - 75
:
018
;
2516
23
          if (NewMajor >= 2) {
2517
5
            if (Version.getMinor().hasValue()) {
2518
4
              if (Version.getSubminor().hasValue())
2519
0
                return VersionTuple(NewMajor, Version.getMinor().getValue(),
2520
0
                                    Version.getSubminor().getValue());
2521
4
              else
2522
4
                return VersionTuple(NewMajor, Version.getMinor().getValue());
2523
4
            }
2524
1
            return VersionTuple(NewMajor);
2525
5
          }
2526
2527
18
          return VersionTuple(2, 0);
2528
23
        };
2529
2530
17
        auto NewIntroduced = adjustWatchOSVersion(Introduced.Version);
2531
17
        auto NewDeprecated = adjustWatchOSVersion(Deprecated.Version);
2532
17
        auto NewObsoleted = adjustWatchOSVersion(Obsoleted.Version);
2533
2534
17
        AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
2535
17
            ND, AL, NewII, true /*Implicit*/, NewIntroduced, NewDeprecated,
2536
17
            NewObsoleted, IsUnavailable, Str, IsStrict, Replacement,
2537
17
            Sema::AMK_None,
2538
17
            PriorityModifier + Sema::AP_InferredFromOtherPlatform);
2539
17
        if (NewAttr)
2540
16
          D->addAttr(NewAttr);
2541
17
      }
2542
5.93M
  } else if (S.Context.getTargetInfo().getTriple().isTvOS()) {
2543
    // Transcribe "ios" to "tvos" (and add a new attribute) if the versioning
2544
    // matches before the start of the tvOS platform.
2545
86
    IdentifierInfo *NewII = nullptr;
2546
86
    if (II->getName() == "ios")
2547
20
      NewII = &S.Context.Idents.get("tvos");
2548
66
    else if (II->getName() == "ios_app_extension")
2549
3
      NewII = &S.Context.Idents.get("tvos_app_extension");
2550
2551
86
    if (NewII) {
2552
23
      AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
2553
23
          ND, AL, NewII, true /*Implicit*/, Introduced.Version,
2554
23
          Deprecated.Version, Obsoleted.Version, IsUnavailable, Str, IsStrict,
2555
23
          Replacement, Sema::AMK_None,
2556
23
          PriorityModifier + Sema::AP_InferredFromOtherPlatform);
2557
23
      if (NewAttr)
2558
17
        D->addAttr(NewAttr);
2559
23
      }
2560
5.93M
  } else if (S.Context.getTargetInfo().getTriple().getOS() ==
2561
5.93M
                 llvm::Triple::IOS &&
2562
5.93M
             
S.Context.getTargetInfo().getTriple().isMacCatalystEnvironment()223
) {
2563
119
    auto GetSDKInfo = [&]() {
2564
46
      return S.getDarwinSDKInfoForAvailabilityChecking(AL.getRange().getBegin(),
2565
46
                                                       "macOS");
2566
46
    };
2567
2568
    // Transcribe "ios" to "maccatalyst" (and add a new attribute).
2569
119
    IdentifierInfo *NewII = nullptr;
2570
119
    if (II->getName() == "ios")
2571
32
      NewII = &S.Context.Idents.get("maccatalyst");
2572
87
    else if (II->getName() == "ios_app_extension")
2573
10
      NewII = &S.Context.Idents.get("maccatalyst_app_extension");
2574
119
    if (NewII) {
2575
126
      auto MinMacCatalystVersion = [](const VersionTuple &V) {
2576
126
        if (V.empty())
2577
78
          return V;
2578
48
        if (V.getMajor() < 13 ||
2579
48
            
(14
V.getMajor() == 1314
&&
V.getMinor()2
&&
*V.getMinor() < 12
))
2580
34
          return VersionTuple(13, 1); // The min Mac Catalyst version is 13.1.
2581
14
        return V;
2582
48
      };
2583
42
      AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
2584
42
          ND, AL.getRange(), NewII, true /*Implicit*/,
2585
42
          MinMacCatalystVersion(Introduced.Version),
2586
42
          MinMacCatalystVersion(Deprecated.Version),
2587
42
          MinMacCatalystVersion(Obsoleted.Version), IsUnavailable, Str,
2588
42
          IsStrict, Replacement, Sema::AMK_None,
2589
42
          PriorityModifier + Sema::AP_InferredFromOtherPlatform);
2590
42
      if (NewAttr)
2591
28
        D->addAttr(NewAttr);
2592
77
    } else if (II->getName() == "macos" && 
GetSDKInfo()25
&&
2593
77
               
(23
!Introduced.Version.empty()23
||
!Deprecated.Version.empty()2
||
2594
23
                
!Obsoleted.Version.empty()2
)) {
2595
21
      if (const auto *MacOStoMacCatalystMapping =
2596
21
              GetSDKInfo()->getVersionMapping(
2597
21
                  DarwinSDKInfo::OSEnvPair::macOStoMacCatalystPair())) {
2598
        // Infer Mac Catalyst availability from the macOS availability attribute
2599
        // if it has versioned availability. Don't infer 'unavailable'. This
2600
        // inferred availability has lower priority than the other availability
2601
        // attributes that are inferred from 'ios'.
2602
21
        NewII = &S.Context.Idents.get("maccatalyst");
2603
21
        auto RemapMacOSVersion =
2604
63
            [&](const VersionTuple &V) -> Optional<VersionTuple> {
2605
63
          if (V.empty())
2606
29
            return None;
2607
          // API_TO_BE_DEPRECATED is 100000.
2608
34
          if (V.getMajor() == 100000)
2609
4
            return VersionTuple(100000);
2610
          // The minimum iosmac version is 13.1
2611
30
          return MacOStoMacCatalystMapping->map(V, VersionTuple(13, 1), None);
2612
34
        };
2613
21
        Optional<VersionTuple> NewIntroduced =
2614
21
                                   RemapMacOSVersion(Introduced.Version),
2615
21
                               NewDeprecated =
2616
21
                                   RemapMacOSVersion(Deprecated.Version),
2617
21
                               NewObsoleted =
2618
21
                                   RemapMacOSVersion(Obsoleted.Version);
2619
21
        if (NewIntroduced || 
NewDeprecated2
||
NewObsoleted2
) {
2620
19
          auto VersionOrEmptyVersion =
2621
57
              [](const Optional<VersionTuple> &V) -> VersionTuple {
2622
57
            return V ? 
*V32
:
VersionTuple()25
;
2623
57
          };
2624
19
          AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
2625
19
              ND, AL.getRange(), NewII, true /*Implicit*/,
2626
19
              VersionOrEmptyVersion(NewIntroduced),
2627
19
              VersionOrEmptyVersion(NewDeprecated),
2628
19
              VersionOrEmptyVersion(NewObsoleted), /*IsUnavailable=*/false, Str,
2629
19
              IsStrict, Replacement, Sema::AMK_None,
2630
19
              PriorityModifier + Sema::AP_InferredFromOtherPlatform +
2631
19
                  Sema::AP_InferredFromOtherPlatform);
2632
19
          if (NewAttr)
2633
19
            D->addAttr(NewAttr);
2634
19
        }
2635
21
      }
2636
21
    }
2637
119
  }
2638
5.93M
}
2639
2640
static void handleExternalSourceSymbolAttr(Sema &S, Decl *D,
2641
71
                                           const ParsedAttr &AL) {
2642
71
  if (!AL.checkAtLeastNumArgs(S, 1) || 
!AL.checkAtMostNumArgs(S, 3)68
)
2643
3
    return;
2644
2645
68
  StringRef Language;
2646
68
  if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getArgAsExpr(0)))
2647
57
    Language = SE->getString();
2648
68
  StringRef DefinedIn;
2649
68
  if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getArgAsExpr(1)))
2650
55
    DefinedIn = SE->getString();
2651
68
  bool IsGeneratedDeclaration = AL.getArgAsIdent(2) != nullptr;
2652
2653
68
  D->addAttr(::new (S.Context) ExternalSourceSymbolAttr(
2654
68
      S.Context, AL, Language, DefinedIn, IsGeneratedDeclaration));
2655
68
}
2656
2657
template <class T>
2658
static T *mergeVisibilityAttr(Sema &S, Decl *D, const AttributeCommonInfo &CI,
2659
1.76M
                              typename T::VisibilityType value) {
2660
1.76M
  T *existingAttr = D->getAttr<T>();
2661
1.76M
  if (existingAttr) {
2662
34.9k
    typename T::VisibilityType existingValue = existingAttr->getVisibility();
2663
34.9k
    if (existingValue == value)
2664
34.9k
      return nullptr;
2665
6
    S.Diag(existingAttr->getLocation(), diag::err_mismatched_visibility);
2666
6
    S.Diag(CI.getLoc(), diag::note_previous_attribute);
2667
6
    D->dropAttr<T>();
2668
6
  }
2669
1.72M
  return ::new (S.Context) T(S.Context, CI, value);
2670
1.76M
}
SemaDeclAttr.cpp:clang::VisibilityAttr* mergeVisibilityAttr<clang::VisibilityAttr>(clang::Sema&, clang::Decl*, clang::AttributeCommonInfo const&, clang::VisibilityAttr::VisibilityType)
Line
Count
Source
2659
1.59M
                              typename T::VisibilityType value) {
2660
1.59M
  T *existingAttr = D->getAttr<T>();
2661
1.59M
  if (existingAttr) {
2662
24.2k
    typename T::VisibilityType existingValue = existingAttr->getVisibility();
2663
24.2k
    if (existingValue == value)
2664
24.2k
      return nullptr;
2665
6
    S.Diag(existingAttr->getLocation(), diag::err_mismatched_visibility);
2666
6
    S.Diag(CI.getLoc(), diag::note_previous_attribute);
2667
6
    D->dropAttr<T>();
2668
6
  }
2669
1.57M
  return ::new (S.Context) T(S.Context, CI, value);
2670
1.59M
}
SemaDeclAttr.cpp:clang::TypeVisibilityAttr* mergeVisibilityAttr<clang::TypeVisibilityAttr>(clang::Sema&, clang::Decl*, clang::AttributeCommonInfo const&, clang::TypeVisibilityAttr::VisibilityType)
Line
Count
Source
2659
169k
                              typename T::VisibilityType value) {
2660
169k
  T *existingAttr = D->getAttr<T>();
2661
169k
  if (existingAttr) {
2662
10.6k
    typename T::VisibilityType existingValue = existingAttr->getVisibility();
2663
10.6k
    if (existingValue == value)
2664
10.6k
      return nullptr;
2665
0
    S.Diag(existingAttr->getLocation(), diag::err_mismatched_visibility);
2666
0
    S.Diag(CI.getLoc(), diag::note_previous_attribute);
2667
0
    D->dropAttr<T>();
2668
0
  }
2669
158k
  return ::new (S.Context) T(S.Context, CI, value);
2670
169k
}
2671
2672
VisibilityAttr *Sema::mergeVisibilityAttr(Decl *D,
2673
                                          const AttributeCommonInfo &CI,
2674
1.59M
                                          VisibilityAttr::VisibilityType Vis) {
2675
1.59M
  return ::mergeVisibilityAttr<VisibilityAttr>(*this, D, CI, Vis);
2676
1.59M
}
2677
2678
TypeVisibilityAttr *
2679
Sema::mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
2680
169k
                              TypeVisibilityAttr::VisibilityType Vis) {
2681
169k
  return ::mergeVisibilityAttr<TypeVisibilityAttr>(*this, D, CI, Vis);
2682
169k
}
2683
2684
static void handleVisibilityAttr(Sema &S, Decl *D, const ParsedAttr &AL,
2685
1.64M
                                 bool isTypeVisibility) {
2686
  // Visibility attributes don't mean anything on a typedef.
2687
1.64M
  if (isa<TypedefNameDecl>(D)) {
2688
1
    S.Diag(AL.getRange().getBegin(), diag::warn_attribute_ignored) << AL;
2689
1
    return;
2690
1
  }
2691
2692
  // 'type_visibility' can only go on a type or namespace.
2693
1.64M
  if (isTypeVisibility &&
2694
1.64M
      
!(149k
isa<TagDecl>(D)149k
||
2695
149k
        
isa<ObjCInterfaceDecl>(D)1
||
2696
149k
        
isa<NamespaceDecl>(D)1
)) {
2697
1
    S.Diag(AL.getRange().getBegin(), diag::err_attribute_wrong_decl_type)
2698
1
        << AL << ExpectedTypeOrNamespace;
2699
1
    return;
2700
1
  }
2701
2702
  // Check that the argument is a string literal.
2703
1.64M
  StringRef TypeStr;
2704
1.64M
  SourceLocation LiteralLoc;
2705
1.64M
  if (!S.checkStringLiteralArgumentAttr(AL, 0, TypeStr, &LiteralLoc))
2706
0
    return;
2707
2708
1.64M
  VisibilityAttr::VisibilityType type;
2709
1.64M
  if (!VisibilityAttr::ConvertStrToVisibilityType(TypeStr, type)) {
2710
0
    S.Diag(LiteralLoc, diag::warn_attribute_type_not_supported) << AL
2711
0
                                                                << TypeStr;
2712
0
    return;
2713
0
  }
2714
2715
  // Complain about attempts to use protected visibility on targets
2716
  // (like Darwin) that don't support it.
2717
1.64M
  if (type == VisibilityAttr::Protected &&
2718
1.64M
      
!S.Context.getTargetInfo().hasProtectedVisibility()62
) {
2719
3
    S.Diag(AL.getLoc(), diag::warn_attribute_protected_visibility);
2720
3
    type = VisibilityAttr::Default;
2721
3
  }
2722
2723
1.64M
  Attr *newAttr;
2724
1.64M
  if (isTypeVisibility) {
2725
149k
    newAttr = S.mergeTypeVisibilityAttr(
2726
149k
        D, AL, (TypeVisibilityAttr::VisibilityType)type);
2727
1.49M
  } else {
2728
1.49M
    newAttr = S.mergeVisibilityAttr(D, AL, type);
2729
1.49M
  }
2730
1.64M
  if (newAttr)
2731
1.64M
    D->addAttr(newAttr);
2732
1.64M
}
2733
2734
115
static void handleObjCDirectAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2735
  // objc_direct cannot be set on methods declared in the context of a protocol
2736
115
  if (isa<ObjCProtocolDecl>(D->getDeclContext())) {
2737
2
    S.Diag(AL.getLoc(), diag::err_objc_direct_on_protocol) << false;
2738
2
    return;
2739
2
  }
2740
2741
113
  if (S.getLangOpts().ObjCRuntime.allowsDirectDispatch()) {
2742
113
    handleSimpleAttribute<ObjCDirectAttr>(S, D, AL);
2743
113
  } else {
2744
0
    S.Diag(AL.getLoc(), diag::warn_objc_direct_ignored) << AL;
2745
0
  }
2746
113
}
2747
2748
static void handleObjCDirectMembersAttr(Sema &S, Decl *D,
2749
11
                                        const ParsedAttr &AL) {
2750
11
  if (S.getLangOpts().ObjCRuntime.allowsDirectDispatch()) {
2751
11
    handleSimpleAttribute<ObjCDirectMembersAttr>(S, D, AL);
2752
11
  } else {
2753
0
    S.Diag(AL.getLoc(), diag::warn_objc_direct_ignored) << AL;
2754
0
  }
2755
11
}
2756
2757
18
static void handleObjCMethodFamilyAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2758
18
  const auto *M = cast<ObjCMethodDecl>(D);
2759
18
  if (!AL.isArgIdent(0)) {
2760
2
    S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
2761
2
        << AL << 1 << AANT_ArgumentIdentifier;
2762
2
    return;
2763
2
  }
2764
2765
16
  IdentifierLoc *IL = AL.getArgAsIdent(0);
2766
16
  ObjCMethodFamilyAttr::FamilyKind F;
2767
16
  if (!ObjCMethodFamilyAttr::ConvertStrToFamilyKind(IL->Ident->getName(), F)) {
2768
0
    S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << AL << IL->Ident;
2769
0
    return;
2770
0
  }
2771
2772
16
  if (F == ObjCMethodFamilyAttr::OMF_init &&
2773
16
      
!M->getReturnType()->isObjCObjectPointerType()14
) {
2774
0
    S.Diag(M->getLocation(), diag::err_init_method_bad_return_type)
2775
0
        << M->getReturnType();
2776
    // Ignore the attribute.
2777
0
    return;
2778
0
  }
2779
2780
16
  D->addAttr(new (S.Context) ObjCMethodFamilyAttr(S.Context, AL, F));
2781
16
}
2782
2783
15
static void handleObjCNSObject(Sema &S, Decl *D, const ParsedAttr &AL) {
2784
15
  if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2785
9
    QualType T = TD->getUnderlyingType();
2786
9
    if (!T->isCARCBridgableType()) {
2787
1
      S.Diag(TD->getLocation(), diag::err_nsobject_attribute);
2788
1
      return;
2789
1
    }
2790
9
  }
2791
6
  else if (const auto *PD = dyn_cast<ObjCPropertyDecl>(D)) {
2792
4
    QualType T = PD->getType();
2793
4
    if (!T->isCARCBridgableType()) {
2794
1
      S.Diag(PD->getLocation(), diag::err_nsobject_attribute);
2795
1
      return;
2796
1
    }
2797
4
  }
2798
2
  else {
2799
    // It is okay to include this attribute on properties, e.g.:
2800
    //
2801
    //  @property (retain, nonatomic) struct Bork *Q __attribute__((NSObject));
2802
    //
2803
    // In this case it follows tradition and suppresses an error in the above
2804
    // case.
2805
2
    S.Diag(D->getLocation(), diag::warn_nsobject_attribute);
2806
2
  }
2807
13
  D->addAttr(::new (S.Context) ObjCNSObjectAttr(S.Context, AL));
2808
13
}
2809
2810
4.35k
static void handleObjCIndependentClass(Sema &S, Decl *D, const ParsedAttr &AL) {
2811
4.35k
  if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2812
4.35k
    QualType T = TD->getUnderlyingType();
2813
4.35k
    if (!T->isObjCObjectPointerType()) {
2814
1
      S.Diag(TD->getLocation(), diag::warn_ptr_independentclass_attribute);
2815
1
      return;
2816
1
    }
2817
4.35k
  } else {
2818
4
    S.Diag(D->getLocation(), diag::warn_independentclass_attribute);
2819
4
    return;
2820
4
  }
2821
4.35k
  D->addAttr(::new (S.Context) ObjCIndependentClassAttr(S.Context, AL));
2822
4.35k
}
2823
2824
502
static void handleBlocksAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2825
502
  if (!AL.isArgIdent(0)) {
2826
0
    S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
2827
0
        << AL << 1 << AANT_ArgumentIdentifier;
2828
0
    return;
2829
0
  }
2830
2831
502
  IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
2832
502
  BlocksAttr::BlockType type;
2833
502
  if (!BlocksAttr::ConvertStrToBlockType(II->getName(), type)) {
2834
0
    S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << II;
2835
0
    return;
2836
0
  }
2837
2838
502
  D->addAttr(::new (S.Context) BlocksAttr(S.Context, AL, type));
2839
502
}
2840
2841
1.96k
static void handleSentinelAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2842
1.96k
  unsigned sentinel = (unsigned)SentinelAttr::DefaultSentinel;
2843
1.96k
  if (AL.getNumArgs() > 0) {
2844
1.92k
    Expr *E = AL.getArgAsExpr(0);
2845
1.92k
    Optional<llvm::APSInt> Idx = llvm::APSInt(32);
2846
1.92k
    if (E->isTypeDependent() || E->isValueDependent() ||
2847
1.92k
        !(Idx = E->getIntegerConstantExpr(S.Context))) {
2848
4
      S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
2849
4
          << AL << 1 << AANT_ArgumentIntegerConstant << E->getSourceRange();
2850
4
      return;
2851
4
    }
2852
2853
1.92k
    if (Idx->isSigned() && Idx->isNegative()) {
2854
4
      S.Diag(AL.getLoc(), diag::err_attribute_sentinel_less_than_zero)
2855
4
        << E->getSourceRange();
2856
4
      return;
2857
4
    }
2858
2859
1.91k
    sentinel = Idx->getZExtValue();
2860
1.91k
  }
2861
2862
1.95k
  unsigned nullPos = (unsigned)SentinelAttr::DefaultNullPos;
2863
1.95k
  if (AL.getNumArgs() > 1) {
2864
1.87k
    Expr *E = AL.getArgAsExpr(1);
2865
1.87k
    Optional<llvm::APSInt> Idx = llvm::APSInt(32);
2866
1.87k
    if (E->isTypeDependent() || E->isValueDependent() ||
2867
1.87k
        !(Idx = E->getIntegerConstantExpr(S.Context))) {
2868
0
      S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
2869
0
          << AL << 2 << AANT_ArgumentIntegerConstant << E->getSourceRange();
2870
0
      return;
2871
0
    }
2872
1.87k
    nullPos = Idx->getZExtValue();
2873
2874
1.87k
    if ((Idx->isSigned() && Idx->isNegative()) || nullPos > 1) {
2875
      // FIXME: This error message could be improved, it would be nice
2876
      // to say what the bounds actually are.
2877
3
      S.Diag(AL.getLoc(), diag::err_attribute_sentinel_not_zero_or_one)
2878
3
        << E->getSourceRange();
2879
3
      return;
2880
3
    }
2881
1.87k
  }
2882
2883
1.95k
  if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
2884
61
    const FunctionType *FT = FD->getType()->castAs<FunctionType>();
2885
61
    if (isa<FunctionNoProtoType>(FT)) {
2886
2
      S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_named_arguments);
2887
2
      return;
2888
2
    }
2889
2890
59
    if (!cast<FunctionProtoType>(FT)->isVariadic()) {
2891
4
      S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
2892
4
      return;
2893
4
    }
2894
1.89k
  } else if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
2895
1.87k
    if (!MD->isVariadic()) {
2896
1
      S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
2897
1
      return;
2898
1
    }
2899
1.87k
  } else 
if (const auto *16
BD16
= dyn_cast<BlockDecl>(D)) {
2900
4
    if (!BD->isVariadic()) {
2901
1
      S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 1;
2902
1
      return;
2903
1
    }
2904
12
  } else if (const auto *V = dyn_cast<VarDecl>(D)) {
2905
12
    QualType Ty = V->getType();
2906
12
    if (Ty->isBlockPointerType() || 
Ty->isFunctionPointerType()7
) {
2907
9
      const FunctionType *FT = Ty->isFunctionPointerType()
2908
9
                                   ? 
D->getFunctionType()4
2909
9
                                   : Ty->castAs<BlockPointerType>()
2910
5
                                         ->getPointeeType()
2911
5
                                         ->castAs<FunctionType>();
2912
9
      if (!cast<FunctionProtoType>(FT)->isVariadic()) {
2913
1
        int m = Ty->isFunctionPointerType() ? 
00
: 1;
2914
1
        S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << m;
2915
1
        return;
2916
1
      }
2917
9
    } else {
2918
3
      S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
2919
3
          << AL << ExpectedFunctionMethodOrBlock;
2920
3
      return;
2921
3
    }
2922
12
  } else {
2923
0
    S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
2924
0
        << AL << ExpectedFunctionMethodOrBlock;
2925
0
    return;
2926
0
  }
2927
1.94k
  D->addAttr(::new (S.Context) SentinelAttr(S.Context, AL, sentinel, nullPos));
2928
1.94k
}
2929
2930
37.7k
static void handleWarnUnusedResult(Sema &S, Decl *D, const ParsedAttr &AL) {
2931
37.7k
  if (D->getFunctionType() &&
2932
37.7k
      
D->getFunctionType()->getReturnType()->isVoidType()37.6k
&&
2933
37.7k
      
!isa<CXXConstructorDecl>(D)10
) {
2934
1
    S.Diag(AL.getLoc(), diag::warn_attribute_void_function_method) << AL << 0;
2935
1
    return;
2936
1
  }
2937
37.7k
  if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
2938
79
    if (MD->getReturnType()->isVoidType()) {
2939
1
      S.Diag(AL.getLoc(), diag::warn_attribute_void_function_method) << AL << 1;
2940
1
      return;
2941
1
    }
2942
2943
37.7k
  StringRef Str;
2944
37.7k
  if (AL.isStandardAttributeSyntax() && 
!AL.getScopeName()583
) {
2945
    // The standard attribute cannot be applied to variable declarations such
2946
    // as a function pointer.
2947
557
    if (isa<VarDecl>(D))
2948
5
      S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type_str)
2949
5
          << AL << "functions, classes, or enumerations";
2950
2951
    // If this is spelled as the standard C++17 attribute, but not in C++17,
2952
    // warn about using it as an extension. If there are attribute arguments,
2953
    // then claim it's a C++2a extension instead.
2954
    // FIXME: If WG14 does not seem likely to adopt the same feature, add an
2955
    // extension warning for C2x mode.
2956
557
    const LangOptions &LO = S.getLangOpts();
2957
557
    if (AL.getNumArgs() == 1) {
2958
29
      if (LO.CPlusPlus && 
!LO.CPlusPlus2028
)
2959
18
        S.Diag(AL.getLoc(), diag::ext_cxx20_attr) << AL;
2960
2961
      // Since this this is spelled [[nodiscard]], get the optional string
2962
      // literal. If in C++ mode, but not in C++2a mode, diagnose as an
2963
      // extension.
2964
      // FIXME: C2x should support this feature as well, even as an extension.
2965
29
      if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, nullptr))
2966
0
        return;
2967
528
    } else if (LO.CPlusPlus && 
!LO.CPlusPlus17517
)
2968
472
      S.Diag(AL.getLoc(), diag::ext_cxx17_attr) << AL;
2969
557
  }
2970
2971
37.7k
  D->addAttr(::new (S.Context) WarnUnusedResultAttr(S.Context, AL, Str));
2972
37.7k
}
2973
2974
915
static void handleWeakImportAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2975
  // weak_import only applies to variable & function declarations.
2976
915
  bool isDef = false;
2977
915
  if (!D->canBeWeakImported(isDef)) {
2978
9
    if (isDef)
2979
3
      S.Diag(AL.getLoc(), diag::warn_attribute_invalid_on_definition)
2980
3
        << "weak_import";
2981
6
    else if (isa<ObjCPropertyDecl>(D) || 
isa<ObjCMethodDecl>(D)5
||
2982
6
             
(3
S.Context.getTargetInfo().getTriple().isOSDarwin()3
&&
2983
5
              
(3
isa<ObjCInterfaceDecl>(D)3
||
isa<EnumDecl>(D)3
))) {
2984
      // Nothing to warn about here.
2985
5
    } else
2986
1
      S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
2987
1
          << AL << ExpectedVariableOrFunction;
2988
2989
9
    return;
2990
9
  }
2991
2992
906
  D->addAttr(::new (S.Context) WeakImportAttr(S.Context, AL));
2993
906
}
2994
2995
// Handles reqd_work_group_size and work_group_size_hint.
2996
template <typename WorkGroupAttr>
2997
20
static void handleWorkGroupSize(Sema &S, Decl *D, const ParsedAttr &AL) {
2998
20
  uint32_t WGSize[3];
2999
71
  for (unsigned i = 0; i < 3; 
++i51
) {
3000
56
    const Expr *E = AL.getArgAsExpr(i);
3001
56
    if (!checkUInt32Argument(S, AL, E, WGSize[i], i,
3002
56
                             /*StrictlyUnsigned=*/true))
3003
2
      return;
3004
54
    if (WGSize[i] == 0) {
3005
3
      S.Diag(AL.getLoc(), diag::err_attribute_argument_is_zero)
3006
3
          << AL << E->getSourceRange();
3007
3
      return;
3008
3
    }
3009
54
  }
3010
3011
15
  WorkGroupAttr *Existing = D->getAttr<WorkGroupAttr>();
3012
15
  if (Existing && 
!(1
Existing->getXDim() == WGSize[0]1
&&
3013
1
                    
Existing->getYDim() == WGSize[1]0
&&
3014
1
                    
Existing->getZDim() == WGSize[2]0
))
3015
1
    S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
3016
3017
15
  D->addAttr(::new (S.Context)
3018
15
                 WorkGroupAttr(S.Context, AL, WGSize[0], WGSize[1], WGSize[2]));
3019
15
}
SemaDeclAttr.cpp:void handleWorkGroupSize<clang::WorkGroupSizeHintAttr>(clang::Sema&, clang::Decl*, clang::ParsedAttr const&)
Line
Count
Source
2997
6
static void handleWorkGroupSize(Sema &S, Decl *D, const ParsedAttr &AL) {
2998
6
  uint32_t WGSize[3];
2999
22
  for (unsigned i = 0; i < 3; 
++i16
) {
3000
17
    const Expr *E = AL.getArgAsExpr(i);
3001
17
    if (!checkUInt32Argument(S, AL, E, WGSize[i], i,
3002
17
                             /*StrictlyUnsigned=*/true))
3003
1
      return;
3004
16
    if (WGSize[i] == 0) {
3005
0
      S.Diag(AL.getLoc(), diag::err_attribute_argument_is_zero)
3006
0
          << AL << E->getSourceRange();
3007
0
      return;
3008
0
    }
3009
16
  }
3010
3011
5
  WorkGroupAttr *Existing = D->getAttr<WorkGroupAttr>();
3012
5
  if (Existing && 
!(1
Existing->getXDim() == WGSize[0]1
&&
3013
1
                    
Existing->getYDim() == WGSize[1]0
&&
3014
1
                    
Existing->getZDim() == WGSize[2]0
))
3015
1
    S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
3016
3017
5
  D->addAttr(::new (S.Context)
3018
5
                 WorkGroupAttr(S.Context, AL, WGSize[0], WGSize[1], WGSize[2]));
3019
5
}
SemaDeclAttr.cpp:void handleWorkGroupSize<clang::ReqdWorkGroupSizeAttr>(clang::Sema&, clang::Decl*, clang::ParsedAttr const&)
Line
Count
Source
2997
14
static void handleWorkGroupSize(Sema &S, Decl *D, const ParsedAttr &AL) {
2998
14
  uint32_t WGSize[3];
2999
49
  for (unsigned i = 0; i < 3; 
++i35
) {
3000
39
    const Expr *E = AL.getArgAsExpr(i);
3001
39
    if (!checkUInt32Argument(S, AL, E, WGSize[i], i,
3002
39
                             /*StrictlyUnsigned=*/true))
3003
1
      return;
3004
38
    if (WGSize[i] == 0) {
3005
3
      S.Diag(AL.getLoc(), diag::err_attribute_argument_is_zero)
3006
3
          << AL << E->getSourceRange();
3007
3
      return;
3008
3
    }
3009
38
  }
3010
3011
10
  WorkGroupAttr *Existing = D->getAttr<WorkGroupAttr>();
3012
10
  if (Existing && 
!(0
Existing->getXDim() == WGSize[0]0
&&
3013
0
                    Existing->getYDim() == WGSize[1] &&
3014
0
                    Existing->getZDim() == WGSize[2]))
3015
0
    S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
3016
3017
10
  D->addAttr(::new (S.Context)
3018
10
                 WorkGroupAttr(S.Context, AL, WGSize[0], WGSize[1], WGSize[2]));
3019
10
}
3020
3021
// Handles intel_reqd_sub_group_size.
3022
6
static void handleSubGroupSize(Sema &S, Decl *D, const ParsedAttr &AL) {
3023
6
  uint32_t SGSize;
3024
6
  const Expr *E = AL.getArgAsExpr(0);
3025
6
  if (!checkUInt32Argument(S, AL, E, SGSize))
3026
0
    return;
3027
6
  if (SGSize == 0) {
3028
1
    S.Diag(AL.getLoc(), diag::err_attribute_argument_is_zero)
3029
1
        << AL << E->getSourceRange();
3030
1
    return;
3031
1
  }
3032
3033
5
  OpenCLIntelReqdSubGroupSizeAttr *Existing =
3034
5
      D->getAttr<OpenCLIntelReqdSubGroupSizeAttr>();
3035
5
  if (Existing && 
Existing->getSubGroupSize() != SGSize1
)
3036
1
    S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
3037
3038
5
  D->addAttr(::new (S.Context)
3039
5
                 OpenCLIntelReqdSubGroupSizeAttr(S.Context, AL, SGSize));
3040
5
}
3041
3042
8
static void handleVecTypeHint(Sema &S, Decl *D, const ParsedAttr &AL) {
3043
8
  if (!AL.hasParsedType()) {
3044
0
    S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
3045
0
    return;
3046
0
  }
3047
3048
8
  TypeSourceInfo *ParmTSI = nullptr;
3049
8
  QualType ParmType = S.GetTypeFromParser(AL.getTypeArg(), &ParmTSI);
3050
8
  assert(ParmTSI && "no type source info for attribute argument");
3051
3052
8
  if (!ParmType->isExtVectorType() && 
!ParmType->isFloatingType()7
&&
3053
8
      
(6
ParmType->isBooleanType()6
||
3054
6
       
!ParmType->isIntegralType(S.getASTContext())5
)) {
3055
2
    S.Diag(AL.getLoc(), diag::err_attribute_invalid_argument) << 2 << AL;
3056
2
    return;
3057
2
  }
3058
3059
6
  if (VecTypeHintAttr *A = D->getAttr<VecTypeHintAttr>()) {
3060
1
    if (!S.Context.hasSameType(A->getTypeHint(), ParmType)) {
3061
1
      S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
3062
1
      return;
3063
1
    }
3064
1
  }
3065
3066
5
  D->addAttr(::new (S.Context) VecTypeHintAttr(S.Context, AL, ParmTSI));
3067
5
}
3068
3069
SectionAttr *Sema::mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI,
3070
1.28k
                                    StringRef Name) {
3071
  // Explicit or partial specializations do not inherit
3072
  // the section attribute from the primary template.
3073
1.28k
  if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
3074
70
    if (CI.getAttributeSpellingListIndex() == SectionAttr::Declspec_allocate &&
3075
70
        
FD->isFunctionTemplateSpecialization()3
)
3076
3
      return nullptr;
3077
70
  }
3078
1.28k
  if (SectionAttr *ExistingAttr = D->getAttr<SectionAttr>()) {
3079
7
    if (ExistingAttr->getName() == Name)
3080
0
      return nullptr;
3081
7
    Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section)
3082
7
         << 1 /*section*/;
3083
7
    Diag(CI.getLoc(), diag::note_previous_attribute);
3084
7
    return nullptr;
3085
7
  }
3086
1.27k
  return ::new (Context) SectionAttr(Context, CI, Name);
3087
1.28k
}
3088
3089
/// Used to implement to perform semantic checking on
3090
/// attribute((section("foo"))) specifiers.
3091
///
3092
/// In this case, "foo" is passed in to be checked.  If the section
3093
/// specifier is invalid, return an Error that indicates the problem.
3094
///
3095
/// This is a simple quality of implementation feature to catch errors
3096
/// and give good diagnostics in cases when the assembler or code generator
3097
/// would otherwise reject the section specifier.
3098
1.43k
llvm::Error Sema::isValidSectionSpecifier(StringRef SecName) {
3099
1.43k
  if (!Context.getTargetInfo().getTriple().isOSDarwin())
3100
252
    return llvm::Error::success();
3101
3102
  // Let MCSectionMachO validate this.
3103
1.18k
  StringRef Segment, Section;
3104
1.18k
  unsigned TAA, StubSize;
3105
1.18k
  bool HasTAA;
3106
1.18k
  return llvm::MCSectionMachO::ParseSectionSpecifier(SecName, Segment, Section,
3107
1.18k
                                                     TAA, HasTAA, StubSize);
3108
1.43k
}
3109
3110
1.30k
bool Sema::checkSectionName(SourceLocation LiteralLoc, StringRef SecName) {
3111
1.30k
  if (llvm::Error E = isValidSectionSpecifier(SecName)) {
3112
2
    Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target)
3113
2
        << toString(std::move(E)) << 1 /*'section'*/;
3114
2
    return false;
3115
2
  }
3116
1.30k
  return true;
3117
1.30k
}
3118
3119
1.26k
static void handleSectionAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3120
  // Make sure that there is a string literal as the sections's single
3121
  // argument.
3122
1.26k
  StringRef Str;
3123
1.26k
  SourceLocation LiteralLoc;
3124
1.26k
  if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc))
3125
2
    return;
3126
3127
1.26k
  if (!S.checkSectionName(LiteralLoc, Str))
3128
1
    return;
3129
3130
1.25k
  SectionAttr *NewAttr = S.mergeSectionAttr(D, AL, Str);
3131
1.25k
  if (NewAttr) {
3132
1.25k
    D->addAttr(NewAttr);
3133
1.25k
    if (isa<FunctionDecl, FunctionTemplateDecl, ObjCMethodDecl,
3134
1.25k
            ObjCPropertyDecl>(D))
3135
52
      S.UnifySection(NewAttr->getName(),
3136
52
                     ASTContext::PSF_Execute | ASTContext::PSF_Read,
3137
52
                     cast<NamedDecl>(D));
3138
1.25k
  }
3139
1.25k
}
3140
3141
// This is used for `__declspec(code_seg("segname"))` on a decl.
3142
// `#pragma code_seg("segname")` uses checkSectionName() instead.
3143
static bool checkCodeSegName(Sema &S, SourceLocation LiteralLoc,
3144
83
                             StringRef CodeSegName) {
3145
83
  if (llvm::Error E = S.isValidSectionSpecifier(CodeSegName)) {
3146
0
    S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target)
3147
0
        << toString(std::move(E)) << 0 /*'code-seg'*/;
3148
0
    return false;
3149
0
  }
3150
3151
83
  return true;
3152
83
}
3153
3154
CodeSegAttr *Sema::mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI,
3155
94
                                    StringRef Name) {
3156
  // Explicit or partial specializations do not inherit
3157
  // the code_seg attribute from the primary template.
3158
94
  if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
3159
46
    if (FD->isFunctionTemplateSpecialization())
3160
3
      return nullptr;
3161
46
  }
3162
91
  if (const auto *ExistingAttr = D->getAttr<CodeSegAttr>()) {
3163
14
    if (ExistingAttr->getName() == Name)
3164
12
      return nullptr;
3165
2
    Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section)
3166
2
         << 0 /*codeseg*/;
3167
2
    Diag(CI.getLoc(), diag::note_previous_attribute);
3168
2
    return nullptr;
3169
14
  }
3170
77
  return ::new (Context) CodeSegAttr(Context, CI, Name);
3171
91
}
3172
3173
83
static void handleCodeSegAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3174
83
  StringRef Str;
3175
83
  SourceLocation LiteralLoc;
3176
83
  if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc))
3177
0
    return;
3178
83
  if (!checkCodeSegName(S, LiteralLoc, Str))
3179
0
    return;
3180
83
  if (const auto *ExistingAttr = D->getAttr<CodeSegAttr>()) {
3181
14
    if (!ExistingAttr->isImplicit()) {
3182
6
      S.Diag(AL.getLoc(),
3183
6
             ExistingAttr->getName() == Str
3184
6
             ? 
diag::warn_duplicate_codeseg_attribute3
3185
6
             : 
diag::err_conflicting_codeseg_attribute3
);
3186
6
      return;
3187
6
    }
3188
8
    D->dropAttr<CodeSegAttr>();
3189
8
  }
3190
77
  if (CodeSegAttr *CSA = S.mergeCodeSegAttr(D, AL, Str))
3191
77
    D->addAttr(CSA);
3192
77
}
3193
3194
// Check for things we'd like to warn about. Multiversioning issues are
3195
// handled later in the process, once we know how many exist.
3196
1.08M
bool Sema::checkTargetAttr(SourceLocation LiteralLoc, StringRef AttrStr) {
3197
1.08M
  enum FirstParam { Unsupported, Duplicate, Unknown };
3198
1.08M
  enum SecondParam { None, Architecture, Tune };
3199
1.08M
  if (AttrStr.find("fpmath=") != StringRef::npos)
3200
2
    return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3201
2
           << Unsupported << None << "fpmath=";
3202
3203
  // Diagnose use of tune if target doesn't support it.
3204
1.08M
  if (!Context.getTargetInfo().supportsTargetAttributeTune() &&
3205
1.08M
      
AttrStr.find("tune=") != StringRef::npos661
)
3206
1
    return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3207
1
           << Unsupported << None << "tune=";
3208
3209
1.08M
  ParsedTargetAttr ParsedAttrs = TargetAttr::parse(AttrStr);
3210
3211
1.08M
  if (!ParsedAttrs.Architecture.empty() &&
3212
1.08M
      
!Context.getTargetInfo().isValidCPUName(ParsedAttrs.Architecture)160
)
3213
3
    return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3214
3
           << Unknown << Architecture << ParsedAttrs.Architecture;
3215
3216
1.08M
  if (!ParsedAttrs.Tune.empty() &&
3217
1.08M
      
!Context.getTargetInfo().isValidCPUName(ParsedAttrs.Tune)3
)
3218
1
    return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3219
1
           << Unknown << Tune << ParsedAttrs.Tune;
3220
3221
1.08M
  if (ParsedAttrs.DuplicateArchitecture)
3222
1
    return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3223
1
           << Duplicate << None << "arch=";
3224
1.08M
  if (ParsedAttrs.DuplicateTune)
3225
0
    return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3226
0
           << Duplicate << None << "tune=";
3227
3228
1.27M
  
for (const auto &Feature : ParsedAttrs.Features)1.08M
{
3229
1.27M
    auto CurFeature = StringRef(Feature).drop_front(); // remove + or -.
3230
1.27M
    if (!Context.getTargetInfo().isValidFeatureName(CurFeature))
3231
4
      return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3232
4
             << Unsupported << None << CurFeature;
3233
1.27M
  }
3234
3235
1.08M
  TargetInfo::BranchProtectionInfo BPI;
3236
1.08M
  StringRef Error;
3237
1.08M
  if (!ParsedAttrs.BranchProtection.empty() &&
3238
1.08M
      !Context.getTargetInfo().validateBranchProtection(
3239
19
          ParsedAttrs.BranchProtection, BPI, Error)) {
3240
8
    if (Error.empty())
3241
1
      return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3242
1
             << Unsupported << None << "branch-protection";
3243
7
    else
3244
7
      return Diag(LiteralLoc, diag::err_invalid_branch_protection_spec)
3245
7
             << Error;
3246
8
  }
3247
3248
1.08M
  return false;
3249
1.08M
}
3250
3251
1.08M
static void handleTargetAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3252
1.08M
  StringRef Str;
3253
1.08M
  SourceLocation LiteralLoc;
3254
1.08M
  if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc) ||
3255
1.08M
      S.checkTargetAttr(LiteralLoc, Str))
3256
20
    return;
3257
3258
1.08M
  TargetAttr *NewAttr = ::new (S.Context) TargetAttr(S.Context, AL, Str);
3259
1.08M
  D->addAttr(NewAttr);
3260
1.08M
}
3261
3262
1.03M
static void handleMinVectorWidthAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3263
1.03M
  Expr *E = AL.getArgAsExpr(0);
3264
1.03M
  uint32_t VecWidth;
3265
1.03M
  if (!checkUInt32Argument(S, AL, E, VecWidth)) {
3266
1
    AL.setInvalid();
3267
1
    return;
3268
1
  }
3269
3270
1.03M
  MinVectorWidthAttr *Existing = D->getAttr<MinVectorWidthAttr>();
3271
1.03M
  if (Existing && 
Existing->getVectorWidth() != VecWidth1
) {
3272
1
    S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
3273
1
    return;
3274
1
  }
3275
3276
1.03M
  D->addAttr(::new (S.Context) MinVectorWidthAttr(S.Context, AL, VecWidth));
3277
1.03M
}
3278
3279
39
static void handleCleanupAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3280
39
  Expr *E = AL.getArgAsExpr(0);
3281
39
  SourceLocation Loc = E->getExprLoc();
3282
39
  FunctionDecl *FD = nullptr;
3283
39
  DeclarationNameInfo NI;
3284
3285
  // gcc only allows for simple identifiers. Since we support more than gcc, we
3286
  // will warn the user.
3287
39
  if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
3288
36
    if (DRE->hasQualifier())
3289
4
      S.Diag(Loc, diag::warn_cleanup_ext);
3290
36
    FD = dyn_cast<FunctionDecl>(DRE->getDecl());
3291
36
    NI = DRE->getNameInfo();
3292
36
    if (!FD) {
3293
1
      S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 1
3294
1
        << NI.getName();
3295
1
      return;
3296
1
    }
3297
36
  } else 
if (auto *3
ULE3
= dyn_cast<UnresolvedLookupExpr>(E)) {
3298
2
    if (ULE->hasExplicitTemplateArgs())
3299
1
      S.Diag(Loc, diag::warn_cleanup_ext);
3300
2
    FD = S.ResolveSingleFunctionTemplateSpecialization(ULE, true);
3301
2
    NI = ULE->getNameInfo();
3302
2
    if (!FD) {
3303
1
      S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 2
3304
1
        << NI.getName();
3305
1
      if (ULE->getType() == S.Context.OverloadTy)
3306
1
        S.NoteAllOverloadCandidates(ULE);
3307
1
      return;
3308
1
    }
3309
2
  } else {
3310
1
    S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 0;
3311
1
    return;
3312
1
  }
3313
3314
36
  if (FD->getNumParams() != 1) {
3315
1
    S.Diag(Loc, diag::err_attribute_cleanup_func_must_take_one_arg)
3316
1
      << NI.getName();
3317
1
    return;
3318
1
  }
3319
3320
  // We're currently more strict than GCC about what function types we accept.
3321
  // If this ever proves to be a problem it should be easy to fix.
3322
35
  QualType Ty = S.Context.getPointerType(cast<VarDecl>(D)->getType());
3323
35
  QualType ParamTy = FD->getParamDecl(0)->getType();
3324
35
  if (S.CheckAssignmentConstraints(FD->getParamDecl(0)->getLocation(),
3325
35
                                   ParamTy, Ty) != Sema::Compatible) {
3326
1
    S.Diag(Loc, diag::err_attribute_cleanup_func_arg_incompatible_type)
3327
1
      << NI.getName() << ParamTy << Ty;
3328
1
    return;
3329
1
  }
3330
3331
34
  D->addAttr(::new (S.Context) CleanupAttr(S.Context, AL, FD));
3332
34
}
3333
3334
static void handleEnumExtensibilityAttr(Sema &S, Decl *D,
3335
97.5k
                                        const ParsedAttr &AL) {
3336
97.5k
  if (!AL.isArgIdent(0)) {
3337
0
    S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
3338
0
        << AL << 0 << AANT_ArgumentIdentifier;
3339
0
    return;
3340
0
  }
3341
3342
97.5k
  EnumExtensibilityAttr::Kind ExtensibilityKind;
3343
97.5k
  IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
3344
97.5k
  if (!EnumExtensibilityAttr::ConvertStrToKind(II->getName(),
3345
97.5k
                                               ExtensibilityKind)) {
3346
1
    S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << II;
3347
1
    return;
3348
1
  }
3349
3350
97.5k
  D->addAttr(::new (S.Context)
3351
97.5k
                 EnumExtensibilityAttr(S.Context, AL, ExtensibilityKind));
3352
97.5k
}
3353
3354
/// Handle __attribute__((format_arg((idx)))) attribute based on
3355
/// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
3356
790
static void handleFormatArgAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3357
790
  Expr *IdxExpr = AL.getArgAsExpr(0);
3358
790
  ParamIdx Idx;
3359
790
  if (!checkFunctionOrMethodParameterIndex(S, D, AL, 1, IdxExpr, Idx))
3360
2
    return;
3361
3362
  // Make sure the format string is really a string.
3363
788
  QualType Ty = getFunctionOrMethodParamType(D, Idx.getASTIndex());
3364
3365
788
  bool NotNSStringTy = !isNSStringType(Ty, S.Context);
3366
788
  if (NotNSStringTy &&
3367
788
      
!isCFStringType(Ty, S.Context)559
&&
3368
788
      
(338
!Ty->isPointerType()338
||
3369
338
       
!Ty->castAs<PointerType>()->getPointeeType()->isCharType()336
)) {
3370
2
    S.Diag(AL.getLoc(), diag::err_format_attribute_not)
3371
2
        << "a string type" << IdxExpr->getSourceRange()
3372
2
        << getFunctionOrMethodParamRange(D, 0);
3373
2
    return;
3374
2
  }
3375
786
  Ty = getFunctionOrMethodResultType(D);
3376
786
  if (!isNSStringType(Ty, S.Context, /*AllowNSAttributedString=*/true) &&
3377
786
      
!isCFStringType(Ty, S.Context)558
&&
3378
786
      
(116
!Ty->isPointerType()116
||
3379
116
       
!Ty->castAs<PointerType>()->getPointeeType()->isCharType()115
)) {
3380
1
    S.Diag(AL.getLoc(), diag::err_format_attribute_result_not)
3381
1
        << (NotNSStringTy ? 
"string type"0
: "NSString")
3382
1
        << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, 0);
3383
1
    return;
3384
1
  }
3385
3386
785
  D->addAttr(::new (S.Context) FormatArgAttr(S.Context, AL, Idx));
3387
785
}
3388
3389
enum FormatAttrKind {
3390
  CFStringFormat,
3391
  NSStringFormat,
3392
  StrftimeFormat,
3393
  SupportedFormat,
3394
  IgnoredFormat,
3395
  InvalidFormat
3396
};
3397
3398
/// getFormatAttrKind - Map from format attribute names to supported format
3399
/// types.
3400
35.2k
static FormatAttrKind getFormatAttrKind(StringRef Format) {
3401
35.2k
  return llvm::StringSwitch<FormatAttrKind>(Format)
3402
      // Check for formats that get handled specially.
3403
35.2k
      .Case("NSString", NSStringFormat)
3404
35.2k
      .Case("CFString", CFStringFormat)
3405
35.2k
      .Case("strftime", StrftimeFormat)
3406
3407
      // Otherwise, check for supported formats.
3408
35.2k
      .Cases("scanf", "printf", "printf0", "strfmon", SupportedFormat)
3409
35.2k
      .Cases("cmn_err", "vcmn_err", "zcmn_err", SupportedFormat)
3410
35.2k
      .Case("kprintf", SupportedFormat)         // OpenBSD.
3411
35.2k
      .Case("freebsd_kprintf", SupportedFormat) // FreeBSD.
3412
35.2k
      .Case("os_trace", SupportedFormat)
3413
35.2k
      .Case("os_log", SupportedFormat)
3414
3415
35.2k
      .Cases("gcc_diag", "gcc_cdiag", "gcc_cxxdiag", "gcc_tdiag", IgnoredFormat)
3416
35.2k
      .Default(InvalidFormat);
3417
35.2k
}
3418
3419
/// Handle __attribute__((init_priority(priority))) attributes based on
3420
/// http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html
3421
1.14k
static void handleInitPriorityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3422
1.14k
  if (!S.getLangOpts().CPlusPlus) {
3423
0
    S.Diag(AL.getLoc(), diag::warn_attribute_ignored) << AL;
3424
0
    return;
3425
0
  }
3426
3427
1.14k
  if (S.getCurFunctionOrMethodDecl()) {
3428
2
    S.Diag(AL.getLoc(), diag::err_init_priority_object_attr);
3429
2
    AL.setInvalid();
3430
2
    return;
3431
2
  }
3432
1.14k
  QualType T = cast<VarDecl>(D)->getType();
3433
1.14k
  if (S.Context.getAsArrayType(T))
3434
6
    T = S.Context.getBaseElementType(T);
3435
1.14k
  if (!T->getAs<RecordType>()) {
3436
2
    S.Diag(AL.getLoc(), diag::err_init_priority_object_attr);
3437
2
    AL.setInvalid();
3438
2
    return;
3439
2
  }
3440
3441
1.14k
  Expr *E = AL.getArgAsExpr(0);
3442
1.14k
  uint32_t prioritynum;
3443
1.14k
  if (!checkUInt32Argument(S, AL, E, prioritynum)) {
3444
2
    AL.setInvalid();
3445
2
    return;
3446
2
  }
3447
3448
  // Only perform the priority check if the attribute is outside of a system
3449
  // header. Values <= 100 are reserved for the implementation, and libc++
3450
  // benefits from being able to specify values in that range.
3451
1.13k
  if ((prioritynum < 101 || 
prioritynum > 655351.13k
) &&
3452
1.13k
      
!S.getSourceManager().isInSystemHeader(AL.getLoc())4
) {
3453
2
    S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_range)
3454
2
        << E->getSourceRange() << AL << 101 << 65535;
3455
2
    AL.setInvalid();
3456
2
    return;
3457
2
  }
3458
1.13k
  D->addAttr(::new (S.Context) InitPriorityAttr(S.Context, AL, prioritynum));
3459
1.13k
}
3460
3461
FormatAttr *Sema::mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI,
3462
                                  IdentifierInfo *Format, int FormatIdx,
3463
36.0k
                                  int FirstArg) {
3464
  // Check whether we already have an equivalent format attribute.
3465
36.0k
  for (auto *F : D->specific_attrs<FormatAttr>()) {
3466
392
    if (F->getType() == Format &&
3467
392
        
F->getFormatIdx() == FormatIdx384
&&
3468
392
        
F->getFirstArg() == FirstArg384
) {
3469
      // If we don't have a valid location for this attribute, adopt the
3470
      // location.
3471
384
      if (F->getLocation().isInvalid())
3472
0
        F->setRange(CI.getRange());
3473
384
      return nullptr;
3474
384
    }
3475
392
  }
3476
3477
35.7k
  return ::new (Context) FormatAttr(Context, CI, Format, FormatIdx, FirstArg);
3478
36.0k
}
3479
3480
/// Handle __attribute__((format(type,idx,firstarg))) attributes based on
3481
/// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
3482
35.2k
static void handleFormatAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3483
35.2k
  if (!AL.isArgIdent(0)) {
3484
0
    S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
3485
0
        << AL << 1 << AANT_ArgumentIdentifier;
3486
0
    return;
3487
0
  }
3488
3489
  // In C++ the implicit 'this' function parameter also counts, and they are
3490
  // counted from one.
3491
35.2k
  bool HasImplicitThisParam = isInstanceMethod(D);
3492
35.2k
  unsigned NumArgs = getFunctionOrMethodNumParams(D) + HasImplicitThisParam;
3493
3494
35.2k
  IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
3495
35.2k
  StringRef Format = II->getName();
3496
3497
35.2k
  if (normalizeName(Format)) {
3498
    // If we've modified the string name, we need a new identifier for it.
3499
33.1k
    II = &S.Context.Idents.get(Format);
3500
33.1k
  }
3501
3502
  // Check for supported formats.
3503
35.2k
  FormatAttrKind Kind = getFormatAttrKind(Format);
3504
3505
35.2k
  if (Kind == IgnoredFormat)
3506
4
    return;
3507
3508
35.2k
  if (Kind == InvalidFormat) {
3509
0
    S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported)
3510
0
        << AL << II->getName();
3511
0
    return;
3512
0
  }
3513
3514
  // checks for the 2nd argument
3515
35.2k
  Expr *IdxExpr = AL.getArgAsExpr(1);
3516
35.2k
  uint32_t Idx;
3517
35.2k
  if (!checkUInt32Argument(S, AL, IdxExpr, Idx, 2))
3518
0
    return;
3519
3520
35.2k
  if (Idx < 1 || 
Idx > NumArgs35.2k
) {
3521
3
    S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
3522
3
        << AL << 2 << IdxExpr->getSourceRange();
3523
3
    return;
3524
3
  }
3525
3526
  // FIXME: Do we need to bounds check?
3527
35.2k
  unsigned ArgIdx = Idx - 1;
3528
3529
35.2k
  if (HasImplicitThisParam) {
3530
76
    if (ArgIdx == 0) {
3531
4
      S.Diag(AL.getLoc(),
3532
4
             diag::err_format_attribute_implicit_this_format_string)
3533
4
        << IdxExpr->getSourceRange();
3534
4
      return;
3535
4
    }
3536
72
    ArgIdx--;
3537
72
  }
3538
3539
  // make sure the format string is really a string
3540
35.2k
  QualType Ty = getFunctionOrMethodParamType(D, ArgIdx);
3541
3542
35.2k
  if (Kind == CFStringFormat) {
3543
892
    if (!isCFStringType(Ty, S.Context)) {
3544
1
      S.Diag(AL.getLoc(), diag::err_format_attribute_not)
3545
1
        << "a CFString" << IdxExpr->getSourceRange()
3546
1
        << getFunctionOrMethodParamRange(D, ArgIdx);
3547
1
      return;
3548
1
    }
3549
34.3k
  } else if (Kind == NSStringFormat) {
3550
    // FIXME: do we need to check if the type is NSString*?  What are the
3551
    // semantics?
3552
3.16k
    if (!isNSStringType(Ty, S.Context, /*AllowNSAttributedString=*/true)) {
3553
1
      S.Diag(AL.getLoc(), diag::err_format_attribute_not)
3554
1
        << "an NSString" << IdxExpr->getSourceRange()
3555
1
        << getFunctionOrMethodParamRange(D, ArgIdx);
3556
1
      return;
3557
1
    }
3558
31.1k
  } else if (!Ty->isPointerType() ||
3559
31.1k
             
!Ty->castAs<PointerType>()->getPointeeType()->isCharType()31.1k
) {
3560
8
    S.Diag(AL.getLoc(), diag::err_format_attribute_not)
3561
8
      << "a string type" << IdxExpr->getSourceRange()
3562
8
      << getFunctionOrMethodParamRange(D, ArgIdx);
3563
8
    return;
3564
8
  }
3565
3566
  // check the 3rd argument
3567
35.2k
  Expr *FirstArgExpr = AL.getArgAsExpr(2);
3568
35.2k
  uint32_t FirstArg;
3569
35.2k
  if (!checkUInt32Argument(S, AL, FirstArgExpr, FirstArg, 3))
3570
0
    return;
3571
3572
  // check if the function is variadic if the 3rd argument non-zero
3573
35.2k
  if (FirstArg != 0) {
3574
17.6k
    if (isFunctionOrMethodVariadic(D)) {
3575
17.6k
      ++NumArgs; // +1 for ...
3576
17.6k
    } else {
3577
3
      S.Diag(D->getLocation(), diag::err_format_attribute_requires_variadic);
3578
3
      return;
3579
3
    }
3580
17.6k
  }
3581
3582
  // strftime requires FirstArg to be 0 because it doesn't read from any
3583
  // variable the input is just the current time + the format string.
3584
35.2k
  if (Kind == StrftimeFormat) {
3585
198
    if (FirstArg != 0) {
3586
1
      S.Diag(AL.getLoc(), diag::err_format_strftime_third_parameter)
3587
1
        << FirstArgExpr->getSourceRange();
3588
1
      return;
3589
1
    }
3590
  // if 0 it disables parameter checking (to use with e.g. va_list)
3591
35.0k
  } else if (FirstArg != 0 && 
FirstArg != NumArgs17.6k
) {
3592
4
    S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
3593
4
        << AL << 3 << FirstArgExpr->getSourceRange();
3594
4
    return;
3595
4
  }
3596
3597
35.2k
  FormatAttr *NewAttr = S.mergeFormatAttr(D, AL, II, Idx, FirstArg);
3598
35.2k
  if (NewAttr)
3599
35.2k
    D->addAttr(NewAttr);
3600
35.2k
}
3601
3602
/// Handle __attribute__((callback(CalleeIdx, PayloadIdx0, ...))) attributes.
3603
142
static void handleCallbackAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3604
  // The index that identifies the callback callee is mandatory.
3605
142
  if (AL.getNumArgs() == 0) {
3606
2
    S.Diag(AL.getLoc(), diag::err_callback_attribute_no_callee)
3607
2
        << AL.getRange();
3608
2
    return;
3609
2
  }
3610
3611
140
  bool HasImplicitThisParam = isInstanceMethod(D);
3612
140
  int32_t NumArgs = getFunctionOrMethodNumParams(D);
3613
3614
140
  FunctionDecl *FD = D->getAsFunction();
3615
140
  assert(FD && "Expected a function declaration!");
3616
3617
0
  llvm::StringMap<int> NameIdxMapping;
3618
140
  NameIdxMapping["__"] = -1;
3619
3620
140
  NameIdxMapping["this"] = 0;
3621
3622
140
  int Idx = 1;
3623
140
  for (const ParmVarDecl *PVD : FD->parameters())
3624
248
    NameIdxMapping[PVD->getName()] = Idx++;
3625
3626
140
  auto UnknownName = NameIdxMapping.end();
3627
3628
140
  SmallVector<int, 8> EncodingIndices;
3629
437
  for (unsigned I = 0, E = AL.getNumArgs(); I < E; 
++I297
) {
3630
317
    SourceRange SR;
3631
317
    int32_t ArgIdx;
3632
3633
317
    if (AL.isArgIdent(I)) {
3634
127
      IdentifierLoc *IdLoc = AL.getArgAsIdent(I);
3635
127
      auto It = NameIdxMapping.find(IdLoc->Ident->getName());
3636
127
      if (It == UnknownName) {
3637
4
        S.Diag(AL.getLoc(), diag::err_callback_attribute_argument_unknown)
3638
4
            << IdLoc->Ident << IdLoc->Loc;
3639
4
        return;
3640
4
      }
3641
3642
123
      SR = SourceRange(IdLoc->Loc);
3643
123
      ArgIdx = It->second;
3644
190
    } else if (AL.isArgExpr(I)) {
3645
190
      Expr *IdxExpr = AL.getArgAsExpr(I);
3646
3647
      // If the expression is not parseable as an int32_t we have a problem.
3648
190
      if (!checkUInt32Argument(S, AL, IdxExpr, (uint32_t &)ArgIdx, I + 1,
3649
190
                               false)) {
3650
0
        S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
3651
0
            << AL << (I + 1) << IdxExpr->getSourceRange();
3652
0
        return;
3653
0
      }
3654
3655
      // Check oob, excluding the special values, 0 and -1.
3656
190
      if (ArgIdx < -1 || 
ArgIdx > NumArgs186
) {
3657
10
        S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
3658
10
            << AL << (I + 1) << IdxExpr->getSourceRange();
3659
10
        return;
3660
10
      }
3661
3662
180
      SR = IdxExpr->getSourceRange();
3663
180
    } else {
3664
0
      llvm_unreachable("Unexpected ParsedAttr argument type!");
3665
0
    }
3666
3667
303
    if (ArgIdx == 0 && 
!HasImplicitThisParam14
) {
3668
6
      S.Diag(AL.getLoc(), diag::err_callback_implicit_this_not_available)
3669
6
          << (I + 1) << SR;
3670
6
      return;
3671
6
    }
3672
3673
    // Adjust for the case we do not have an implicit "this" parameter. In this
3674
    // case we decrease all positive values by 1 to get LLVM argument indices.
3675
297
    if (!HasImplicitThisParam && 
ArgIdx > 0152
)
3676
116
      ArgIdx -= 1;
3677
3678
297
    EncodingIndices.push_back(ArgIdx);
3679
297
  }
3680
3681
120
  int CalleeIdx = EncodingIndices.front();
3682
  // Check if the callee index is proper, thus not "this" and not "unknown".
3683
  // This means the "CalleeIdx" has to be non-negative if "HasImplicitThisParam"
3684
  // is false and positive if "HasImplicitThisParam" is true.
3685
120
  if (CalleeIdx < (int)HasImplicitThisParam) {
3686
6
    S.Diag(AL.getLoc(), diag::err_callback_attribute_invalid_callee)
3687
6
        << AL.getRange();
3688
6
    return;
3689
6
  }
3690
3691
  // Get the callee type, note the index adjustment as the AST doesn't contain
3692
  // the this type (which the callee cannot reference anyway!).
3693
114
  const Type *CalleeType =
3694
114
      getFunctionOrMethodParamType(D, CalleeIdx - HasImplicitThisParam)
3695
114
          .getTypePtr();
3696
114
  if (!CalleeType || !CalleeType->isFunctionPointerType()) {
3697
0
    S.Diag(AL.getLoc(), diag::err_callback_callee_no_function_type)
3698
0
        << AL.getRange();
3699
0
    return;
3700
0
  }
3701
3702
114
  const Type *CalleeFnType =
3703
114
      CalleeType->getPointeeType()->getUnqualifiedDesugaredType();
3704
3705
  // TODO: Check the type of the callee arguments.
3706
3707
114
  const auto *CalleeFnProtoType = dyn_cast<FunctionProtoType>(CalleeFnType);
3708
114
  if (!CalleeFnProtoType) {
3709
0
    S.Diag(AL.getLoc(), diag::err_callback_callee_no_function_type)
3710
0
        << AL.getRange();
3711
0
    return;
3712
0
  }
3713
3714
114
  if (CalleeFnProtoType->getNumParams() > EncodingIndices.size() - 1) {
3715
12
    S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments)
3716
12
        << AL << (unsigned)(EncodingIndices.size() - 1);
3717
12
    return;
3718
12
  }
3719
3720
102
  if (CalleeFnProtoType->getNumParams() < EncodingIndices.size() - 1) {
3721
28
    S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments)
3722
28
        << AL << (unsigned)(EncodingIndices.size() - 1);
3723
28
    return;
3724
28
  }
3725
3726
74
  if (CalleeFnProtoType->isVariadic()) {
3727
8
    S.Diag(AL.getLoc(), diag::err_callback_callee_is_variadic) << AL.getRange();
3728
8
    return;
3729
8
  }
3730
3731
  // Do not allow multiple callback attributes.
3732
66
  if (D->hasAttr<CallbackAttr>()) {
3733
8
    S.Diag(AL.getLoc(), diag::err_callback_attribute_multiple) << AL.getRange();
3734
8
    return;
3735
8
  }
3736
3737
58
  D->addAttr(::new (S.Context) CallbackAttr(
3738
58
      S.Context, AL, EncodingIndices.data(), EncodingIndices.size()));
3739
58
}
3740
3741
103
static bool isFunctionLike(const Type &T) {
3742
  // Check for explicit function types.
3743
  // 'called_once' is only supported in Objective-C and it has
3744
  // function pointers and block pointers.
3745
103
  return T.isFunctionPointerType() || 
T.isBlockPointerType()100
;
3746
103
}
3747
3748
/// Handle 'called_once' attribute.
3749
103
static void handleCalledOnceAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3750
  // 'called_once' only applies to parameters representing functions.
3751
103
  QualType T = cast<ParmVarDecl>(D)->getType();
3752
3753
103
  if (!isFunctionLike(*T)) {
3754
2
    S.Diag(AL.getLoc(), diag::err_called_once_attribute_wrong_type);
3755
2
    return;
3756
2
  }
3757
3758
101
  D->addAttr(::new (S.Context) CalledOnceAttr(S.Context, AL));
3759
101
}
3760
3761
67
static void handleTransparentUnionAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3762
  // Try to find the underlying union declaration.
3763
67
  RecordDecl *RD = nullptr;
3764
67
  const auto *TD = dyn_cast<TypedefNameDecl>(D);
3765
67
  if (TD && 
TD->getUnderlyingType()->isUnionType()38
)
3766
38
    RD = TD->getUnderlyingType()->getAsUnionType()->getDecl();
3767
29
  else
3768
29
    RD = dyn_cast<RecordDecl>(D);
3769
3770
67
  if (!RD || !RD->isUnion()) {
3771
0
    S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type) << AL
3772
0
                                                              << ExpectedUnion;
3773
0
    return;
3774
0
  }
3775
3776
67
  if (!RD->isCompleteDefinition()) {
3777
8
    if (!RD->isBeingDefined())
3778
0
      S.Diag(AL.getLoc(),
3779
0
             diag::warn_transparent_union_attribute_not_definition);
3780
8
    return;
3781
8
  }
3782
3783
59
  RecordDecl::field_iterator Field = RD->field_begin(),
3784
59
                          FieldEnd = RD->field_end();
3785
59
  if (Field == FieldEnd) {
3786
1
    S.Diag(AL.getLoc(), diag::warn_transparent_union_attribute_zero_fields);
3787
1
    return;
3788
1
  }
3789
3790
58
  FieldDecl *FirstField = *Field;
3791
58
  QualType FirstType = FirstField->getType();
3792
58
  if (FirstType->hasFloatingRepresentation() || 
FirstType->isVectorType()57
) {
3793
2
    S.Diag(FirstField->getLocation(),
3794
2
           diag::warn_transparent_union_attribute_floating)
3795
2
      << FirstType->isVectorType() << FirstType;
3796
2
    return;
3797
2
  }
3798
3799
56
  if (FirstType->isIncompleteType())
3800
3
    return;
3801
53
  uint64_t FirstSize = S.Context.getTypeSize(FirstType);
3802
53
  uint64_t FirstAlign = S.Context.getTypeAlign(FirstType);
3803
226
  for (; Field != FieldEnd; 
++Field173
) {
3804
179
    QualType FieldType = Field->getType();
3805
179
    if (FieldType->isIncompleteType())
3806
1
      return;
3807
    // FIXME: this isn't fully correct; we also need to test whether the
3808
    // members of the union would all have the same calling convention as the
3809
    // first member of the union. Checking just the size and alignment isn't
3810
    // sufficient (consider structs passed on the stack instead of in registers
3811
    // as an example).
3812
178
    if (S.Context.getTypeSize(FieldType) != FirstSize ||
3813
178
        
S.Context.getTypeAlign(FieldType) > FirstAlign176
) {
3814
      // Warn if we drop the attribute.
3815
5
      bool isSize = S.Context.getTypeSize(FieldType) != FirstSize;
3816
5
      unsigned FieldBits = isSize ? 
S.Context.getTypeSize(FieldType)2
3817
5
                                  : 
S.Context.getTypeAlign(FieldType)3
;
3818
5
      S.Diag(Field->getLocation(),
3819
5
             diag::warn_transparent_union_attribute_field_size_align)
3820
5
          << isSize << *Field << FieldBits;
3821
5
      unsigned FirstBits = isSize ? 
FirstSize2
:
FirstAlign3
;
3822
5
      S.Diag(FirstField->getLocation(),
3823
5
             diag::note_transparent_union_first_field_size_align)
3824
5
          << isSize << FirstBits;
3825
5
      return;
3826
5
    }
3827
178
  }
3828
3829
47
  RD->addAttr(::new (S.Context) TransparentUnionAttr(S.Context, AL));
3830
47
}
3831
3832
void Sema::AddAnnotationAttr(Decl *D, const AttributeCommonInfo &CI,
3833
360
                             StringRef Str, MutableArrayRef<Expr *> Args) {
3834
360
  auto *Attr = AnnotateAttr::Create(Context, Str, Args.data(), Args.size(), CI);
3835
360
  llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
3836
426
  for (unsigned Idx = 0; Idx < Attr->args_size(); 
Idx++66
) {
3837
72
    Expr *&E = Attr->args_begin()[Idx];
3838
72
    assert(E && "error are handled before");
3839
72
    if (E->isValueDependent() || 
E->isTypeDependent()48
)
3840
24
      continue;
3841
3842
48
    if (E->getType()->isArrayType())
3843
2
      E = ImpCastExprToType(E, Context.getPointerType(E->getType()),
3844
2
                            clang::CK_ArrayToPointerDecay)
3845
2
              .get();
3846
48
    if (E->getType()->isFunctionType())
3847
2
      E = ImplicitCastExpr::Create(Context,
3848
2
                                   Context.getPointerType(E->getType()),
3849
2
                                   clang::CK_FunctionToPointerDecay, E, nullptr,
3850
2
                                   VK_PRValue, FPOptionsOverride());
3851
48
    if (E->isLValue())
3852
8
      E = ImplicitCastExpr::Create(Context, E->getType().getNonReferenceType(),
3853
8
                                   clang::CK_LValueToRValue, E, nullptr,
3854
8
                                   VK_PRValue, FPOptionsOverride());
3855
3856
48
    Expr::EvalResult Eval;
3857
48
    Notes.clear();
3858
48
    Eval.Diag = &Notes;
3859
3860
48
    bool Result =
3861
48
        E->EvaluateAsConstantExpr(Eval, Context);
3862
3863
    /// Result means the expression can be folded to a constant.
3864
    /// Note.empty() means the expression is a valid constant expression in the
3865
    /// current language mode.
3866
48
    if (!Result || 
!Notes.empty()43
) {
3867
6
      Diag(E->getBeginLoc(), diag::err_attribute_argument_n_type)
3868
6
          << CI << (Idx + 1) << AANT_ArgumentConstantExpr;
3869
6
      for (auto &Note : Notes)
3870
10
        Diag(Note.first, Note.second);
3871
6
      return;
3872
6
    }
3873
42
    assert(Eval.Val.hasValue());
3874
0
    E = ConstantExpr::Create(Context, E, Eval.Val);
3875
42
  }
3876
354
  D->addAttr(Attr);
3877
354
}
3878
3879
339
static void handleAnnotateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3880
  // Make sure that there is a string literal as the annotation's first
3881
  // argument.
3882
339
  StringRef Str;
3883
339
  if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
3884
2
    return;
3885
3886
337
  llvm::SmallVector<Expr *, 4> Args;
3887
337
  Args.reserve(AL.getNumArgs() - 1);
3888
377
  for (unsigned Idx = 1; Idx < AL.getNumArgs(); 
Idx++40
) {
3889
40
    assert(!AL.isArgIdent(Idx));
3890
0
    Args.push_back(AL.getArgAsExpr(Idx));
3891
40
  }
3892
3893
337
  S.AddAnnotationAttr(D, AL, Str, Args);
3894
337
}
3895
3896
277
static void handleAlignValueAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3897
277
  S.AddAlignValueAttr(D, AL, AL.getArgAsExpr(0));
3898
277
}
3899
3900
280
void Sema::AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E) {
3901
280
  AlignValueAttr TmpAttr(Context, CI, E);
3902
280
  SourceLocation AttrLoc = CI.getLoc();
3903
3904
280
  QualType T;
3905
280
  if (const auto *TD = dyn_cast<TypedefNameDecl>(D))
3906
14
    T = TD->getUnderlyingType();
3907
266
  else if (const auto *VD = dyn_cast<ValueDecl>(D))
3908
266
    T = VD->getType();
3909
0
  else
3910
0
    llvm_unreachable("Unknown decl type for align_value");
3911
3912
280
  if (!T->isDependentType() && 
!T->isAnyPointerType()277
&&
3913
280
      
!T->isReferenceType()5
&&
!T->isMemberPointerType()1
) {
3914
1
    Diag(AttrLoc, diag::warn_attribute_pointer_or_reference_only)
3915
1
      << &TmpAttr << T << D->getSourceRange();
3916
1
    return;
3917
1
  }
3918
3919
279
  if (!E->isValueDependent()) {
3920
276
    llvm::APSInt Alignment;
3921
276
    ExprResult ICE = VerifyIntegerConstantExpression(
3922
276
        E, &Alignment, diag::err_align_value_attribute_argument_not_int);
3923
276
    if (ICE.isInvalid())
3924
1
      return;
3925
3926
275
    if (!Alignment.isPowerOf2()) {
3927
3
      Diag(AttrLoc, diag::err_alignment_not_power_of_two)
3928
3
        << E->getSourceRange();
3929
3
      return;
3930
3
    }
3931
3932
272
    D->addAttr(::new (Context) AlignValueAttr(Context, CI, ICE.get()));
3933
272
    return;
3934
275
  }
3935
3936
  // Save dependent expressions in the AST to be instantiated.
3937
3
  D->addAttr(::new (Context) AlignValueAttr(Context, CI, E));
3938
3
}
3939
3940
32.0k
static void handleAlignedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3941
  // check the attribute arguments.
3942
32.0k
  if (AL.getNumArgs() > 1) {
3943
0
    S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
3944
0
    return;
3945
0
  }
3946
3947
32.0k
  if (AL.getNumArgs() == 0) {
3948
46
    D->addAttr(::new (S.Context) AlignedAttr(S.Context, AL, true, nullptr));
3949
46
    return;
3950
46
  }
3951
3952
31.9k
  Expr *E = AL.getArgAsExpr(0);
3953
31.9k
  if (AL.isPackExpansion() && 
!E->containsUnexpandedParameterPack()9
) {
3954
1
    S.Diag(AL.getEllipsisLoc(),
3955
1
           diag::err_pack_expansion_without_parameter_packs);
3956
1
    return;
3957
1
  }
3958
3959
31.9k
  if (!AL.isPackExpansion() && 
S.DiagnoseUnexpandedParameterPack(E)31.9k
)
3960
3
    return;
3961
3962
31.9k
  S.AddAlignedAttr(D, AL, E, AL.isPackExpansion());
3963
31.9k
}
3964
3965
void Sema::AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
3966
32.1k
                          bool IsPackExpansion) {
3967
32.1k
  AlignedAttr TmpAttr(Context, CI, true, E);
3968
32.1k
  SourceLocation AttrLoc = CI.getLoc();
3969
3970
  // C++11 alignas(...) and C11 _Alignas(...) have additional requirements.
3971
32.1k
  if (TmpAttr.isAlignas()) {
3972
    // C++11 [dcl.align]p1:
3973
    //   An alignment-specifier may be applied to a variable or to a class
3974
    //   data member, but it shall not be applied to a bit-field, a function
3975
    //   parameter, the formal parameter of a catch clause, or a variable
3976
    //   declared with the register storage class specifier. An
3977
    //   alignment-specifier may also be applied to the declaration of a class
3978
    //   or enumeration type.
3979
    // C11 6.7.5/2:
3980
    //   An alignment attribute shall not be specified in a declaration of
3981
    //   a typedef, or a bit-field, or a function, or a parameter, or an
3982
    //   object declared with the register storage-class specifier.
3983
9.57k
    int DiagKind = -1;
3984
9.57k
    if (isa<ParmVarDecl>(D)) {
3985
3
      DiagKind = 0;
3986
9.57k
    } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
3987
1.28k
      if (VD->getStorageClass() == SC_Register)
3988
3
        DiagKind = 1;
3989
1.28k
      if (VD->isExceptionVariable())
3990
1
        DiagKind = 2;
3991
8.29k
    } else if (const auto *FD = dyn_cast<FieldDecl>(D)) {
3992
82
      if (FD->isBitField())
3993
3
        DiagKind = 3;
3994
8.21k
    } else if (!isa<TagDecl>(D)) {
3995
8
      Diag(AttrLoc, diag::err_attribute_wrong_decl_type) << &TmpAttr
3996
8
        << (TmpAttr.isC11() ? 
ExpectedVariableOrField2
3997
8
                            : 
ExpectedVariableFieldOrTag6
);
3998
8
      return;
3999
8
    }
4000
9.56k
    if (DiagKind != -1) {
4001
10
      Diag(AttrLoc, diag::err_alignas_attribute_wrong_decl_type)
4002
10
        << &TmpAttr << DiagKind;
4003
10
      return;
4004
10
    }
4005
9.56k
  }
4006
4007
32.1k
  if (E->isValueDependent()) {
4008
    // We can't support a dependent alignment on a non-dependent type,
4009
    // because we have no way to model that a type is "alignment-dependent"
4010
    // but not dependent in any other way.
4011
948
    if (const auto *TND = dyn_cast<TypedefNameDecl>(D)) {
4012
2
      if (!TND->getUnderlyingType()->isDependentType()) {
4013
2
        Diag(AttrLoc, diag::err_alignment_dependent_typedef_name)
4014
2
            << E->getSourceRange();
4015
2
        return;
4016
2
      }
4017
2
    }
4018
4019
    // Save dependent expressions in the AST to be instantiated.
4020
946
    AlignedAttr *AA = ::new (Context) AlignedAttr(Context, CI, true, E);
4021
946
    AA->setPackExpansion(IsPackExpansion);
4022
946
    D->addAttr(AA);
4023
946
    return;
4024
948
  }
4025
4026
  // FIXME: Cache the number on the AL object?
4027
31.2k
  llvm::APSInt Alignment;
4028
31.2k
  ExprResult ICE = VerifyIntegerConstantExpression(
4029
31.2k
      E, &Alignment, diag::err_aligned_attribute_argument_not_int);
4030
31.2k
  if (ICE.isInvalid())
4031
3
    return;
4032
4033
31.2k
  uint64_t AlignVal = Alignment.getZExtValue();
4034
  // 16 byte ByVal alignment not due to a vector member is not honoured by XL
4035
  // on AIX. Emit a warning here that users are generating binary incompatible
4036
  // code to be safe.
4037
31.2k
  if (AlignVal >= 16 && 
isa<FieldDecl>(D)14.8k
&&
4038
31.2k
      
Context.getTargetInfo().getTriple().isOSAIX()764
)
4039
14
    Diag(AttrLoc, diag::warn_not_xl_compatible) << E->getSourceRange();
4040
4041
  // C++11 [dcl.align]p2:
4042
  //   -- if the constant expression evaluates to zero, the alignment
4043
  //      specifier shall have no effect
4044
  // C11 6.7.5p6:
4045
  //   An alignment specification of zero has no effect.
4046
31.2k
  if (!(TmpAttr.isAlignas() && 
!Alignment8.61k
)) {
4047
31.2k
    if (!llvm::isPowerOf2_64(AlignVal)) {
4048
6
      Diag(AttrLoc, diag::err_alignment_not_power_of_two)
4049
6
        << E->getSourceRange();
4050
6
      return;
4051
6
    }
4052
31.2k
  }
4053
4054
31.2k
  unsigned MaximumAlignment = Sema::MaximumAlignment;
4055
31.2k
  if (Context.getTargetInfo().getTriple().isOSBinFormatCOFF())
4056
847
    MaximumAlignment = std::min(MaximumAlignment, 8192u);
4057
31.2k
  if (AlignVal > MaximumAlignment) {
4058
15
    Diag(AttrLoc, diag::err_attribute_aligned_too_great)
4059
15
        << MaximumAlignment << E->getSourceRange();
4060
15
    return;
4061
15
  }
4062
4063
31.1k
  const auto *VD = dyn_cast<VarDecl>(D);
4064
31.1k
  if (VD && 
Context.getTargetInfo().isTLSSupported()2.10k
) {
4065
1.76k
    unsigned MaxTLSAlign =
4066
1.76k
        Context.toCharUnitsFromBits(Context.getTargetInfo().getMaxTLSAlign())
4067
1.76k
            .getQuantity();
4068
1.76k
    if (MaxTLSAlign && 
AlignVal > MaxTLSAlign16
&&
4069
1.76k
        
VD->getTLSKind() != VarDecl::TLS_None2
) {
4070
2
      Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
4071
2
          << (unsigned)AlignVal << VD << MaxTLSAlign;
4072
2
      return;
4073
2
    }
4074
1.76k
  }
4075
4076
  // On AIX, an aligned attribute can not decrease the alignment when applied
4077
  // to a variable declaration with vector type.
4078
31.1k
  if (VD && 
Context.getTargetInfo().getTriple().isOSAIX()2.10k
) {
4079
22
    const Type *Ty = VD->getType().getTypePtr();
4080
22
    if (Ty->isVectorType() && 
AlignVal < 1610
) {
4081
6
      Diag(VD->getLocation(), diag::warn_aligned_attr_underaligned)
4082
6
          << VD->getType() << 16;
4083
6
      return;
4084
6
    }
4085
22
  }
4086
4087
31.1k
  AlignedAttr *AA = ::new (Context) AlignedAttr(Context, CI, true, ICE.get());
4088
31.1k
  AA->setPackExpansion(IsPackExpansion);
4089
31.1k
  D->addAttr(AA);
4090
31.1k
}
4091
4092
void Sema::AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI,
4093
0
                          TypeSourceInfo *TS, bool IsPackExpansion) {
4094
  // FIXME: Cache the number on the AL object if non-dependent?
4095
  // FIXME: Perform checking of type validity
4096
0
  AlignedAttr *AA = ::new (Context) AlignedAttr(Context, CI, false, TS);
4097
0
  AA->setPackExpansion(IsPackExpansion);
4098
0
  D->addAttr(AA);
4099
0
}
4100
4101
1.39M
void Sema::CheckAlignasUnderalignment(Decl *D) {
4102
1.39M
  assert(D->hasAttrs() && "no attributes on decl");
4103
4104
0
  QualType UnderlyingTy, DiagTy;
4105
1.39M
  if (const auto *VD = dyn_cast<ValueDecl>(D)) {
4106
805k
    UnderlyingTy = DiagTy = VD->getType();
4107
805k
  } else {
4108
586k
    UnderlyingTy = DiagTy = Context.getTagDeclType(cast<TagDecl>(D));
4109
586k
    if (const auto *ED = dyn_cast<EnumDecl>(D))
4110
100k
      UnderlyingTy = ED->getIntegerType();
4111
586k
  }
4112
1.39M
  if (DiagTy->isDependentType() || 
DiagTy->isIncompleteType()1.26M
)
4113
132k
    return;
4114
4115
  // C++11 [dcl.align]p5, C11 6.7.5/4:
4116
  //   The combined effect of all alignment attributes in a declaration shall
4117
  //   not specify an alignment that is less strict than the alignment that
4118
  //   would otherwise be required for the entity being declared.
4119
1.25M
  AlignedAttr *AlignasAttr = nullptr;
4120
1.25M
  AlignedAttr *LastAlignedAttr = nullptr;
4121
1.25M
  unsigned Align = 0;
4122
1.25M
  for (auto *I : D->specific_attrs<AlignedAttr>()) {
4123
13.4k
    if (I->isAlignmentDependent())
4124
16
      return;
4125
13.4k
    if (I->isAlignas())
4126
2.42k
      AlignasAttr = I;
4127
13.4k
    Align = std::max(Align, I->getAlignment(Context));
4128
13.4k
    LastAlignedAttr = I;
4129
13.4k
  }
4130
4131
1.25M
  if (Align && 
DiagTy->isSizelessType()13.3k
) {
4132
21
    Diag(LastAlignedAttr->getLocation(), diag::err_attribute_sizeless_type)
4133
21
        << LastAlignedAttr << DiagTy;
4134
1.25M
  } else if (AlignasAttr && 
Align2.37k
) {
4135
2.37k
    CharUnits RequestedAlign = Context.toCharUnitsFromBits(Align);
4136
2.37k
    CharUnits NaturalAlign = Context.getTypeAlignInChars(UnderlyingTy);
4137
2.37k
    if (NaturalAlign > RequestedAlign)
4138
27
      Diag(AlignasAttr->getLocation(), diag::err_alignas_underaligned)
4139
27
        << DiagTy << (unsigned)NaturalAlign.getQuantity();
4140
2.37k
  }
4141
1.25M
}
4142
4143
bool Sema::checkMSInheritanceAttrOnDefinition(
4144
    CXXRecordDecl *RD, SourceRange Range, bool BestCase,
4145
91
    MSInheritanceModel ExplicitModel) {
4146
91
  assert(RD->hasDefinition() && "RD has no definition!");
4147
4148
  // We may not have seen base specifiers or any virtual methods yet.  We will
4149
  // have to wait until the record is defined to catch any mismatches.
4150
91
  if (!RD->getDefinition()->isCompleteDefinition())
4151
29
    return false;
4152
4153
  // The unspecified model never matches what a definition could need.
4154
62
  if (ExplicitModel == MSInheritanceModel::Unspecified)
4155
33
    return false;
4156
4157
29
  if (BestCase) {
4158
27
    if (RD->calculateInheritanceModel() == ExplicitModel)
4159
21
      return false;
4160
27
  } else {
4161
2
    if (RD->calculateInheritanceModel() <= ExplicitModel)
4162
2
      return false;
4163
2
  }
4164
4165
6
  Diag(Range.getBegin(), diag::err_mismatched_ms_inheritance)
4166
6
      << 0 /*definition*/;
4167
6
  Diag(RD->getDefinition()->getLocation(), diag::note_defined_here) << RD;
4168
6
  return true;
4169
29
}
4170
4171
/// parseModeAttrArg - Parses attribute mode string and returns parsed type
4172
/// attribute.
4173
static void parseModeAttrArg(Sema &S, StringRef Str, unsigned &DestWidth,
4174
                             bool &IntegerMode, bool &ComplexMode,
4175
369
                             bool &ExplicitIEEE) {
4176
369
  IntegerMode = true;
4177
369
  ComplexMode = false;
4178
369
  switch (Str.size()) {
4179
334
  case 2:
4180
334
    switch (Str[0]) {
4181
66
    case 'Q':
4182
66
      DestWidth = 8;
4183
66
      break;
4184
67
    case 'H':
4185
67
      DestWidth = 16;
4186
67
      break;
4187
93
    case 'S':
4188
93
      DestWidth = 32;
4189
93
      break;
4190
81
    case 'D':
4191
81
      DestWidth = 64;
4192
81
      break;
4193
5
    case 'X':
4194
5
      DestWidth = 96;
4195
5
      break;
4196
4
    case 'K': // KFmode - IEEE quad precision (__float128)
4197
4
      ExplicitIEEE = true;
4198
4
      DestWidth = Str[1] == 'I' ? 
01
:
1283
;
4199
4
      break;
4200
9
    case 'T':
4201
9
      ExplicitIEEE = false;
4202
9
      DestWidth = 128;
4203
9
      break;
4204
334
    }
4205
334
    if (Str[1] == 'F') {
4206
52
      IntegerMode = false;
4207
282
    } else if (Str[1] == 'C') {
4208
26
      IntegerMode = false;
4209
26
      ComplexMode = true;
4210
256
    } else if (Str[1] != 'I') {
4211
0
      DestWidth = 0;
4212
0
    }
4213
334
    break;
4214
7
  case 4:
4215
    // FIXME: glibc uses 'word' to define register_t; this is narrower than a
4216
    // pointer on PIC16 and other embedded platforms.
4217
7
    if (Str == "word")
4218
1
      DestWidth = S.Context.getTargetInfo().getRegisterWidth();
4219
6
    else if (Str == "byte")
4220
5
      DestWidth = S.Context.getTargetInfo().getCharWidth();
4221
7
    break;
4222
0
  case 7:
4223
0
    if (Str == "pointer")
4224
0
      DestWidth = S.Context.getTargetInfo().getPointerWidth(0);
4225
0
    break;
4226
28
  case 11:
4227
28
    if (Str == "unwind_word")
4228
28
      DestWidth = S.Context.getTargetInfo().getUnwindWordWidth();
4229
28
    break;
4230
369
  }
4231
369
}
4232
4233
/// handleModeAttr - This attribute modifies the width of a decl with primitive
4234
/// type.
4235
///
4236
/// Despite what would be logical, the mode attribute is a decl attribute, not a
4237
/// type attribute: 'int ** __attribute((mode(HI))) *G;' tries to make 'G' be
4238
/// HImode, not an intermediate pointer.
4239
294
static void handleModeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4240
  // This attribute isn't documented, but glibc uses it.  It changes
4241
  // the width of an int or unsigned int to the specified size.
4242
294
  if (!AL.isArgIdent(0)) {
4243
9
    S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
4244
9
        << AL << AANT_ArgumentIdentifier;
4245
9
    return;
4246
9
  }
4247
4248
285
  IdentifierInfo *Name = AL.getArgAsIdent(0)->Ident;
4249
4250
285
  S.AddModeAttr(D, AL, Name);
4251
285
}
4252
4253
void Sema::AddModeAttr(Decl *D, const AttributeCommonInfo &CI,
4254
369
                       IdentifierInfo *Name, bool InInstantiation) {
4255
369
  StringRef Str = Name->getName();
4256
369
  normalizeName(Str);
4257
369
  SourceLocation AttrLoc = CI.getLoc();
4258
4259
369
  unsigned DestWidth = 0;
4260
369
  bool IntegerMode = true;
4261
369
  bool ComplexMode = false;
4262
369
  bool ExplicitIEEE = false;
4263
369
  llvm::APInt VectorSize(64, 0);
4264
369
  if (Str.size() >= 4 && 
Str[0] == 'V'85
) {
4265
    // Minimal length of vector mode is 4: 'V' + NUMBER(>=1) + TYPE(>=2).
4266
51
    size_t StrSize = Str.size();
4267
51
    size_t VectorStringLength = 0;
4268
106
    while ((VectorStringLength + 1) < StrSize &&
4269
106
           isdigit(Str[VectorStringLength + 1]))
4270
55
      ++VectorStringLength;
4271
51
    if (VectorStringLength &&
4272
51
        !Str.substr(1, VectorStringLength).getAsInteger(10, VectorSize) &&
4273
51
        VectorSize.isPowerOf2()) {
4274
50
      parseModeAttrArg(*this, Str.substr(VectorStringLength + 1), DestWidth,
4275
50
                       IntegerMode, ComplexMode, ExplicitIEEE);
4276
      // Avoid duplicate warning from template instantiation.
4277
50
      if (!InInstantiation)
4278
25
        Diag(AttrLoc, diag::warn_vector_mode_deprecated);
4279
50
    } else {
4280
1
      VectorSize = 0;
4281
1
    }
4282
51
  }
4283
4284
369
  if (!VectorSize)
4285
319
    parseModeAttrArg(*this, Str, DestWidth, IntegerMode, ComplexMode,
4286
319
                     ExplicitIEEE);
4287
4288
  // FIXME: Sync this with InitializePredefinedMacros; we need to match int8_t
4289
  // and friends, at least with glibc.
4290
  // FIXME: Make sure floating-point mappings are accurate
4291
  // FIXME: Support XF and TF types
4292
369
  if (!DestWidth) {
4293
11
    Diag(AttrLoc, diag::err_machine_mode) << 0 /*Unknown*/ << Name;
4294
11
    return;
4295
11
  }
4296
4297
358
  QualType OldTy;
4298
358
  if (const auto *TD = dyn_cast<TypedefNameDecl>(D))
4299
274
    OldTy = TD->getUnderlyingType();
4300
84
  else if (const auto *ED = dyn_cast<EnumDecl>(D)) {
4301
    // Something like 'typedef enum { X } __attribute__((mode(XX))) T;'.
4302
    // Try to get type from enum declaration, default to int.
4303
20
    OldTy = ED->getIntegerType();
4304
20
    if (OldTy.isNull())
4305
20
      OldTy = Context.IntTy;
4306
20
  } else
4307
64
    OldTy = cast<ValueDecl>(D)->getType();
4308
4309
358
  if (OldTy->isDependentType()) {
4310
31
    D->addAttr(::new (Context) ModeAttr(Context, CI, Name));
4311
31
    return;
4312
31
  }
4313
4314
  // Base type can also be a vector type (see PR17453).
4315
  // Distinguish between base type and base element type.
4316
327
  QualType OldElemTy = OldTy;
4317
327
  if (const auto *VT = OldTy->getAs<VectorType>())
4318
28
    OldElemTy = VT->getElementType();
4319
4320
  // GCC allows 'mode' attribute on enumeration types (even incomplete), except
4321
  // for vector modes. So, 'enum X __attribute__((mode(QI)));' forms a complete
4322
  // type, 'enum { A } __attribute__((mode(V4SI)))' is rejected.
4323
327
  if ((isa<EnumDecl>(D) || 
OldElemTy->getAs<EnumType>()307
) &&
4324
327
      
VectorSize.getBoolValue()55
) {
4325
13
    Diag(AttrLoc, diag::err_enum_mode_vector_type) << Name << CI.getRange();
4326
13
    return;
4327
13
  }
4328
314
  bool IntegralOrAnyEnumType = (OldElemTy->isIntegralOrEnumerationType() &&
4329
314
                                
!OldElemTy->isExtIntType()218
) ||
4330
314
                               
OldElemTy->getAs<EnumType>()97
;
4331
4332
314
  if (!OldElemTy->getAs<BuiltinType>() && 
!OldElemTy->isComplexType()69
&&
4333
314
      
!IntegralOrAnyEnumType46
)
4334
19
    Diag(AttrLoc, diag::err_mode_not_primitive);
4335
295
  else if (IntegerMode) {
4336
224
    if (!IntegralOrAnyEnumType)
4337
12
      Diag(AttrLoc, diag::err_mode_wrong_type);
4338
224
  } else 
if (71
ComplexMode71
) {
4339
26
    if (!OldElemTy->isComplexType())
4340
3
      Diag(AttrLoc, diag::err_mode_wrong_type);
4341
45
  } else {
4342
45
    if (!OldElemTy->isFloatingType())
4343
11
      Diag(AttrLoc, diag::err_mode_wrong_type);
4344
45
  }
4345
4346
314
  QualType NewElemTy;
4347
4348
314
  if (IntegerMode)
4349
243
    NewElemTy = Context.getIntTypeForBitwidth(DestWidth,
4350
243
                                              OldElemTy->isSignedIntegerType());
4351
71
  else
4352
71
    NewElemTy = Context.getRealTypeForBitwidth(DestWidth, ExplicitIEEE);
4353
4354
314
  if (NewElemTy.isNull()) {
4355
2
    Diag(AttrLoc, diag::err_machine_mode) << 1 /*Unsupported*/ << Name;
4356
2
    return;
4357
2
  }
4358
4359
312
  if (ComplexMode) {
4360
24
    NewElemTy = Context.getComplexType(NewElemTy);
4361
24
  }
4362
4363
312
  QualType NewTy = NewElemTy;
4364
312
  if (VectorSize.getBoolValue()) {
4365
25
    NewTy = Context.getVectorType(NewTy, VectorSize.getZExtValue(),
4366
25
                                  VectorType::GenericVector);
4367
287
  } else if (const auto *OldVT = OldTy->getAs<VectorType>()) {
4368
    // Complex machine mode does not support base vector types.
4369
27
    if (ComplexMode) {
4370
2
      Diag(AttrLoc, diag::err_complex_mode_vector_type);
4371
2
      return;
4372
2
    }
4373
25
    unsigned NumElements = Context.getTypeSize(OldElemTy) *
4374
25
                           OldVT->getNumElements() /
4375
25
                           Context.getTypeSize(NewElemTy);
4376
25
    NewTy =
4377
25
        Context.getVectorType(NewElemTy, NumElements, OldVT->getVectorKind());
4378
25
  }
4379
4380
310
  if (NewTy.isNull()) {
4381
0
    Diag(AttrLoc, diag::err_mode_wrong_type);
4382
0
    return;
4383
0
  }
4384
4385
  // Install the new type.
4386
310
  if (auto *TD = dyn_cast<TypedefNameDecl>(D))
4387
244
    TD->setModedTypeSourceInfo(TD->getTypeSourceInfo(), NewTy);
4388
66
  else if (auto *ED = dyn_cast<EnumDecl>(D))
4389
15
    ED->setIntegerType(NewTy);
4390
51
  else
4391
51
    cast<ValueDecl>(D)->setType(NewTy);
4392
4393
310
  D->addAttr(::new (Context) ModeAttr(Context, CI, Name));
4394
310
}
4395
4396
26.2M
static void handleNoDebugAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4397
26.2M
  D->addAttr(::new (S.Context) NoDebugAttr(S.Context, AL));
4398
26.2M
}
4399
4400
AlwaysInlineAttr *Sema::mergeAlwaysInlineAttr(Decl *D,
4401
                                              const AttributeCommonInfo &CI,
4402
26.4M
                                              const IdentifierInfo *Ident) {
4403
26.4M
  if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
4404
11
    Diag(CI.getLoc(), diag::warn_attribute_ignored) << Ident;
4405
11
    Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
4406
11
    return nullptr;
4407
11
  }
4408
4409
26.4M
  if (D->hasAttr<AlwaysInlineAttr>())
4410
6.94k
    return nullptr;
4411
4412
26.4M
  return ::new (Context) AlwaysInlineAttr(Context, CI);
4413
26.4M
}
4414
4415
InternalLinkageAttr *Sema::mergeInternalLinkageAttr(Decl *D,
4416
1.16k
                                                    const ParsedAttr &AL) {
4417
1.16k
  if (const auto *VD = dyn_cast<VarDecl>(D)) {
4418
    // Attribute applies to Var but not any subclass of it (like ParmVar,
4419
    // ImplicitParm or VarTemplateSpecialization).
4420
1.14k
    if (VD->getKind() != Decl::Var) {
4421
1
      Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
4422
1
          << AL << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass
4423
1
                                            : 
ExpectedVariableOrFunction0
);
4424
1
      return nullptr;
4425
1
    }
4426
    // Attribute does not apply to non-static local variables.
4427
1.14k
    if (VD->hasLocalStorage()) {
4428
1
      Diag(VD->getLocation(), diag::warn_internal_linkage_local_storage);
4429
1
      return nullptr;
4430
1
    }
4431
1.14k
  }
4432
4433
1.16k
  return ::new (Context) InternalLinkageAttr(Context, AL);
4434
1.16k
}
4435
InternalLinkageAttr *
4436
7
Sema::mergeInternalLinkageAttr(Decl *D, const InternalLinkageAttr &AL) {
4437
7
  if (const auto *VD = dyn_cast<VarDecl>(D)) {
4438
    // Attribute applies to Var but not any subclass of it (like ParmVar,
4439
    // ImplicitParm or VarTemplateSpecialization).
4440
3
    if (VD->getKind() != Decl::Var) {
4441
0
      Diag(AL.getLocation(), diag::warn_attribute_wrong_decl_type)
4442
0
          << &AL << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass
4443
0
                                             : ExpectedVariableOrFunction);
4444
0
      return nullptr;
4445
0
    }
4446
    // Attribute does not apply to non-static local variables.
4447
3
    if (VD->hasLocalStorage()) {
4448
0
      Diag(VD->getLocation(), diag::warn_internal_linkage_local_storage);
4449
0
      return nullptr;
4450
0
    }
4451
3
  }
4452
4453
7
  return ::new (Context) InternalLinkageAttr(Context, AL);
4454
7
}
4455
4456
27
MinSizeAttr *Sema::mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI) {
4457
27
  if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
4458
4
    Diag(CI.getLoc(), diag::warn_attribute_ignored) << "'minsize'";
4459
4
    Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
4460
4
    return nullptr;
4461
4
  }
4462
4463
23
  if (D->hasAttr<MinSizeAttr>())
4464
0
    return nullptr;
4465
4466
23
  return ::new (Context) MinSizeAttr(Context, CI);
4467
23
}
4468
4469
SwiftNameAttr *Sema::mergeSwiftNameAttr(Decl *D, const SwiftNameAttr &SNA,
4470
13
                                        StringRef Name) {
4471
13
  if (const auto *PrevSNA = D->getAttr<SwiftNameAttr>()) {
4472
11
    if (PrevSNA->getName() != Name && 
!PrevSNA->isImplicit()1
) {
4473
1
      Diag(PrevSNA->getLocation(), diag::err_attributes_are_not_compatible)
4474
1
          << PrevSNA << &SNA;
4475
1
      Diag(SNA.getLoc(), diag::note_conflicting_attribute);
4476
1
    }
4477
4478
11
    D->dropAttr<SwiftNameAttr>();
4479
11
  }
4480
13
  return ::new (Context) SwiftNameAttr(Context, SNA, Name);
4481
13
}
4482
4483
OptimizeNoneAttr *Sema::mergeOptimizeNoneAttr(Decl *D,
4484
143
                                              const AttributeCommonInfo &CI) {
4485
143
  if (AlwaysInlineAttr *Inline = D->getAttr<AlwaysInlineAttr>()) {
4486
6
    Diag(Inline->getLocation(), diag::warn_attribute_ignored) << Inline;
4487
6
    Diag(CI.getLoc(), diag::note_conflicting_attribute);
4488
6
    D->dropAttr<AlwaysInlineAttr>();
4489
6
  }
4490
143
  if (MinSizeAttr *MinSize = D->getAttr<MinSizeAttr>()) {
4491
3
    Diag(MinSize->getLocation(), diag::warn_attribute_ignored) << MinSize;
4492
3
    Diag(CI.getLoc(), diag::note_conflicting_attribute);
4493
3
    D->dropAttr<MinSizeAttr>();
4494
3
  }
4495
4496
143
  if (D->hasAttr<OptimizeNoneAttr>())
4497
1
    return nullptr;
4498
4499
142
  return ::new (Context) OptimizeNoneAttr(Context, CI);
4500
143
}
4501
4502
26.4M
static void handleAlwaysInlineAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4503
26.4M
  if (AlwaysInlineAttr *Inline =
4504
26.4M
          S.mergeAlwaysInlineAttr(D, AL, AL.getAttrName()))
4505
26.4M
    D->addAttr(Inline);
4506
26.4M
}
4507
4508
24
static void handleMinSizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4509
24
  if (MinSizeAttr *MinSize = S.mergeMinSizeAttr(D, AL))
4510
23
    D->addAttr(MinSize);
4511
24
}
4512
4513
131
static void handleOptimizeNoneAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4514
131
  if (OptimizeNoneAttr *Optnone = S.mergeOptimizeNoneAttr(D, AL))
4515
131
    D->addAttr(Optnone);
4516
131
}
4517
4518
309
static void handleConstantAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4519
309
  const auto *VD = cast<VarDecl>(D);
4520
309
  if (VD->hasLocalStorage()) {
4521
6
    S.Diag(AL.getLoc(), diag::err_cuda_nonstatic_constdev);
4522
6
    return;
4523
6
  }
4524
  // constexpr variable may already get an implicit constant attr, which should
4525
  // be replaced by the explicit constant attr.
4526
303
  if (auto *A = D->getAttr<CUDAConstantAttr>()) {
4527
2
    if (!A->isImplicit())
4528
2
      return;
4529
0
    D->dropAttr<CUDAConstantAttr>();
4530
0
  }
4531
301
  D->addAttr(::new (S.Context) CUDAConstantAttr(S.Context, AL));
4532
301
}
4533
4534
300
static void handleSharedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4535
300
  const auto *VD = cast<VarDecl>(D);
4536
  // extern __shared__ is only allowed on arrays with no length (e.g.
4537
  // "int x[]").
4538
300
  if (!S.getLangOpts().GPURelocatableDeviceCode && 
VD->hasExternalStorage()266
&&
4539
300
      
!isa<IncompleteArrayType>(VD->getType())28
) {
4540
18
    S.Diag(AL.getLoc(), diag::err_cuda_extern_shared) << VD;
4541
18
    return;
4542
18
  }
4543
282
  if (S.getLangOpts().CUDA && VD->hasLocalStorage() &&
4544
282
      S.CUDADiagIfHostCode(AL.getLoc(), diag::err_cuda_host_shared)
4545
32
          << S.CurrentCUDATarget())
4546
2
    return;
4547
280
  D->addAttr(::new (S.Context) CUDASharedAttr(S.Context, AL));
4548
280
}
4549
4550
346
static void handleGlobalAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4551
346
  const auto *FD = cast<FunctionDecl>(D);
4552
346
  if (!FD->getReturnType()->isVoidType() &&
4553
346
      
!FD->getReturnType()->getAs<AutoType>()11
&&
4554
346
      
!FD->getReturnType()->isInstantiationDependentType()7
) {
4555
4
    SourceRange RTRange = FD->getReturnTypeSourceRange();
4556
4
    S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return)
4557
4
        << FD->getType()
4558
4
        << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
4559
4
                              : 
FixItHint()0
);
4560
4
    return;
4561
4
  }
4562
342
  if (const auto *Method = dyn_cast<CXXMethodDecl>(FD)) {
4563
13
    if (Method->isInstance()) {
4564
4
      S.Diag(Method->getBeginLoc(), diag::err_kern_is_nonstatic_method)
4565
4
          << Method;
4566
4
      return;
4567
4
    }
4568
9
    S.Diag(Method->getBeginLoc(), diag::warn_kern_is_method) << Method;
4569
9
  }
4570
  // Only warn for "inline" when compiling for host, to cut down on noise.
4571
338
  if (FD->isInlineSpecified() && 
!S.getLangOpts().CUDAIsDevice2
)
4572
1
    S.Diag(FD->getBeginLoc(), diag::warn_kern_is_inline) << FD;
4573
4574
338
  D->addAttr(::new (S.Context) CUDAGlobalAttr(S.Context, AL));
4575
  // In host compilation the kernel is emitted as a stub function, which is
4576
  // a helper function for launching the kernel. The instructions in the helper
4577
  // function has nothing to do with the source code of the kernel. Do not emit
4578
  // debug info for the stub function to avoid confusing the debugger.
4579
338
  if (S.LangOpts.HIP && 
!S.LangOpts.CUDAIsDevice123
)
4580
46
    D->addAttr(NoDebugAttr::CreateImplicit(S.Context));
4581
338
}
4582
4583
8.02k
static void handleDeviceAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4584
8.02k
  if (const auto *VD = dyn_cast<VarDecl>(D)) {
4585
445
    if (VD->hasLocalStorage()) {
4586
2
      S.Diag(AL.getLoc(), diag::err_cuda_nonstatic_constdev);
4587
2
      return;
4588
2
    }
4589
445
  }
4590
4591
8.02k
  if (auto *A = D->getAttr<CUDADeviceAttr>()) {
4592
22
    if (!A->isImplicit())
4593
16
      return;
4594
6
    D->dropAttr<CUDADeviceAttr>();
4595
6
  }
4596
8.00k
  D->addAttr(::new (S.Context) CUDADeviceAttr(S.Context, AL));
4597
8.00k
}
4598
4599
84
static void handleManagedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4600
84
  if (const auto *VD = dyn_cast<VarDecl>(D)) {
4601
84
    if (VD->hasLocalStorage()) {
4602
4
      S.Diag(AL.getLoc(), diag::err_cuda_nonstatic_constdev);
4603
4
      return;
4604
4
    }
4605
84
  }
4606
80
  if (!D->hasAttr<HIPManagedAttr>())
4607
74
    D->addAttr(::new (S.Context) HIPManagedAttr(S.Context, AL));
4608
80
  if (!D->hasAttr<CUDADeviceAttr>())
4609
68
    D->addAttr(CUDADeviceAttr::CreateImplicit(S.Context));
4610
80
}
4611
4612
7.55k
static void handleGNUInlineAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4613
7.55k
  const auto *Fn = cast<FunctionDecl>(D);
4614
7.55k
  if (!Fn->isInlineSpecified()) {
4615
2
    S.Diag(AL.getLoc(), diag::warn_gnu_inline_attribute_requires_inline);
4616
2
    return;
4617
2
  }
4618
4619
7.54k
  if (S.LangOpts.CPlusPlus && 
Fn->getStorageClass() != SC_Extern590
)
4620
11
    S.Diag(AL.getLoc(), diag::warn_gnu_inline_cplusplus_without_extern);
4621
4622
7.54k
  D->addAttr(::new (S.Context) GNUInlineAttr(S.Context, AL));
4623
7.54k
}
4624
4625
5.33k
static void handleCallConvAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4626
5.33k
  if (hasDeclarator(D)) 
return5.32k
;
4627
4628
  // Diagnostic is emitted elsewhere: here we store the (valid) AL
4629
  // in the Decl node for syntactic reasoning, e.g., pretty-printing.
4630
17
  CallingConv CC;
4631
17
  if (S.CheckCallingConvAttr(AL, CC, /*FD*/nullptr))
4632
0
    return;
4633
4634
17
  if (!isa<ObjCMethodDecl>(D)) {
4635
14
    S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
4636
14
        << AL << ExpectedFunctionOrMethod;
4637
14
    return;
4638
14
  }
4639
</