Coverage Report

Created: 2020-09-22 08:39

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Sema/SemaChecking.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- SemaChecking.cpp - Extra Semantic Checking -------------------------===//
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 extra semantic analysis beyond what is enforced
10
//  by the C type system.
11
//
12
//===----------------------------------------------------------------------===//
13
14
#include "clang/AST/APValue.h"
15
#include "clang/AST/ASTContext.h"
16
#include "clang/AST/Attr.h"
17
#include "clang/AST/AttrIterator.h"
18
#include "clang/AST/CharUnits.h"
19
#include "clang/AST/Decl.h"
20
#include "clang/AST/DeclBase.h"
21
#include "clang/AST/DeclCXX.h"
22
#include "clang/AST/DeclObjC.h"
23
#include "clang/AST/DeclarationName.h"
24
#include "clang/AST/EvaluatedExprVisitor.h"
25
#include "clang/AST/Expr.h"
26
#include "clang/AST/ExprCXX.h"
27
#include "clang/AST/ExprObjC.h"
28
#include "clang/AST/ExprOpenMP.h"
29
#include "clang/AST/FormatString.h"
30
#include "clang/AST/NSAPI.h"
31
#include "clang/AST/NonTrivialTypeVisitor.h"
32
#include "clang/AST/OperationKinds.h"
33
#include "clang/AST/RecordLayout.h"
34
#include "clang/AST/Stmt.h"
35
#include "clang/AST/TemplateBase.h"
36
#include "clang/AST/Type.h"
37
#include "clang/AST/TypeLoc.h"
38
#include "clang/AST/UnresolvedSet.h"
39
#include "clang/Basic/AddressSpaces.h"
40
#include "clang/Basic/CharInfo.h"
41
#include "clang/Basic/Diagnostic.h"
42
#include "clang/Basic/IdentifierTable.h"
43
#include "clang/Basic/LLVM.h"
44
#include "clang/Basic/LangOptions.h"
45
#include "clang/Basic/OpenCLOptions.h"
46
#include "clang/Basic/OperatorKinds.h"
47
#include "clang/Basic/PartialDiagnostic.h"
48
#include "clang/Basic/SourceLocation.h"
49
#include "clang/Basic/SourceManager.h"
50
#include "clang/Basic/Specifiers.h"
51
#include "clang/Basic/SyncScope.h"
52
#include "clang/Basic/TargetBuiltins.h"
53
#include "clang/Basic/TargetCXXABI.h"
54
#include "clang/Basic/TargetInfo.h"
55
#include "clang/Basic/TypeTraits.h"
56
#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
57
#include "clang/Sema/Initialization.h"
58
#include "clang/Sema/Lookup.h"
59
#include "clang/Sema/Ownership.h"
60
#include "clang/Sema/Scope.h"
61
#include "clang/Sema/ScopeInfo.h"
62
#include "clang/Sema/Sema.h"
63
#include "clang/Sema/SemaInternal.h"
64
#include "llvm/ADT/APFloat.h"
65
#include "llvm/ADT/APInt.h"
66
#include "llvm/ADT/APSInt.h"
67
#include "llvm/ADT/ArrayRef.h"
68
#include "llvm/ADT/DenseMap.h"
69
#include "llvm/ADT/FoldingSet.h"
70
#include "llvm/ADT/None.h"
71
#include "llvm/ADT/Optional.h"
72
#include "llvm/ADT/STLExtras.h"
73
#include "llvm/ADT/SmallBitVector.h"
74
#include "llvm/ADT/SmallPtrSet.h"
75
#include "llvm/ADT/SmallString.h"
76
#include "llvm/ADT/SmallVector.h"
77
#include "llvm/ADT/StringRef.h"
78
#include "llvm/ADT/StringSwitch.h"
79
#include "llvm/ADT/Triple.h"
80
#include "llvm/Support/AtomicOrdering.h"
81
#include "llvm/Support/Casting.h"
82
#include "llvm/Support/Compiler.h"
83
#include "llvm/Support/ConvertUTF.h"
84
#include "llvm/Support/ErrorHandling.h"
85
#include "llvm/Support/Format.h"
86
#include "llvm/Support/Locale.h"
87
#include "llvm/Support/MathExtras.h"
88
#include "llvm/Support/SaveAndRestore.h"
89
#include "llvm/Support/raw_ostream.h"
90
#include <algorithm>
91
#include <bitset>
92
#include <cassert>
93
#include <cstddef>
94
#include <cstdint>
95
#include <functional>
96
#include <limits>
97
#include <string>
98
#include <tuple>
99
#include <utility>
100
101
using namespace clang;
102
using namespace sema;
103
104
SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
105
24
                                                    unsigned ByteNo) const {
106
24
  return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
107
24
                               Context.getTargetInfo());
108
24
}
109
110
/// Checks that a call expression's argument count is the desired number.
111
/// This is useful when doing custom type-checking.  Returns true on error.
112
12.6k
static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
113
12.6k
  unsigned argCount = call->getNumArgs();
114
12.6k
  if (argCount == desiredArgCount) 
return false12.5k
;
115
116
79
  if (argCount < desiredArgCount)
117
42
    return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args)
118
42
           << 0 /*function call*/ << desiredArgCount << argCount
119
42
           << call->getSourceRange();
120
121
  // Highlight all the excess arguments.
122
37
  SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(),
123
37
                    call->getArg(argCount - 1)->getEndLoc());
124
125
37
  return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
126
37
    << 0 /*function call*/ << desiredArgCount << argCount
127
37
    << call->getArg(1)->getSourceRange();
128
37
}
129
130
/// Check that the first argument to __builtin_annotation is an integer
131
/// and the second argument is a non-wide string literal.
132
12
static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
133
12
  if (checkArgCount(S, TheCall, 2))
134
0
    return true;
135
136
  // First argument should be an integer.
137
12
  Expr *ValArg = TheCall->getArg(0);
138
12
  QualType Ty = ValArg->getType();
139
12
  if (!Ty->isIntegerType()) {
140
1
    S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
141
1
        << ValArg->getSourceRange();
142
1
    return true;
143
1
  }
144
145
  // Second argument should be a constant string.
146
11
  Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
147
11
  StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
148
11
  if (!Literal || 
!Literal->isAscii()10
) {
149
2
    S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
150
2
        << StrArg->getSourceRange();
151
2
    return true;
152
2
  }
153
154
9
  TheCall->setType(Ty);
155
9
  return false;
156
9
}
157
158
31
static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
159
  // We need at least one argument.
160
31
  if (TheCall->getNumArgs() < 1) {
161
3
    S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
162
3
        << 0 << 1 << TheCall->getNumArgs()
163
3
        << TheCall->getCallee()->getSourceRange();
164
3
    return true;
165
3
  }
166
167
  // All arguments should be wide string literals.
168
49
  
for (Expr *Arg : TheCall->arguments())28
{
169
49
    auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
170
49
    if (!Literal || 
!Literal->isWide()43
) {
171
6
      S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
172
6
          << Arg->getSourceRange();
173
6
      return true;
174
6
    }
175
49
  }
176
177
22
  return false;
178
28
}
179
180
/// Check that the argument to __builtin_addressof is a glvalue, and set the
181
/// result type to the corresponding pointer type.
182
1.06k
static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
183
1.06k
  if (checkArgCount(S, TheCall, 1))
184
0
    return true;
185
186
1.06k
  ExprResult Arg(TheCall->getArg(0));
187
1.06k
  QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
188
1.06k
  if (ResultType.isNull())
189
2
    return true;
190
191
1.06k
  TheCall->setArg(0, Arg.get());
192
1.06k
  TheCall->setType(ResultType);
193
1.06k
  return false;
194
1.06k
}
195
196
/// Check the number of arguments and set the result type to
197
/// the argument type.
198
29
static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
199
29
  if (checkArgCount(S, TheCall, 1))
200
1
    return true;
201
202
28
  TheCall->setType(TheCall->getArg(0)->getType());
203
28
  return false;
204
28
}
205
206
/// Check that the value argument for __builtin_is_aligned(value, alignment) and
207
/// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer
208
/// type (but not a function pointer) and that the alignment is a power-of-two.
209
281
static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) {
210
281
  if (checkArgCount(S, TheCall, 2))
211
1
    return true;
212
213
280
  clang::Expr *Source = TheCall->getArg(0);
214
280
  bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned;
215
216
406
  auto IsValidIntegerType = [](QualType Ty) {
217
406
    return Ty->isIntegerType() && 
!Ty->isEnumeralType()386
&&
!Ty->isBooleanType()380
;
218
406
  };
219
280
  QualType SrcTy = Source->getType();
220
  // We should also be able to use it with arrays (but not functions!).
221
280
  if (SrcTy->canDecayToPointerType() && 
SrcTy->isArrayType()24
) {
222
21
    SrcTy = S.Context.getDecayedType(SrcTy);
223
21
  }
224
280
  if ((!SrcTy->isPointerType() && 
!IsValidIntegerType(SrcTy)150
) ||
225
259
      SrcTy->isFunctionPointerType()) {
226
    // FIXME: this is not quite the right error message since we don't allow
227
    // floating point types, or member pointers.
228
24
    S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand)
229
24
        << SrcTy;
230
24
    return true;
231
24
  }
232
233
256
  clang::Expr *AlignOp = TheCall->getArg(1);
234
256
  if (!IsValidIntegerType(AlignOp->getType())) {
235
12
    S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int)
236
12
        << AlignOp->getType();
237
12
    return true;
238
12
  }
239
244
  Expr::EvalResult AlignResult;
240
244
  unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1;
241
  // We can't check validity of alignment if it is value dependent.
242
244
  if (!AlignOp->isValueDependent() &&
243
243
      AlignOp->EvaluateAsInt(AlignResult, S.Context,
244
196
                             Expr::SE_AllowSideEffects)) {
245
196
    llvm::APSInt AlignValue = AlignResult.Val.getInt();
246
196
    llvm::APSInt MaxValue(
247
196
        llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits));
248
196
    if (AlignValue < 1) {
249
4
      S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1;
250
4
      return true;
251
4
    }
252
192
    if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) {
253
15
      S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big)
254
15
          << MaxValue.toString(10);
255
15
      return true;
256
15
    }
257
177
    if (!AlignValue.isPowerOf2()) {
258
16
      S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two);
259
16
      return true;
260
16
    }
261
161
    if (AlignValue == 1) {
262
3
      S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless)
263
3
          << IsBooleanAlignBuiltin;
264
3
    }
265
161
  }
266
267
209
  ExprResult SrcArg = S.PerformCopyInitialization(
268
209
      InitializedEntity::InitializeParameter(S.Context, SrcTy, false),
269
209
      SourceLocation(), Source);
270
209
  if (SrcArg.isInvalid())
271
0
    return true;
272
209
  TheCall->setArg(0, SrcArg.get());
273
209
  ExprResult AlignArg =
274
209
      S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
275
209
                                      S.Context, AlignOp->getType(), false),
276
209
                                  SourceLocation(), AlignOp);
277
209
  if (AlignArg.isInvalid())
278
0
    return true;
279
209
  TheCall->setArg(1, AlignArg.get());
280
  // For align_up/align_down, the return type is the same as the (potentially
281
  // decayed) argument type including qualifiers. For is_aligned(), the result
282
  // is always bool.
283
138
  TheCall->setType(IsBooleanAlignBuiltin ? 
S.Context.BoolTy71
: SrcTy);
284
209
  return false;
285
209
}
286
287
static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall,
288
105
                                unsigned BuiltinID) {
289
105
  if (checkArgCount(S, TheCall, 3))
290
2
    return true;
291
292
  // First two arguments should be integers.
293
306
  
for (unsigned I = 0; 103
I < 2;
++I203
) {
294
205
    ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(I));
295
205
    if (Arg.isInvalid()) 
return true0
;
296
205
    TheCall->setArg(I, Arg.get());
297
298
205
    QualType Ty = Arg.get()->getType();
299
205
    if (!Ty->isIntegerType()) {
300
2
      S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
301
2
          << Ty << Arg.get()->getSourceRange();
302
2
      return true;
303
2
    }
304
205
  }
305
306
  // Third argument should be a pointer to a non-const integer.
307
  // IRGen correctly handles volatile, restrict, and address spaces, and
308
  // the other qualifiers aren't possible.
309
101
  {
310
101
    ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(2));
311
101
    if (Arg.isInvalid()) 
return true0
;
312
101
    TheCall->setArg(2, Arg.get());
313
314
101
    QualType Ty = Arg.get()->getType();
315
101
    const auto *PtrTy = Ty->getAs<PointerType>();
316
101
    if (!PtrTy ||
317
100
        !PtrTy->getPointeeType()->isIntegerType() ||
318
99
        PtrTy->getPointeeType().isConstQualified()) {
319
3
      S.Diag(Arg.get()->getBeginLoc(),
320
3
             diag::err_overflow_builtin_must_be_ptr_int)
321
3
        << Ty << Arg.get()->getSourceRange();
322
3
      return true;
323
3
    }
324
98
  }
325
326
  // Disallow signed ExtIntType args larger than 128 bits to mul function until
327
  // we improve backend support.
328
98
  if (BuiltinID == Builtin::BI__builtin_mul_overflow) {
329
205
    for (unsigned I = 0; I < 3; 
++I153
) {
330
154
      const auto Arg = TheCall->getArg(I);
331
      // Third argument will be a pointer.
332
103
      auto Ty = I < 2 ? Arg->getType() : 
Arg->getType()->getPointeeType()51
;
333
154
      if (Ty->isExtIntType() && 
Ty->isSignedIntegerType()34
&&
334
31
          S.getASTContext().getIntWidth(Ty) > 128)
335
1
        return S.Diag(Arg->getBeginLoc(),
336
1
                      diag::err_overflow_builtin_ext_int_max_size)
337
1
               << 128;
338
154
    }
339
52
  }
340
341
97
  return false;
342
98
}
343
344
16
static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
345
16
  if (checkArgCount(S, BuiltinCall, 2))
346
0
    return true;
347
348
16
  SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
349
16
  Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
350
16
  Expr *Call = BuiltinCall->getArg(0);
351
16
  Expr *Chain = BuiltinCall->getArg(1);
352
353
16
  if (Call->getStmtClass() != Stmt::CallExprClass) {
354
2
    S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
355
2
        << Call->getSourceRange();
356
2
    return true;
357
2
  }
358
359
14
  auto CE = cast<CallExpr>(Call);
360
14
  if (CE->getCallee()->getType()->isBlockPointerType()) {
361
1
    S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
362
1
        << Call->getSourceRange();
363
1
    return true;
364
1
  }
365
366
13
  const Decl *TargetDecl = CE->getCalleeDecl();
367
13
  if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
368
12
    if (FD->getBuiltinID()) {
369
1
      S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
370
1
          << Call->getSourceRange();
371
1
      return true;
372
1
    }
373
374
12
  if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
375
1
    S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
376
1
        << Call->getSourceRange();
377
1
    return true;
378
1
  }
379
380
11
  ExprResult ChainResult = S.UsualUnaryConversions(Chain);
381
11
  if (ChainResult.isInvalid())
382
0
    return true;
383
11
  if (!ChainResult.get()->getType()->isPointerType()) {
384
1
    S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
385
1
        << Chain->getSourceRange();
386
1
    return true;
387
1
  }
388
389
10
  QualType ReturnTy = CE->getCallReturnType(S.Context);
390
10
  QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
391
10
  QualType BuiltinTy = S.Context.getFunctionType(
392
10
      ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
393
10
  QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
394
395
10
  Builtin =
396
10
      S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
397
398
10
  BuiltinCall->setType(CE->getType());
399
10
  BuiltinCall->setValueKind(CE->getValueKind());
400
10
  BuiltinCall->setObjectKind(CE->getObjectKind());
401
10
  BuiltinCall->setCallee(Builtin);
402
10
  BuiltinCall->setArg(1, ChainResult.get());
403
404
10
  return false;
405
10
}
406
407
namespace {
408
409
class EstimateSizeFormatHandler
410
    : public analyze_format_string::FormatStringHandler {
411
  size_t Size;
412
413
public:
414
  EstimateSizeFormatHandler(StringRef Format)
415
      : Size(std::min(Format.find(0), Format.size()) +
416
329
             1 /* null byte always written by sprintf */) {}
417
418
  bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
419
290
                             const char *, unsigned SpecifierLen) override {
420
421
290
    const size_t FieldWidth = computeFieldWidth(FS);
422
290
    const size_t Precision = computePrecision(FS);
423
424
    // The actual format.
425
290
    switch (FS.getConversionSpecifier().getKind()) {
426
    // Just a char.
427
16
    case analyze_format_string::ConversionSpecifier::cArg:
428
16
    case analyze_format_string::ConversionSpecifier::CArg:
429
16
      Size += std::max(FieldWidth, (size_t)1);
430
16
      break;
431
    // Just an integer.
432
171
    case analyze_format_string::ConversionSpecifier::dArg:
433
171
    case analyze_format_string::ConversionSpecifier::DArg:
434
171
    case analyze_format_string::ConversionSpecifier::iArg:
435
171
    case analyze_format_string::ConversionSpecifier::oArg:
436
171
    case analyze_format_string::ConversionSpecifier::OArg:
437
171
    case analyze_format_string::ConversionSpecifier::uArg:
438
171
    case analyze_format_string::ConversionSpecifier::UArg:
439
171
    case analyze_format_string::ConversionSpecifier::xArg:
440
171
    case analyze_format_string::ConversionSpecifier::XArg:
441
171
      Size += std::max(FieldWidth, Precision);
442
171
      break;
443
444
    // %g style conversion switches between %f or %e style dynamically.
445
    // %f always takes less space, so default to it.
446
40
    case analyze_format_string::ConversionSpecifier::gArg:
447
40
    case analyze_format_string::ConversionSpecifier::GArg:
448
449
    // Floating point number in the form '[+]ddd.ddd'.
450
40
    case analyze_format_string::ConversionSpecifier::fArg:
451
40
    case analyze_format_string::ConversionSpecifier::FArg:
452
40
      Size += std::max(FieldWidth, 1 /* integer part */ +
453
40
                                       (Precision ? 1 + Precision
454
0
                                                  : 0) /* period + decimal */);
455
40
      break;
456
457
    // Floating point number in the form '[-]d.ddde[+-]dd'.
458
16
    case analyze_format_string::ConversionSpecifier::eArg:
459
16
    case analyze_format_string::ConversionSpecifier::EArg:
460
16
      Size +=
461
16
          std::max(FieldWidth,
462
16
                   1 /* integer part */ +
463
12
                       (Precision ? 1 + Precision : 
04
) /* period + decimal */ +
464
16
                       1 /* e or E letter */ + 2 /* exponent */);
465
16
      break;
466
467
    // Floating point number in the form '[-]0xh.hhhhp±dd'.
468
0
    case analyze_format_string::ConversionSpecifier::aArg:
469
0
    case analyze_format_string::ConversionSpecifier::AArg:
470
0
      Size +=
471
0
          std::max(FieldWidth,
472
0
                   2 /* 0x */ + 1 /* integer part */ +
473
0
                       (Precision ? 1 + Precision : 0) /* period + decimal */ +
474
0
                       1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
475
0
      break;
476
477
    // Just a string.
478
11
    case analyze_format_string::ConversionSpecifier::sArg:
479
11
    case analyze_format_string::ConversionSpecifier::SArg:
480
11
      Size += FieldWidth;
481
11
      break;
482
483
    // Just a pointer in the form '0xddd'.
484
16
    case analyze_format_string::ConversionSpecifier::pArg:
485
16
      Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision);
486
16
      break;
487
488
    // A plain percent.
489
20
    case analyze_format_string::ConversionSpecifier::PercentArg:
490
20
      Size += 1;
491
20
      break;
492
493
0
    default:
494
0
      break;
495
290
    }
496
497
290
    Size += FS.hasPlusPrefix() || 
FS.hasSpacePrefix()258
;
498
499
290
    if (FS.hasAlternativeForm()) {
500
16
      switch (FS.getConversionSpecifier().getKind()) {
501
0
      default:
502
0
        break;
503
      // Force a leading '0'.
504
0
      case analyze_format_string::ConversionSpecifier::oArg:
505
0
        Size += 1;
506
0
        break;
507
      // Force a leading '0x'.
508
16
      case analyze_format_string::ConversionSpecifier::xArg:
509
16
      case analyze_format_string::ConversionSpecifier::XArg:
510
16
        Size += 2;
511
16
        break;
512
      // Force a period '.' before decimal, even if precision is 0.
513
0
      case analyze_format_string::ConversionSpecifier::aArg:
514
0
      case analyze_format_string::ConversionSpecifier::AArg:
515
0
      case analyze_format_string::ConversionSpecifier::eArg:
516
0
      case analyze_format_string::ConversionSpecifier::EArg:
517
0
      case analyze_format_string::ConversionSpecifier::fArg:
518
0
      case analyze_format_string::ConversionSpecifier::FArg:
519
0
      case analyze_format_string::ConversionSpecifier::gArg:
520
0
      case analyze_format_string::ConversionSpecifier::GArg:
521
0
        Size += (Precision ? 0 : 1);
522
0
        break;
523
290
      }
524
290
    }
525
290
    assert(SpecifierLen <= Size && "no underflow");
526
290
    Size -= SpecifierLen;
527
290
    return true;
528
290
  }
529
530
329
  size_t getSizeLowerBound() const { return Size; }
531
532
private:
533
290
  static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
534
290
    const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
535
290
    size_t FieldWidth = 0;
536
290
    if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant)
537
18
      FieldWidth = FW.getConstantAmount();
538
290
    return FieldWidth;
539
290
  }
540
541
290
  static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
542
290
    const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
543
290
    size_t Precision = 0;
544
545
    // See man 3 printf for default precision value based on the specifier.
546
290
    switch (FW.getHowSpecified()) {
547
266
    case analyze_format_string::OptionalAmount::NotSpecified:
548
266
      switch (FS.getConversionSpecifier().getKind()) {
549
47
      default:
550
47
        break;
551
122
      case analyze_format_string::ConversionSpecifier::dArg: // %d
552
122
      case analyze_format_string::ConversionSpecifier::DArg: // %D
553
122
      case analyze_format_string::ConversionSpecifier::iArg: // %i
554
122
        Precision = 1;
555
122
        break;
556
49
      case analyze_format_string::ConversionSpecifier::oArg: // %d
557
49
      case analyze_format_string::ConversionSpecifier::OArg: // %D
558
49
      case analyze_format_string::ConversionSpecifier::uArg: // %d
559
49
      case analyze_format_string::ConversionSpecifier::UArg: // %D
560
49
      case analyze_format_string::ConversionSpecifier::xArg: // %d
561
49
      case analyze_format_string::ConversionSpecifier::XArg: // %D
562
49
        Precision = 1;
563
49
        break;
564
32
      case analyze_format_string::ConversionSpecifier::fArg: // %f
565
32
      case analyze_format_string::ConversionSpecifier::FArg: // %F
566
32
      case analyze_format_string::ConversionSpecifier::eArg: // %e
567
32
      case analyze_format_string::ConversionSpecifier::EArg: // %E
568
32
      case analyze_format_string::ConversionSpecifier::gArg: // %g
569
32
      case analyze_format_string::ConversionSpecifier::GArg: // %G
570
32
        Precision = 6;
571
32
        break;
572
16
      case analyze_format_string::ConversionSpecifier::pArg: // %d
573
16
        Precision = 1;
574
16
        break;
575
266
      }
576
266
      break;
577
24
    case analyze_format_string::OptionalAmount::Constant:
578
24
      Precision = FW.getConstantAmount();
579
24
      break;
580
0
    default:
581
0
      break;
582
290
    }
583
290
    return Precision;
584
290
  }
585
};
586
587
} // namespace
588
589
/// Check a call to BuiltinID for buffer overflows. If BuiltinID is a
590
/// __builtin_*_chk function, then use the object size argument specified in the
591
/// source. Otherwise, infer the object size using __builtin_object_size.
592
void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
593
2.86M
                                               CallExpr *TheCall) {
594
  // FIXME: There are some more useful checks we could be doing here:
595
  //  - Evaluate strlen of strcpy arguments, use as object size.
596
597
2.86M
  if (TheCall->isValueDependent() || 
TheCall->isTypeDependent()2.84M
||
598
2.84M
      isConstantEvaluated())
599
43.2k
    return;
600
601
2.82M
  unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true);
602
2.82M
  if (!BuiltinID)
603
1.41M
    return;
604
605
1.40M
  const TargetInfo &TI = getASTContext().getTargetInfo();
606
1.40M
  unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
607
608
1.40M
  unsigned DiagID = 0;
609
1.40M
  bool IsChkVariant = false;
610
1.40M
  Optional<llvm::APSInt> UsedSize;
611
1.40M
  unsigned SizeIndex, ObjectIndex;
612
1.40M
  switch (BuiltinID) {
613
1.40M
  default:
614
1.40M
    return;
615
346
  case Builtin::BIsprintf:
616
346
  case Builtin::BI__builtin___sprintf_chk: {
617
197
    size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 
1149
: 3;
618
346
    auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
619
620
346
    if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) {
621
622
329
      if (!Format->isAscii() && 
!Format->isUTF8()0
)
623
0
        return;
624
625
329
      StringRef FormatStrRef = Format->getString();
626
329
      EstimateSizeFormatHandler H(FormatStrRef);
627
329
      const char *FormatBytes = FormatStrRef.data();
628
329
      const ConstantArrayType *T =
629
329
          Context.getAsConstantArrayType(Format->getType());
630
329
      assert(T && "String literal not of constant array type!");
631
329
      size_t TypeSize = T->getSize().getZExtValue();
632
633
      // In case there's a null byte somewhere.
634
329
      size_t StrLen =
635
329
          std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
636
329
      if (!analyze_format_string::ParsePrintfString(
637
329
              H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
638
329
              Context.getTargetInfo(), false)) {
639
329
        DiagID = diag::warn_fortify_source_format_overflow;
640
329
        UsedSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound())
641
329
                       .extOrTrunc(SizeTypeWidth);
642
329
        if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
643
195
          IsChkVariant = true;
644
195
          ObjectIndex = 2;
645
134
        } else {
646
134
          IsChkVariant = false;
647
134
          ObjectIndex = 0;
648
134
        }
649
329
        break;
650
329
      }
651
17
    }
652
17
    return;
653
17
  }
654
156
  case Builtin::BI__builtin___memcpy_chk:
655
156
  case Builtin::BI__builtin___memmove_chk:
656
156
  case Builtin::BI__builtin___memset_chk:
657
156
  case Builtin::BI__builtin___strlcat_chk:
658
156
  case Builtin::BI__builtin___strlcpy_chk:
659
156
  case Builtin::BI__builtin___strncat_chk:
660
156
  case Builtin::BI__builtin___strncpy_chk:
661
156
  case Builtin::BI__builtin___stpncpy_chk:
662
156
  case Builtin::BI__builtin___memccpy_chk:
663
156
  case Builtin::BI__builtin___mempcpy_chk: {
664
156
    DiagID = diag::warn_builtin_chk_overflow;
665
156
    IsChkVariant = true;
666
156
    SizeIndex = TheCall->getNumArgs() - 2;
667
156
    ObjectIndex = TheCall->getNumArgs() - 1;
668
156
    break;
669
156
  }
670
671
11
  case Builtin::BI__builtin___snprintf_chk:
672
11
  case Builtin::BI__builtin___vsnprintf_chk: {
673
11
    DiagID = diag::warn_builtin_chk_overflow;
674
11
    IsChkVariant = true;
675
11
    SizeIndex = 1;
676
11
    ObjectIndex = 3;
677
11
    break;
678
11
  }
679
680
226
  case Builtin::BIstrncat:
681
226
  case Builtin::BI__builtin_strncat:
682
226
  case Builtin::BIstrncpy:
683
226
  case Builtin::BI__builtin_strncpy:
684
226
  case Builtin::BIstpncpy:
685
226
  case Builtin::BI__builtin_stpncpy: {
686
    // Whether these functions overflow depends on the runtime strlen of the
687
    // string, not just the buffer size, so emitting the "always overflow"
688
    // diagnostic isn't quite right. We should still diagnose passing a buffer
689
    // size larger than the destination buffer though; this is a runtime abort
690
    // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
691
226
    DiagID = diag::warn_fortify_source_size_mismatch;
692
226
    SizeIndex = TheCall->getNumArgs() - 1;
693
226
    ObjectIndex = 0;
694
226
    break;
695
226
  }
696
697
826
  case Builtin::BImemcpy:
698
826
  case Builtin::BI__builtin_memcpy:
699
826
  case Builtin::BImemmove:
700
826
  case Builtin::BI__builtin_memmove:
701
826
  case Builtin::BImemset:
702
826
  case Builtin::BI__builtin_memset:
703
826
  case Builtin::BImempcpy:
704
826
  case Builtin::BI__builtin_mempcpy: {
705
826
    DiagID = diag::warn_fortify_source_overflow;
706
826
    SizeIndex = TheCall->getNumArgs() - 1;
707
826
    ObjectIndex = 0;
708
826
    break;
709
826
  }
710
65
  case Builtin::BIsnprintf:
711
65
  case Builtin::BI__builtin_snprintf:
712
65
  case Builtin::BIvsnprintf:
713
65
  case Builtin::BI__builtin_vsnprintf: {
714
65
    DiagID = diag::warn_fortify_source_size_mismatch;
715
65
    SizeIndex = 1;
716
65
    ObjectIndex = 0;
717
65
    break;
718
1.61k
  }
719
1.61k
  }
720
721
1.61k
  llvm::APSInt ObjectSize;
722
  // For __builtin___*_chk, the object size is explicitly provided by the caller
723
  // (usually using __builtin_object_size). Use that value to check this call.
724
1.61k
  if (IsChkVariant) {
725
362
    Expr::EvalResult Result;
726
362
    Expr *SizeArg = TheCall->getArg(ObjectIndex);
727
362
    if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
728
31
      return;
729
331
    ObjectSize = Result.Val.getInt();
730
731
  // Otherwise, try to evaluate an imaginary call to __builtin_object_size.
732
1.25k
  } else {
733
    // If the parameter has a pass_object_size attribute, then we should use its
734
    // (potentially) more strict checking mode. Otherwise, conservatively assume
735
    // type 0.
736
1.25k
    int BOSType = 0;
737
1.25k
    if (const auto *POS =
738
0
            FD->getParamDecl(ObjectIndex)->getAttr<PassObjectSizeAttr>())
739
0
      BOSType = POS->getType();
740
741
1.25k
    Expr *ObjArg = TheCall->getArg(ObjectIndex);
742
1.25k
    uint64_t Result;
743
1.25k
    if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
744
507
      return;
745
    // Get the object size in the target's size_t width.
746
744
    ObjectSize = llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
747
744
  }
748
749
  // Evaluate the number of bytes of the object that this call will use.
750
1.07k
  if (!UsedSize) {
751
753
    Expr::EvalResult Result;
752
753
    Expr *UsedSizeArg = TheCall->getArg(SizeIndex);
753
753
    if (!UsedSizeArg->EvaluateAsInt(Result, getASTContext()))
754
107
      return;
755
646
    UsedSize = Result.Val.getInt().extOrTrunc(SizeTypeWidth);
756
646
  }
757
758
968
  if (UsedSize.getValue().ule(ObjectSize))
759
734
    return;
760
761
234
  StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
762
  // Skim off the details of whichever builtin was called to produce a better
763
  // diagnostic, as it's unlikley that the user wrote the __builtin explicitly.
764
234
  if (IsChkVariant) {
765
108
    FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
766
108
    FunctionName = FunctionName.drop_back(std::strlen("_chk"));
767
126
  } else if (FunctionName.startswith("__builtin_")) {
768
46
    FunctionName = FunctionName.drop_front(std::strlen("__builtin_"));
769
46
  }
770
771
234
  DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
772
234
                      PDiag(DiagID)
773
234
                          << FunctionName << ObjectSize.toString(/*Radix=*/10)
774
234
                          << UsedSize.getValue().toString(/*Radix=*/10));
775
234
}
776
777
static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
778
                                     Scope::ScopeFlags NeededScopeFlags,
779
39
                                     unsigned DiagID) {
780
  // Scopes aren't available during instantiation. Fortunately, builtin
781
  // functions cannot be template args so they cannot be formed through template
782
  // instantiation. Therefore checking once during the parse is sufficient.
783
39
  if (SemaRef.inTemplateInstantiation())
784
0
    return false;
785
786
39
  Scope *S = SemaRef.getCurScope();
787
74
  while (S && 
!S->isSEHExceptScope()62
)
788
35
    S = S->getParent();
789
39
  if (!S || 
!(S->getFlags() & NeededScopeFlags)27
) {
790
13
    auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
791
13
    SemaRef.Diag(TheCall->getExprLoc(), DiagID)
792
13
        << DRE->getDecl()->getIdentifier();
793
13
    return true;
794
13
  }
795
796
26
  return false;
797
26
}
798
799
292
static inline bool isBlockPointer(Expr *Arg) {
800
292
  return Arg->getType()->isBlockPointerType();
801
292
}
802
803
/// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
804
/// void*, which is a requirement of device side enqueue.
805
191
static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
806
191
  const BlockPointerType *BPT =
807
191
      cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
808
191
  ArrayRef<QualType> Params =
809
191
      BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes();
810
191
  unsigned ArgCounter = 0;
811
191
  bool IllegalParams = false;
812
  // Iterate through the block parameters until either one is found that is not
813
  // a local void*, or the block is valid.
814
191
  for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
815
380
       I != E; 
++I, ++ArgCounter189
) {
816
189
    if (!(*I)->isPointerType() || 
!(*I)->getPointeeType()->isVoidType()173
||
817
153
        (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
818
36
            LangAS::opencl_local) {
819
      // Get the location of the error. If a block literal has been passed
820
      // (BlockExpr) then we can point straight to the offending argument,
821
      // else we just point to the variable reference.
822
36
      SourceLocation ErrorLoc;
823
36
      if (isa<BlockExpr>(BlockArg)) {
824
16
        BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
825
16
        ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
826
20
      } else if (isa<DeclRefExpr>(BlockArg)) {
827
20
        ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
828
20
      }
829
36
      S.Diag(ErrorLoc,
830
36
             diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
831
36
      IllegalParams = true;
832
36
    }
833
189
  }
834
835
191
  return IllegalParams;
836
191
}
837
838
46
static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
839
46
  if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
840
8
    S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
841
8
        << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
842
8
    return true;
843
8
  }
844
38
  return false;
845
38
}
846
847
38
static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
848
38
  if (checkArgCount(S, TheCall, 2))
849
0
    return true;
850
851
38
  if (checkOpenCLSubgroupExt(S, TheCall))
852
8
    return true;
853
854
  // First argument is an ndrange_t type.
855
30
  Expr *NDRangeArg = TheCall->getArg(0);
856
30
  if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
857
8
    S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
858
8
        << TheCall->getDirectCallee() << "'ndrange_t'";
859
8
    return true;
860
8
  }
861
862
22
  Expr *BlockArg = TheCall->getArg(1);
863
22
  if (!isBlockPointer(BlockArg)) {
864
8
    S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
865
8
        << TheCall->getDirectCallee() << "block";
866
8
    return true;
867
8
  }
868
14
  return checkOpenCLBlockArgs(S, BlockArg);
869
14
}
870
871
/// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
872
/// get_kernel_work_group_size
873
/// and get_kernel_preferred_work_group_size_multiple builtin functions.
874
97
static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
875
97
  if (checkArgCount(S, TheCall, 1))
876
16
    return true;
877
878
81
  Expr *BlockArg = TheCall->getArg(0);
879
81
  if (!isBlockPointer(BlockArg)) {
880
8
    S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
881
8
        << TheCall->getDirectCallee() << "block";
882
8
    return true;
883
8
  }
884
73
  return checkOpenCLBlockArgs(S, BlockArg);
885
73
}
886
887
/// Diagnose integer type and any valid implicit conversion to it.
888
static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
889
                                      const QualType &IntType);
890
891
static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
892
66
                                            unsigned Start, unsigned End) {
893
66
  bool IllegalParams = false;
894
174
  for (unsigned I = Start; I <= End; 
++I108
)
895
108
    IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
896
108
                                              S.Context.getSizeType());
897
66
  return IllegalParams;
898
66
}
899
900
/// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
901
/// 'local void*' parameter of passed block.
902
static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
903
                                           Expr *BlockArg,
904
74
                                           unsigned NumNonVarArgs) {
905
74
  const BlockPointerType *BPT =
906
74
      cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
907
74
  unsigned NumBlockParams =
908
74
      BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams();
909
74
  unsigned TotalNumArgs = TheCall->getNumArgs();
910
911
  // For each argument passed to the block, a corresponding uint needs to
912
  // be passed to describe the size of the local memory.
913
74
  if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
914
8
    S.Diag(TheCall->getBeginLoc(),
915
8
           diag::err_opencl_enqueue_kernel_local_size_args);
916
8
    return true;
917
8
  }
918
919
  // Check that the sizes of the local memory are specified by integers.
920
66
  return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
921
66
                                         TotalNumArgs - 1);
922
66
}
923
924
/// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
925
/// overload formats specified in Table 6.13.17.1.
926
/// int enqueue_kernel(queue_t queue,
927
///                    kernel_enqueue_flags_t flags,
928
///                    const ndrange_t ndrange,
929
///                    void (^block)(void))
930
/// int enqueue_kernel(queue_t queue,
931
///                    kernel_enqueue_flags_t flags,
932
///                    const ndrange_t ndrange,
933
///                    uint num_events_in_wait_list,
934
///                    clk_event_t *event_wait_list,
935
///                    clk_event_t *event_ret,
936
///                    void (^block)(void))
937
/// int enqueue_kernel(queue_t queue,
938
///                    kernel_enqueue_flags_t flags,
939
///                    const ndrange_t ndrange,
940
///                    void (^block)(local void*, ...),
941
///                    uint size0, ...)
942
/// int enqueue_kernel(queue_t queue,
943
///                    kernel_enqueue_flags_t flags,
944
///                    const ndrange_t ndrange,
945
///                    uint num_events_in_wait_list,
946
///                    clk_event_t *event_wait_list,
947
///                    clk_event_t *event_ret,
948
///                    void (^block)(local void*, ...),
949
///                    uint size0, ...)
950
157
static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
951
157
  unsigned NumArgs = TheCall->getNumArgs();
952
953
157
  if (NumArgs < 4) {
954
4
    S.Diag(TheCall->getBeginLoc(),
955
4
           diag::err_typecheck_call_too_few_args_at_least)
956
4
        << 0 << 4 << NumArgs;
957
4
    return true;
958
4
  }
959
960
153
  Expr *Arg0 = TheCall->getArg(0);
961
153
  Expr *Arg1 = TheCall->getArg(1);
962
153
  Expr *Arg2 = TheCall->getArg(2);
963
153
  Expr *Arg3 = TheCall->getArg(3);
964
965
  // First argument always needs to be a queue_t type.
966
153
  if (!Arg0->getType()->isQueueT()) {
967
4
    S.Diag(TheCall->getArg(0)->getBeginLoc(),
968
4
           diag::err_opencl_builtin_expected_type)
969
4
        << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
970
4
    return true;
971
4
  }
972
973
  // Second argument always needs to be a kernel_enqueue_flags_t enum value.
974
149
  if (!Arg1->getType()->isIntegerType()) {
975
4
    S.Diag(TheCall->getArg(1)->getBeginLoc(),
976
4
           diag::err_opencl_builtin_expected_type)
977
4
        << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
978
4
    return true;
979
4
  }
980
981
  // Third argument is always an ndrange_t type.
982
145
  if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
983
4
    S.Diag(TheCall->getArg(2)->getBeginLoc(),
984
4
           diag::err_opencl_builtin_expected_type)
985
4
        << TheCall->getDirectCallee() << "'ndrange_t'";
986
4
    return true;
987
4
  }
988
989
  // With four arguments, there is only one form that the function could be
990
  // called in: no events and no variable arguments.
991
141
  if (NumArgs == 4) {
992
    // check that the last argument is the right block type.
993
25
    if (!isBlockPointer(Arg3)) {
994
4
      S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
995
4
          << TheCall->getDirectCallee() << "block";
996
4
      return true;
997
4
    }
998
    // we have a block type, check the prototype
999
21
    const BlockPointerType *BPT =
1000
21
        cast<BlockPointerType>(Arg3->getType().getCanonicalType());
1001
21
    if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) {
1002
4
      S.Diag(Arg3->getBeginLoc(),
1003
4
             diag::err_opencl_enqueue_kernel_blocks_no_args);
1004
4
      return true;
1005
4
    }
1006
17
    return false;
1007
17
  }
1008
  // we can have block + varargs.
1009
116
  if (isBlockPointer(Arg3))
1010
60
    return (checkOpenCLBlockArgs(S, Arg3) ||
1011
56
            checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
1012
  // last two cases with either exactly 7 args or 7 args and varargs.
1013
56
  if (NumArgs >= 7) {
1014
    // check common block argument.
1015
48
    Expr *Arg6 = TheCall->getArg(6);
1016
48
    if (!isBlockPointer(Arg6)) {
1017
4
      S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1018
4
          << TheCall->getDirectCallee() << "block";
1019
4
      return true;
1020
4
    }
1021
44
    if (checkOpenCLBlockArgs(S, Arg6))
1022
0
      return true;
1023
1024
    // Forth argument has to be any integer type.
1025
44
    if (!Arg3->getType()->isIntegerType()) {
1026
4
      S.Diag(TheCall->getArg(3)->getBeginLoc(),
1027
4
             diag::err_opencl_builtin_expected_type)
1028
4
          << TheCall->getDirectCallee() << "integer";
1029
4
      return true;
1030
4
    }
1031
    // check remaining common arguments.
1032
40
    Expr *Arg4 = TheCall->getArg(4);
1033
40
    Expr *Arg5 = TheCall->getArg(5);
1034
1035
    // Fifth argument is always passed as a pointer to clk_event_t.
1036
40
    if (!Arg4->isNullPointerConstant(S.Context,
1037
40
                                     Expr::NPC_ValueDependentIsNotNull) &&
1038
29
        !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
1039
4
      S.Diag(TheCall->getArg(4)->getBeginLoc(),
1040
4
             diag::err_opencl_builtin_expected_type)
1041
4
          << TheCall->getDirectCallee()
1042
4
          << S.Context.getPointerType(S.Context.OCLClkEventTy);
1043
4
      return true;
1044
4
    }
1045
1046
    // Sixth argument is always passed as a pointer to clk_event_t.
1047
36
    if (!Arg5->isNullPointerConstant(S.Context,
1048
36
                                     Expr::NPC_ValueDependentIsNotNull) &&
1049
25
        !(Arg5->getType()->isPointerType() &&
1050
25
          Arg5->getType()->getPointeeType()->isClkEventT())) {
1051
4
      S.Diag(TheCall->getArg(5)->getBeginLoc(),
1052
4
             diag::err_opencl_builtin_expected_type)
1053
4
          << TheCall->getDirectCallee()
1054
4
          << S.Context.getPointerType(S.Context.OCLClkEventTy);
1055
4
      return true;
1056
4
    }
1057
1058
32
    if (NumArgs == 7)
1059
14
      return false;
1060
1061
18
    return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
1062
18
  }
1063
1064
  // None of the specific case has been detected, give generic error
1065
8
  S.Diag(TheCall->getBeginLoc(),
1066
8
         diag::err_opencl_enqueue_kernel_incorrect_args);
1067
8
  return true;
1068
8
}
1069
1070
/// Returns OpenCL access qual.
1071
50
static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
1072
50
    return D->getAttr<OpenCLAccessAttr>();
1073
50
}
1074
1075
/// Returns true if pipe element type is different from the pointer.
1076
56
static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
1077
56
  const Expr *Arg0 = Call->getArg(0);
1078
  // First argument type should always be pipe.
1079
56
  if (!Arg0->getType()->isPipeType()) {
1080
6
    S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1081
6
        << Call->getDirectCallee() << Arg0->getSourceRange();
1082
6
    return true;
1083
6
  }
1084
50
  OpenCLAccessAttr *AccessQual =
1085
50
      getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
1086
  // Validates the access qualifier is compatible with the call.
1087
  // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
1088
  // read_only and write_only, and assumed to be read_only if no qualifier is
1089
  // specified.
1090
50
  switch (Call->getDirectCallee()->getBuiltinID()) {
1091
27
  case Builtin::BIread_pipe:
1092
27
  case Builtin::BIreserve_read_pipe:
1093
27
  case Builtin::BIcommit_read_pipe:
1094
27
  case Builtin::BIwork_group_reserve_read_pipe:
1095
27
  case Builtin::BIsub_group_reserve_read_pipe:
1096
27
  case Builtin::BIwork_group_commit_read_pipe:
1097
27
  case Builtin::BIsub_group_commit_read_pipe:
1098
27
    if (!(!AccessQual || AccessQual->isReadOnly())) {
1099
4
      S.Diag(Arg0->getBeginLoc(),
1100
4
             diag::err_opencl_builtin_pipe_invalid_access_modifier)
1101
4
          << "read_only" << Arg0->getSourceRange();
1102
4
      return true;
1103
4
    }
1104
23
    break;
1105
23
  case Builtin::BIwrite_pipe:
1106
23
  case Builtin::BIreserve_write_pipe:
1107
23
  case Builtin::BIcommit_write_pipe:
1108
23
  case Builtin::BIwork_group_reserve_write_pipe:
1109
23
  case Builtin::BIsub_group_reserve_write_pipe:
1110
23
  case Builtin::BIwork_group_commit_write_pipe:
1111
23
  case Builtin::BIsub_group_commit_write_pipe:
1112
23
    if (!(AccessQual && AccessQual->isWriteOnly())) {
1113
4
      S.Diag(Arg0->getBeginLoc(),
1114
4
             diag::err_opencl_builtin_pipe_invalid_access_modifier)
1115
4
          << "write_only" << Arg0->getSourceRange();
1116
4
      return true;
1117
4
    }
1118
19
    break;
1119
0
  default:
1120
0
    break;
1121
42
  }
1122
42
  return false;
1123
42
}
1124
1125
/// Returns true if pipe element type is different from the pointer.
1126
16
static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
1127
16
  const Expr *Arg0 = Call->getArg(0);
1128
16
  const Expr *ArgIdx = Call->getArg(Idx);
1129
16
  const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
1130
16
  const QualType EltTy = PipeTy->getElementType();
1131
16
  const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
1132
  // The Idx argument should be a pointer and the type of the pointer and
1133
  // the type of pipe element should also be the same.
1134
16
  if (!ArgTy ||
1135
14
      !S.Context.hasSameType(
1136
2
          EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
1137
2
    S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1138
2
        << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
1139
2
        << ArgIdx->getType() << ArgIdx->getSourceRange();
1140
2
    return true;
1141
2
  }
1142
14
  return false;
1143
14
}
1144
1145
// Performs semantic analysis for the read/write_pipe call.
1146
// \param S Reference to the semantic analyzer.
1147
// \param Call A pointer to the builtin call.
1148
// \return True if a semantic error has been found, false otherwise.
1149
28
static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
1150
  // OpenCL v2.0 s6.13.16.2 - The built-in read/write
1151
  // functions have two forms.
1152
28
  switch (Call->getNumArgs()) {
1153
16
  case 2:
1154
16
    if (checkOpenCLPipeArg(S, Call))
1155
4
      return true;
1156
    // The call with 2 arguments should be
1157
    // read/write_pipe(pipe T, T*).
1158
    // Check packet type T.
1159
12
    if (checkOpenCLPipePacketType(S, Call, 1))
1160
2
      return true;
1161
10
    break;
1162
1163
10
  case 4: {
1164
10
    if (checkOpenCLPipeArg(S, Call))
1165
2
      return true;
1166
    // The call with 4 arguments should be
1167
    // read/write_pipe(pipe T, reserve_id_t, uint, T*).
1168
    // Check reserve_id_t.
1169
8
    if (!Call->getArg(1)->getType()->isReserveIDT()) {
1170
2
      S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1171
2
          << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1172
2
          << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1173
2
      return true;
1174
2
    }
1175
1176
    // Check the index.
1177
6
    const Expr *Arg2 = Call->getArg(2);
1178
6
    if (!Arg2->getType()->isIntegerType() &&
1179
2
        !Arg2->getType()->isUnsignedIntegerType()) {
1180
2
      S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1181
2
          << Call->getDirectCallee() << S.Context.UnsignedIntTy
1182
2
          << Arg2->getType() << Arg2->getSourceRange();
1183
2
      return true;
1184
2
    }
1185
1186
    // Check packet type T.
1187
4
    if (checkOpenCLPipePacketType(S, Call, 3))
1188
0
      return true;
1189
4
  } break;
1190
2
  default:
1191
2
    S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
1192
2
        << Call->getDirectCallee() << Call->getSourceRange();
1193
2
    return true;
1194
14
  }
1195
1196
14
  return false;
1197
14
}
1198
1199
// Performs a semantic analysis on the {work_group_/sub_group_
1200
//        /_}reserve_{read/write}_pipe
1201
// \param S Reference to the semantic analyzer.
1202
// \param Call The call to the builtin function to be analyzed.
1203
// \return True if a semantic error was found, false otherwise.
1204
16
static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
1205
16
  if (checkArgCount(S, Call, 2))
1206
0
    return true;
1207
1208
16
  if (checkOpenCLPipeArg(S, Call))
1209
4
    return true;
1210
1211
  // Check the reserve size.
1212
12
  if (!Call->getArg(1)->getType()->isIntegerType() &&
1213
2
      !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
1214
2
    S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1215
2
        << Call->getDirectCallee() << S.Context.UnsignedIntTy
1216
2
        << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1217
2
    return true;
1218
2
  }
1219
1220
  // Since return type of reserve_read/write_pipe built-in function is
1221
  // reserve_id_t, which is not defined in the builtin def file , we used int
1222
  // as return type and need to override the return type of these functions.
1223
10
  Call->setType(S.Context.OCLReserveIDTy);
1224
1225
10
  return false;
1226
10
}
1227
1228
// Performs a semantic analysis on {work_group_/sub_group_
1229
//        /_}commit_{read/write}_pipe
1230
// \param S Reference to the semantic analyzer.
1231
// \param Call The call to the builtin function to be analyzed.
1232
// \return True if a semantic error was found, false otherwise.
1233
14
static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
1234
14
  if (checkArgCount(S, Call, 2))
1235
0
    return true;
1236
1237
14
  if (checkOpenCLPipeArg(S, Call))
1238
4
    return true;
1239
1240
  // Check reserve_id_t.
1241
10
  if (!Call->getArg(1)->getType()->isReserveIDT()) {
1242
2
    S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1243
2
        << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1244
2
        << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1245
2
    return true;
1246
2
  }
1247
1248
8
  return false;
1249
8
}
1250
1251
// Performs a semantic analysis on the call to built-in Pipe
1252
//        Query Functions.
1253
// \param S Reference to the semantic analyzer.
1254
// \param Call The call to the builtin function to be analyzed.
1255
// \return True if a semantic error was found, false otherwise.
1256
10
static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
1257
10
  if (checkArgCount(S, Call, 1))
1258
0
    return true;
1259
1260
10
  if (!Call->getArg(0)->getType()->isPipeType()) {
1261
2
    S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1262
2
        << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
1263
2
    return true;
1264
2
  }
1265
1266
8
  return false;
1267
8
}
1268
1269
// OpenCL v2.0 s6.13.9 - Address space qualifier functions.
1270
// Performs semantic analysis for the to_global/local/private call.
1271
// \param S Reference to the semantic analyzer.
1272
// \param BuiltinID ID of the builtin function.
1273
// \param Call A pointer to the builtin call.
1274
// \return True if a semantic error has been found, false otherwise.
1275
static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
1276
32
                                    CallExpr *Call) {
1277
32
  if (checkArgCount(S, Call, 1))
1278
1
    return true;
1279
1280
31
  auto RT = Call->getArg(0)->getType();
1281
31
  if (!RT->isPointerType() || RT->getPointeeType()
1282
3
      .getAddressSpace() == LangAS::opencl_constant) {
1283
3
    S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
1284
3
        << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
1285
3
    return true;
1286
3
  }
1287
1288
28
  if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
1289
21
    S.Diag(Call->getArg(0)->getBeginLoc(),
1290
21
           diag::warn_opencl_generic_address_space_arg)
1291
21
        << Call->getDirectCallee()->getNameInfo().getAsString()
1292
21
        << Call->getArg(0)->getSourceRange();
1293
21
  }
1294
1295
28
  RT = RT->getPointeeType();
1296
28
  auto Qual = RT.getQualifiers();
1297
28
  switch (BuiltinID) {
1298
12
  case Builtin::BIto_global:
1299
12
    Qual.setAddressSpace(LangAS::opencl_global);
1300
12
    break;
1301
8
  case Builtin::BIto_local:
1302
8
    Qual.setAddressSpace(LangAS::opencl_local);
1303
8
    break;
1304
8
  case Builtin::BIto_private:
1305
8
    Qual.setAddressSpace(LangAS::opencl_private);
1306
8
    break;
1307
0
  default:
1308
0
    llvm_unreachable("Invalid builtin function");
1309
28
  }
1310
28
  Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
1311
28
      RT.getUnqualifiedType(), Qual)));
1312
1313
28
  return false;
1314
28
}
1315
1316
120
static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) {
1317
120
  if (checkArgCount(S, TheCall, 1))
1318
2
    return ExprError();
1319
1320
  // Compute __builtin_launder's parameter type from the argument.
1321
  // The parameter type is:
1322
  //  * The type of the argument if it's not an array or function type,
1323
  //  Otherwise,
1324
  //  * The decayed argument type.
1325
118
  QualType ParamTy = [&]() {
1326
118
    QualType ArgTy = TheCall->getArg(0)->getType();
1327
118
    if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1328
14
      return S.Context.getPointerType(Ty->getElementType());
1329
104
    if (ArgTy->isFunctionType()) {
1330
2
      return S.Context.getPointerType(ArgTy);
1331
2
    }
1332
102
    return ArgTy;
1333
102
  }();
1334
1335
118
  TheCall->setType(ParamTy);
1336
1337
118
  auto DiagSelect = [&]() -> llvm::Optional<unsigned> {
1338
118
    if (!ParamTy->isPointerType())
1339
11
      return 0;
1340
107
    if (ParamTy->isFunctionPointerType())
1341
5
      return 1;
1342
102
    if (ParamTy->isVoidPointerType())
1343
6
      return 2;
1344
96
    return llvm::Optional<unsigned>{};
1345
96
  }();
1346
118
  if (DiagSelect.hasValue()) {
1347
22
    S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1348
22
        << DiagSelect.getValue() << TheCall->getSourceRange();
1349
22
    return ExprError();
1350
22
  }
1351
1352
  // We either have an incomplete class type, or we have a class template
1353
  // whose instantiation has not been forced. Example:
1354
  //
1355
  //   template <class T> struct Foo { T value; };
1356
  //   Foo<int> *p = nullptr;
1357
  //   auto *d = __builtin_launder(p);
1358
96
  if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1359
96
                            diag::err_incomplete_type))
1360
2
    return ExprError();
1361
1362
94
  assert(ParamTy->getPointeeType()->isObjectType() &&
1363
94
         "Unhandled non-object pointer case");
1364
1365
94
  InitializedEntity Entity =
1366
94
      InitializedEntity::InitializeParameter(S.Context, ParamTy, false);
1367
94
  ExprResult Arg =
1368
94
      S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1369
94
  if (Arg.isInvalid())
1370
0
    return ExprError();
1371
94
  TheCall->setArg(0, Arg.get());
1372
1373
94
  return TheCall;
1374
94
}
1375
1376
// Emit an error and return true if the current architecture is not in the list
1377
// of supported architectures.
1378
static bool
1379
CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
1380
90
                          ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
1381
90
  llvm::Triple::ArchType CurArch =
1382
90
      S.getASTContext().getTargetInfo().getTriple().getArch();
1383
90
  if (llvm::is_contained(SupportedArchs, CurArch))
1384
72
    return false;
1385
18
  S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
1386
18
      << TheCall->getSourceRange();
1387
18
  return true;
1388
18
}
1389
1390
static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
1391
                                 SourceLocation CallSiteLoc);
1392
1393
bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
1394
1.35M
                                      CallExpr *TheCall) {
1395
1.35M
  switch (TI.getTriple().getArch()) {
1396
5.41k
  default:
1397
    // Some builtins don't require additional checking, so just consider these
1398
    // acceptable.
1399
5.41k
    return false;
1400
36.5k
  case llvm::Triple::arm:
1401
36.5k
  case llvm::Triple::armeb:
1402
36.5k
  case llvm::Triple::thumb:
1403
36.5k
  case llvm::Triple::thumbeb:
1404
36.5k
    return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
1405
326k
  case llvm::Triple::aarch64:
1406
326k
  case llvm::Triple::aarch64_32:
1407
326k
  case llvm::Triple::aarch64_be:
1408
326k
    return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
1409
47
  case llvm::Triple::bpfeb:
1410
47
  case llvm::Triple::bpfel:
1411
47
    return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
1412
1.80k
  case llvm::Triple::hexagon:
1413
1.80k
    return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
1414
1.05k
  case llvm::Triple::mips:
1415
1.05k
  case llvm::Triple::mipsel:
1416
1.05k
  case llvm::Triple::mips64:
1417
1.05k
  case llvm::Triple::mips64el:
1418
1.05k
    return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
1419
16.2k
  case llvm::Triple::systemz:
1420
16.2k
    return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
1421
894k
  case llvm::Triple::x86:
1422
894k
  case llvm::Triple::x86_64:
1423
894k
    return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall);
1424
75.8k
  case llvm::Triple::ppc:
1425
75.8k
  case llvm::Triple::ppc64:
1426
75.8k
  case llvm::Triple::ppc64le:
1427
75.8k
    return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
1428
439
  case llvm::Triple::amdgcn:
1429
439
    return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall);
1430
1.35M
  }
1431
1.35M
}
1432
1433
ExprResult
1434
Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
1435
1.58M
                               CallExpr *TheCall) {
1436
1.58M
  ExprResult TheCallResult(TheCall);
1437
1438
  // Find out if any arguments are required to be integer constant expressions.
1439
1.58M
  unsigned ICEArguments = 0;
1440
1.58M
  ASTContext::GetBuiltinTypeError Error;
1441
1.58M
  Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
1442
1.58M
  if (Error != ASTContext::GE_None)
1443
4.89k
    ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
1444
1445
  // If any arguments are required to be ICE's, check and diagnose.
1446
1.98M
  for (unsigned ArgNo = 0; ICEArguments != 0; 
++ArgNo400k
) {
1447
    // Skip arguments not required to be ICE's.
1448
400k
    if ((ICEArguments & (1 << ArgNo)) == 0) 
continue272k
;
1449
1450
127k
    llvm::APSInt Result;
1451
127k
    if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
1452
504
      return true;
1453
127k
    ICEArguments &= ~(1 << ArgNo);
1454
127k
  }
1455
1456
1.58M
  switch (BuiltinID) {
1457
420
  case Builtin::BI__builtin___CFStringMakeConstantString:
1458
420
    assert(TheCall->getNumArgs() == 1 &&
1459
420
           "Wrong # arguments to builtin CFStringMakeConstantString");
1460
420
    if (CheckObjCString(TheCall->getArg(0)))
1461
1
      return ExprError();
1462
419
    break;
1463
562
  case Builtin::BI__builtin_ms_va_start:
1464
562
  case Builtin::BI__builtin_stdarg_start:
1465
562
  case Builtin::BI__builtin_va_start:
1466
562
    if (SemaBuiltinVAStart(BuiltinID, TheCall))
1467
33
      return ExprError();
1468
529
    break;
1469
12
  case Builtin::BI__va_start: {
1470
12
    switch (Context.getTargetInfo().getTriple().getArch()) {
1471
10
    case llvm::Triple::aarch64:
1472
10
    case llvm::Triple::arm:
1473
10
    case llvm::Triple::thumb:
1474
10
      if (SemaBuiltinVAStartARMMicrosoft(TheCall))
1475
3
        return ExprError();
1476
7
      break;
1477
2
    default:
1478
2
      if (SemaBuiltinVAStart(BuiltinID, TheCall))
1479
0
        return ExprError();
1480
2
      break;
1481
9
    }
1482
9
    break;
1483
9
  }
1484
1485
  // The acquire, release, and no fence variants are ARM and AArch64 only.
1486
42
  case Builtin::BI_interlockedbittestandset_acq:
1487
42
  case Builtin::BI_interlockedbittestandset_rel:
1488
42
  case Builtin::BI_interlockedbittestandset_nf:
1489
42
  case Builtin::BI_interlockedbittestandreset_acq:
1490
42
  case Builtin::BI_interlockedbittestandreset_rel:
1491
42
  case Builtin::BI_interlockedbittestandreset_nf:
1492
42
    if (CheckBuiltinTargetSupport(
1493
42
            *this, BuiltinID, TheCall,
1494
42
            {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
1495
12
      return ExprError();
1496
30
    break;
1497
1498
  // The 64-bit bittest variants are x64, ARM, and AArch64 only.
1499
48
  case Builtin::BI_bittest64:
1500
48
  case Builtin::BI_bittestandcomplement64:
1501
48
  case Builtin::BI_bittestandreset64:
1502
48
  case Builtin::BI_bittestandset64:
1503
48
  case Builtin::BI_interlockedbittestandreset64:
1504
48
  case Builtin::BI_interlockedbittestandset64:
1505
48
    if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
1506
48
                                  {llvm::Triple::x86_64, llvm::Triple::arm,
1507
48
                                   llvm::Triple::thumb, llvm::Triple::aarch64}))
1508
6
      return ExprError();
1509
42
    break;
1510
1511
395
  case Builtin::BI__builtin_isgreater:
1512
395
  case Builtin::BI__builtin_isgreaterequal:
1513
395
  case Builtin::BI__builtin_isless:
1514
395
  case Builtin::BI__builtin_islessequal:
1515
395
  case Builtin::BI__builtin_islessgreater:
1516
395
  case Builtin::BI__builtin_isunordered:
1517
395
    if (SemaBuiltinUnorderedCompare(TheCall))
1518
4
      return ExprError();
1519
391
    break;
1520
61
  case Builtin::BI__builtin_fpclassify:
1521
61
    if (SemaBuiltinFPClassification(TheCall, 6))
1522
5
      return ExprError();
1523
56
    break;
1524
400
  case Builtin::BI__builtin_isfinite:
1525
400
  case Builtin::BI__builtin_isinf:
1526
400
  case Builtin::BI__builtin_isinf_sign:
1527
400
  case Builtin::BI__builtin_isnan:
1528
400
  case Builtin::BI__builtin_isnormal:
1529
400
  case Builtin::BI__builtin_signbit:
1530
400
  case Builtin::BI__builtin_signbitf:
1531
400
  case Builtin::BI__builtin_signbitl:
1532
400
    if (SemaBuiltinFPClassification(TheCall, 1))
1533
7
      return ExprError();
1534
393
    break;
1535
159k
  case Builtin::BI__builtin_shufflevector:
1536
159k
    return SemaBuiltinShuffleVector(TheCall);
1537
    // TheCall will be freed by the smart pointer here, but that's fine, since
1538
    // SemaBuiltinShuffleVector guts it, but then doesn't release it.
1539
260
  case Builtin::BI__builtin_prefetch:
1540
260
    if (SemaBuiltinPrefetch(TheCall))
1541
6
      return ExprError();
1542
254
    break;
1543
12
  case Builtin::BI__builtin_alloca_with_align:
1544
12
    if (SemaBuiltinAllocaWithAlign(TheCall))
1545
3
      return ExprError();
1546
9
    LLVM_FALLTHROUGH;
1547
60
  case Builtin::BI__builtin_alloca:
1548
60
    Diag(TheCall->getBeginLoc(), diag::warn_alloca)
1549
60
        << TheCall->getDirectCallee();
1550
60
    break;
1551
738
  case Builtin::BI__assume:
1552
738
  case Builtin::BI__builtin_assume:
1553
738
    if (SemaBuiltinAssume(TheCall))
1554
0
      return ExprError();
1555
738
    break;
1556
55
  case Builtin::BI__builtin_assume_aligned:
1557
55
    if (SemaBuiltinAssumeAligned(TheCall))
1558
6
      return ExprError();
1559
49
    break;
1560
766
  case Builtin::BI__builtin_dynamic_object_size:
1561
766
  case Builtin::BI__builtin_object_size:
1562
766
    if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1563
9
      return ExprError();
1564
757
    break;
1565
11
  case Builtin::BI__builtin_longjmp:
1566
11
    if (SemaBuiltinLongjmp(TheCall))
1567
3
      return ExprError();
1568
8
    break;
1569
9
  case Builtin::BI__builtin_setjmp:
1570
9
    if (SemaBuiltinSetjmp(TheCall))
1571
3
      return ExprError();
1572
6
    break;
1573
15
  case Builtin::BI_setjmp:
1574
15
  case Builtin::BI_setjmpex:
1575
15
    if (checkArgCount(*this, TheCall, 1))
1576
0
      return true;
1577
15
    break;
1578
88
  case Builtin::BI__builtin_classify_type:
1579
88
    if (checkArgCount(*this, TheCall, 1)) 
return true0
;
1580
88
    TheCall->setType(Context.IntTy);
1581
88
    break;
1582
42
  case Builtin::BI__builtin_complex:
1583
42
    if (SemaBuiltinComplex(TheCall))
1584
22
      return ExprError();
1585
20
    break;
1586
4.68k
  case Builtin::BI__builtin_constant_p: {
1587
4.68k
    if (checkArgCount(*this, TheCall, 1)) 
return true2
;
1588
4.68k
    ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
1589
4.68k
    if (Arg.isInvalid()) 
return true0
;
1590
4.68k
    TheCall->setArg(0, Arg.get());
1591
4.68k
    TheCall->setType(Context.IntTy);
1592
4.68k
    break;
1593
4.68k
  }
1594
120
  case Builtin::BI__builtin_launder:
1595
120
    return SemaBuiltinLaunder(*this, TheCall);
1596
266
  case Builtin::BI__sync_fetch_and_add:
1597
266
  case Builtin::BI__sync_fetch_and_add_1:
1598
266
  case Builtin::BI__sync_fetch_and_add_2:
1599
266
  case Builtin::BI__sync_fetch_and_add_4:
1600
266
  case Builtin::BI__sync_fetch_and_add_8:
1601
266
  case Builtin::BI__sync_fetch_and_add_16:
1602
266
  case Builtin::BI__sync_fetch_and_sub:
1603
266
  case Builtin::BI__sync_fetch_and_sub_1:
1604
266
  case Builtin::BI__sync_fetch_and_sub_2:
1605
266
  case Builtin::BI__sync_fetch_and_sub_4:
1606
266
  case Builtin::BI__sync_fetch_and_sub_8:
1607
266
  case Builtin::BI__sync_fetch_and_sub_16:
1608
266
  case Builtin::BI__sync_fetch_and_or:
1609
266
  case Builtin::BI__sync_fetch_and_or_1:
1610
266
  case Builtin::BI__sync_fetch_and_or_2:
1611
266
  case Builtin::BI__sync_fetch_and_or_4:
1612
266
  case Builtin::BI__sync_fetch_and_or_8:
1613
266
  case Builtin::BI__sync_fetch_and_or_16:
1614
266
  case Builtin::BI__sync_fetch_and_and:
1615
266
  case Builtin::BI__sync_fetch_and_and_1:
1616
266
  case Builtin::BI__sync_fetch_and_and_2:
1617
266
  case Builtin::BI__sync_fetch_and_and_4:
1618
266
  case Builtin::BI__sync_fetch_and_and_8:
1619
266
  case Builtin::BI__sync_fetch_and_and_16:
1620
266
  case Builtin::BI__sync_fetch_and_xor:
1621
266
  case Builtin::BI__sync_fetch_and_xor_1:
1622
266
  case Builtin::BI__sync_fetch_and_xor_2:
1623
266
  case Builtin::BI__sync_fetch_and_xor_4:
1624
266
  case Builtin::BI__sync_fetch_and_xor_8:
1625
266
  case Builtin::BI__sync_fetch_and_xor_16:
1626
266
  case Builtin::BI__sync_fetch_and_nand:
1627
266
  case Builtin::BI__sync_fetch_and_nand_1:
1628
266
  case Builtin::BI__sync_fetch_and_nand_2:
1629
266
  case Builtin::BI__sync_fetch_and_nand_4:
1630
266
  case Builtin::BI__sync_fetch_and_nand_8:
1631
266
  case Builtin::BI__sync_fetch_and_nand_16:
1632
266
  case Builtin::BI__sync_add_and_fetch:
1633
266
  case Builtin::BI__sync_add_and_fetch_1:
1634
266
  case Builtin::BI__sync_add_and_fetch_2:
1635
266
  case Builtin::BI__sync_add_and_fetch_4:
1636
266
  case Builtin::BI__sync_add_and_fetch_8:
1637
266
  case Builtin::BI__sync_add_and_fetch_16:
1638
266
  case Builtin::BI__sync_sub_and_fetch:
1639
266
  case Builtin::BI__sync_sub_and_fetch_1:
1640
266
  case Builtin::BI__sync_sub_and_fetch_2:
1641
266
  case Builtin::BI__sync_sub_and_fetch_4:
1642
266
  case Builtin::BI__sync_sub_and_fetch_8:
1643
266
  case Builtin::BI__sync_sub_and_fetch_16:
1644
266
  case Builtin::BI__sync_and_and_fetch:
1645
266
  case Builtin::BI__sync_and_and_fetch_1:
1646
266
  case Builtin::BI__sync_and_and_fetch_2:
1647
266
  case Builtin::BI__sync_and_and_fetch_4:
1648
266
  case Builtin::BI__sync_and_and_fetch_8:
1649
266
  case Builtin::BI__sync_and_and_fetch_16:
1650
266
  case Builtin::BI__sync_or_and_fetch:
1651
266
  case Builtin::BI__sync_or_and_fetch_1:
1652
266
  case Builtin::BI__sync_or_and_fetch_2:
1653
266
  case Builtin::BI__sync_or_and_fetch_4:
1654
266
  case Builtin::BI__sync_or_and_fetch_8:
1655
266
  case Builtin::BI__sync_or_and_fetch_16:
1656
266
  case Builtin::BI__sync_xor_and_fetch:
1657
266
  case Builtin::BI__sync_xor_and_fetch_1:
1658
266
  case Builtin::BI__sync_xor_and_fetch_2:
1659
266
  case Builtin::BI__sync_xor_and_fetch_4:
1660
266
  case Builtin::BI__sync_xor_and_fetch_8:
1661
266
  case Builtin::BI__sync_xor_and_fetch_16:
1662
266
  case Builtin::BI__sync_nand_and_fetch:
1663
266
  case Builtin::BI__sync_nand_and_fetch_1:
1664
266
  case Builtin::BI__sync_nand_and_fetch_2:
1665
266
  case Builtin::BI__sync_nand_and_fetch_4:
1666
266
  case Builtin::BI__sync_nand_and_fetch_8:
1667
266
  case Builtin::BI__sync_nand_and_fetch_16:
1668
266
  case Builtin::BI__sync_val_compare_and_swap:
1669
266
  case Builtin::BI__sync_val_compare_and_swap_1:
1670
266
  case Builtin::BI__sync_val_compare_and_swap_2:
1671
266
  case Builtin::BI__sync_val_compare_and_swap_4:
1672
266
  case Builtin::BI__sync_val_compare_and_swap_8:
1673
266
  case Builtin::BI__sync_val_compare_and_swap_16:
1674
266
  case Builtin::BI__sync_bool_compare_and_swap:
1675
266
  case Builtin::BI__sync_bool_compare_and_swap_1:
1676
266
  case Builtin::BI__sync_bool_compare_and_swap_2:
1677
266
  case Builtin::BI__sync_bool_compare_and_swap_4:
1678
266
  case Builtin::BI__sync_bool_compare_and_swap_8:
1679
266
  case Builtin::BI__sync_bool_compare_and_swap_16:
1680
266
  case Builtin::BI__sync_lock_test_and_set:
1681
266
  case Builtin::BI__sync_lock_test_and_set_1:
1682
266
  case Builtin::BI__sync_lock_test_and_set_2:
1683
266
  case Builtin::BI__sync_lock_test_and_set_4:
1684
266
  case Builtin::BI__sync_lock_test_and_set_8:
1685
266
  case Builtin::BI__sync_lock_test_and_set_16:
1686
266
  case Builtin::BI__sync_lock_release:
1687
266
  case Builtin::BI__sync_lock_release_1:
1688
266
  case Builtin::BI__sync_lock_release_2:
1689
266
  case Builtin::BI__sync_lock_release_4:
1690
266
  case Builtin::BI__sync_lock_release_8:
1691
266
  case Builtin::BI__sync_lock_release_16:
1692
266
  case Builtin::BI__sync_swap:
1693
266
  case Builtin::BI__sync_swap_1:
1694
266
  case Builtin::BI__sync_swap_2:
1695
266
  case Builtin::BI__sync_swap_4:
1696
266
  case Builtin::BI__sync_swap_8:
1697
266
  case Builtin::BI__sync_swap_16:
1698
266
    return SemaBuiltinAtomicOverloaded(TheCallResult);
1699
3
  case Builtin::BI__sync_synchronize:
1700
3
    Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
1701
3
        << TheCall->getCallee()->getSourceRange();
1702
3
    break;
1703
3.85k
  case Builtin::BI__builtin_nontemporal_load:
1704
3.85k
  case Builtin::BI__builtin_nontemporal_store:
1705
3.85k
    return SemaBuiltinNontemporalOverloaded(TheCallResult);
1706
11
  case Builtin::BI__builtin_memcpy_inline: {
1707
11
    clang::Expr *SizeOp = TheCall->getArg(2);
1708
    // We warn about copying to or from `nullptr` pointers when `size` is
1709
    // greater than 0. When `size` is value dependent we cannot evaluate its
1710
    // value so we bail out.
1711
11
    if (SizeOp->isValueDependent())
1712
1
      break;
1713
10
    if (!SizeOp->EvaluateKnownConstInt(Context).isNullValue()) {
1714
6
      CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
1715
6
      CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
1716
6
    }
1717
10
    break;
1718
10
  }
1719
10
#define BUILTIN(ID, TYPE, ATTRS)
1720
10
#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1721
5.17k
  case Builtin::BI##ID: \
1722
5.17k
    return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1723
10
#include "clang/Basic/Builtins.def"
1724
31
  case Builtin::BI__annotation:
1725
31
    if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1726
9
      return ExprError();
1727
22
    break;
1728
12
  case Builtin::BI__builtin_annotation:
1729
12
    if (SemaBuiltinAnnotation(*this, TheCall))
1730
3
      return ExprError();
1731
9
    break;
1732
1.06k
  case Builtin::BI__builtin_addressof:
1733
1.06k
    if (SemaBuiltinAddressof(*this, TheCall))
1734
2
      return ExprError();
1735
1.06k
    break;
1736
281
  case Builtin::BI__builtin_is_aligned:
1737
281
  case Builtin::BI__builtin_align_up:
1738
281
  case Builtin::BI__builtin_align_down:
1739
281
    if (SemaBuiltinAlignment(*this, TheCall, BuiltinID))
1740
72
      return ExprError();
1741
209
    break;
1742
105
  case Builtin::BI__builtin_add_overflow:
1743
105
  case Builtin::BI__builtin_sub_overflow:
1744
105
  case Builtin::BI__builtin_mul_overflow:
1745
105
    if (SemaBuiltinOverflow(*this, TheCall, BuiltinID))
1746
8
      return ExprError();
1747
97
    break;
1748
957
  case Builtin::BI__builtin_operator_new:
1749
957
  case Builtin::BI__builtin_operator_delete: {
1750
957
    bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1751
957
    ExprResult Res =
1752
957
        SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1753
957
    if (Res.isInvalid())
1754
56
      CorrectDelayedTyposInExpr(TheCallResult.get());
1755
957
    return Res;
1756
957
  }
1757
36
  case Builtin::BI__builtin_dump_struct: {
1758
    // We first want to ensure we are called with 2 arguments
1759
36
    if (checkArgCount(*this, TheCall, 2))
1760
2
      return ExprError();
1761
    // Ensure that the first argument is of type 'struct XX *'
1762
34
    const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1763
34
    const QualType PtrArgType = PtrArg->getType();
1764
34
    if (!PtrArgType->isPointerType() ||
1765
32
        !PtrArgType->getPointeeType()->isRecordType()) {
1766
3
      Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1767
3
          << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1768
3
          << "structure pointer";
1769
3
      return ExprError();
1770
3
    }
1771
1772
    // Ensure that the second argument is of type 'FunctionType'
1773
31
    const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1774
31
    const QualType FnPtrArgType = FnPtrArg->getType();
1775
31
    if (!FnPtrArgType->isPointerType()) {
1776
1
      Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1777
1
          << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1778
1
          << FnPtrArgType << "'int (*)(const char *, ...)'";
1779
1
      return ExprError();
1780
1
    }
1781
1782
30
    const auto *FuncType =
1783
30
        FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1784
1785
30
    if (!FuncType) {
1786
0
      Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1787
0
          << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1788
0
          << FnPtrArgType << "'int (*)(const char *, ...)'";
1789
0
      return ExprError();
1790
0
    }
1791
1792
30
    if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1793
29
      if (!FT->getNumParams()) {
1794
1
        Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1795
1
            << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1796
1
            << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1797
1
        return ExprError();
1798
1
      }
1799
28
      QualType PT = FT->getParamType(0);
1800
28
      if (!FT->isVariadic() || 
FT->getReturnType() != Context.IntTy27
||
1801
26
          !PT->isPointerType() || 
!PT->getPointeeType()->isCharType()25
||
1802
25
          !PT->getPointeeType().isConstQualified()) {
1803
4
        Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1804
4
            << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1805
4
            << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1806
4
        return ExprError();
1807
4
      }
1808
25
    }
1809
1810
25
    TheCall->setType(Context.IntTy);
1811
25
    break;
1812
25
  }
1813
36
  case Builtin::BI__builtin_expect_with_probability: {
1814
    // We first want to ensure we are called with 3 arguments
1815
36
    if (checkArgCount(*this, TheCall, 3))
1816
0
      return ExprError();
1817
    // then check probability is constant float in range [0.0, 1.0]
1818
36
    const Expr *ProbArg = TheCall->getArg(2);
1819
36
    SmallVector<PartialDiagnosticAt, 8> Notes;
1820
36
    Expr::EvalResult Eval;
1821
36
    Eval.Diag = &Notes;
1822
36
    if ((!ProbArg->EvaluateAsConstantExpr(Eval, Expr::EvaluateForCodeGen,
1823
36
                                          Context)) ||
1824
34
        !Eval.Val.isFloat()) {
1825
2
      Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
1826
2
          << ProbArg->getSourceRange();
1827
2
      for (const PartialDiagnosticAt &PDiag : Notes)
1828
4
        Diag(PDiag.first, PDiag.second);
1829
2
      return ExprError();
1830
2
    }
1831
34
    llvm::APFloat Probability = Eval.Val.getFloat();
1832
34
    bool LoseInfo = false;
1833
34
    Probability.convert(llvm::APFloat::IEEEdouble(),
1834
34
                        llvm::RoundingMode::Dynamic, &LoseInfo);
1835
34
    if (!(Probability >= llvm::APFloat(0.0) &&
1836
28
          Probability <= llvm::APFloat(1.0))) {
1837
12
      Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
1838
12
          << ProbArg->getSourceRange();
1839
12
      return ExprError();
1840
12
    }
1841
22
    break;
1842
22
  }
1843
29
  case Builtin::BI__builtin_preserve_access_index:
1844
29
    if (SemaBuiltinPreserveAI(*this, TheCall))
1845
1
      return ExprError();
1846
28
    break;
1847
16
  case Builtin::BI__builtin_call_with_static_chain:
1848
16
    if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1849
6
      return ExprError();
1850
10
    break;
1851
30
  case Builtin::BI__exception_code:
1852
30
  case Builtin::BI_exception_code:
1853
30
    if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1854
30
                                 diag::err_seh___except_block))
1855
6
      return ExprError();
1856
24
    break;
1857
9
  case Builtin::BI__exception_info:
1858
9
  case Builtin::BI_exception_info:
1859
9
    if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1860
9
                                 diag::err_seh___except_filter))
1861
7
      return ExprError();
1862
2
    break;
1863
6
  case Builtin::BI__GetExceptionInfo:
1864
6
    if (checkArgCount(*this, TheCall, 1))
1865
0
      return ExprError();
1866
1867
6
    if (CheckCXXThrowOperand(
1868
6
            TheCall->getBeginLoc(),
1869
6
            Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1870
6
            TheCall))
1871
0
      return ExprError();
1872
1873
6
    TheCall->setType(Context.VoidPtrTy);
1874
6
    break;
1875
  // OpenCL v2.0, s6.13.16 - Pipe functions
1876
28
  case Builtin::BIread_pipe:
1877
28
  case Builtin::BIwrite_pipe:
1878
    // Since those two functions are declared with var args, we need a semantic
1879
    // check for the argument.
1880
28
    if (SemaBuiltinRWPipe(*this, TheCall))
1881
14
      return ExprError();
1882
14
    break;
1883
12
  case Builtin::BIreserve_read_pipe:
1884
12
  case Builtin::BIreserve_write_pipe:
1885
12
  case Builtin::BIwork_group_reserve_read_pipe:
1886
12
  case Builtin::BIwork_group_reserve_write_pipe:
1887
12
    if (SemaBuiltinReserveRWPipe(*this, TheCall))
1888
4
      return ExprError();
1889
8
    break;
1890
4
  case Builtin::BIsub_group_reserve_read_pipe:
1891
4
  case Builtin::BIsub_group_reserve_write_pipe:
1892
4
    if (checkOpenCLSubgroupExt(*this, TheCall) ||
1893
4
        SemaBuiltinReserveRWPipe(*this, TheCall))
1894
2
      return ExprError();
1895
2
    break;
1896
10
  case Builtin::BIcommit_read_pipe:
1897
10
  case Builtin::BIcommit_write_pipe:
1898
10
  case Builtin::BIwork_group_commit_read_pipe:
1899
10
  case Builtin::BIwork_group_commit_write_pipe:
1900
10
    if (SemaBuiltinCommitRWPipe(*this, TheCall))
1901
4
      return ExprError();
1902
6
    break;
1903
4
  case Builtin::BIsub_group_commit_read_pipe:
1904
4
  case Builtin::BIsub_group_commit_write_pipe:
1905
4
    if (checkOpenCLSubgroupExt(*this, TheCall) ||
1906
4
        SemaBuiltinCommitRWPipe(*this, TheCall))
1907
2
      return ExprError();
1908
2
    break;
1909
10
  case Builtin::BIget_pipe_num_packets:
1910
10
  case Builtin::BIget_pipe_max_packets:
1911
10
    if (SemaBuiltinPipePackets(*this, TheCall))
1912
2
      return ExprError();
1913
8
    break;
1914
32
  case Builtin::BIto_global:
1915
32
  case Builtin::BIto_local:
1916
32
  case Builtin::BIto_private:
1917
32
    if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1918
4
      return ExprError();
1919
28
    break;
1920
  // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1921
157
  case Builtin::BIenqueue_kernel:
1922
157
    if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1923
68
      return ExprError();
1924
89
    break;
1925
97
  case Builtin::BIget_kernel_work_group_size:
1926
97
  case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1927
97
    if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1928
56
      return ExprError();
1929
41
    break;
1930
38
  case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1931
38
  case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1932
38
    if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1933
24
      return ExprError();
1934
14
    break;
1935
1.21k
  case Builtin::BI__builtin_os_log_format:
1936
1.21k
    Cleanup.setExprNeedsCleanups(true);
1937
1.21k
    LLVM_FALLTHROUGH;
1938
2.35k
  case Builtin::BI__builtin_os_log_format_buffer_size:
1939
2.35k
    if (SemaBuiltinOSLogFormat(TheCall))
1940
2
      return ExprError();
1941
2.35k
    break;
1942
26
  case Builtin::BI__builtin_frame_address:
1943
26
  case Builtin::BI__builtin_return_address: {
1944
26
    if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
1945
4
      return ExprError();
1946
1947
    // -Wframe-address warning if non-zero passed to builtin
1948
    // return/frame address.
1949
22
    Expr::EvalResult Result;
1950
22
    if (TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
1951
22
        Result.Val.getInt() != 0)
1952
5
      Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
1953
5
          << ((BuiltinID == Builtin::BI__builtin_return_address)
1954
3
                  ? "__builtin_return_address"
1955
2
                  : "__builtin_frame_address")
1956
5
          << TheCall->getSourceRange();
1957
22
    break;
1958
22
  }
1959
1960
40
  case Builtin::BI__builtin_matrix_transpose:
1961
40
    return SemaBuiltinMatrixTranspose(TheCall, TheCallResult);
1962
1963
54
  case Builtin::BI__builtin_matrix_column_major_load:
1964
54
    return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
1965
1966
43
  case Builtin::BI__builtin_matrix_column_major_store:
1967
43
    return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
1968
1.41M
  }
1969
1970
  // Since the target specific builtins for each arch overlap, only check those
1971
  // of the arch we are compiling for.
1972
1.41M
  if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1973
1.35M
    if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
1974
4
      assert(Context.getAuxTargetInfo() &&
1975
4
             "Aux Target Builtin, but not an aux target?");
1976
1977
4
      if (CheckTSBuiltinFunctionCall(
1978
4
              *Context.getAuxTargetInfo(),
1979
4
              Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
1980
1
        return ExprError();
1981
1.35M
    } else {
1982
1.35M
      if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
1983
1.35M
                                     TheCall))
1984
2.56k
        return ExprError();
1985
1.41M
    }
1986
1.35M
  }
1987
1988
1.41M
  return TheCallResult;
1989
1.41M
}
1990
1991
// Get the valid immediate range for the specified NEON type code.
1992
2.84k
static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
1993
2.84k
  NeonTypeFlags Type(t);
1994
2.49k
  int IsQuad = ForceQuad ? 
true359
: Type.isQuad();
1995
2.84k
  switch (Type.getEltType()) {
1996
302
  case NeonTypeFlags::Int8:
1997
302
  case NeonTypeFlags::Poly8:
1998
184
    return shift ? 
7118
: (8 << IsQuad) - 1;
1999
707
  case NeonTypeFlags::Int16:
2000
707
  case NeonTypeFlags::Poly16:
2001
356
    return shift ? 15 : 
(4 << IsQuad) - 1351
;
2002
1.02k
  case NeonTypeFlags::Int32:
2003
650
    return shift ? 
31374
: (2 << IsQuad) - 1;
2004
463
  case NeonTypeFlags::Int64:
2005
463
  case NeonTypeFlags::Poly64:
2006
322
    return shift ? 63 : 
(1 << IsQuad) - 1141
;
2007
0
  case NeonTypeFlags::Poly128:
2008
0
    return shift ? 127 : (1 << IsQuad) - 1;
2009
90
  case NeonTypeFlags::Float16:
2010
90
    assert(!shift && "cannot shift float types!");
2011
90
    return (4 << IsQuad) - 1;
2012
106
  case NeonTypeFlags::Float32:
2013
106
    assert(!shift && "cannot shift float types!");
2014
106
    return (2 << IsQuad) - 1;
2015
81
  case NeonTypeFlags::Float64:
2016
81
    assert(!shift && "cannot shift float types!");
2017
81
    return (1 << IsQuad) - 1;
2018
76
  case NeonTypeFlags::BFloat16:
2019
76
    assert(!shift && "cannot shift float types!");
2020
76
    return (4 << IsQuad) - 1;
2021
0
  }
2022
0
  llvm_unreachable("Invalid NeonTypeFlag!");
2023
0
}
2024
2025
/// getNeonEltType - Return the QualType corresponding to the elements of
2026
/// the vector type specified by the NeonTypeFlags.  This is used to check
2027
/// the pointer arguments for Neon load/store intrinsics.
2028
static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
2029
1.46k
                               bool IsPolyUnsigned, bool IsInt64Long) {
2030
1.46k
  switch (Flags.getEltType()) {
2031
222
  case NeonTypeFlags::Int8:
2032
135
    return Flags.isUnsigned() ? 
Context.UnsignedCharTy87
: Context.SignedCharTy;
2033
235
  case NeonTypeFlags::Int16:
2034
142
    return Flags.isUnsigned() ? 
Context.UnsignedShortTy93
: Context.ShortTy;
2035
235
  case NeonTypeFlags::Int32:
2036
142
    return Flags.isUnsigned() ? 
Context.UnsignedIntTy93
: Context.IntTy;
2037
196
  case NeonTypeFlags::Int64:
2038
196
    if (IsInt64Long)
2039
142
      return Flags.isUnsigned() ? 
Context.UnsignedLongTy47
:
Context.LongTy95
;
2040
54
    else
2041
54
      return Flags.isUnsigned() ? 
Context.UnsignedLongLongTy29
2042
25
                                : Context.LongLongTy;
2043
87
  case NeonTypeFlags::Poly8:
2044
47
    return IsPolyUnsigned ? Context.UnsignedCharTy : 
Context.SignedCharTy40
;
2045
93
  case NeonTypeFlags::Poly16:
2046
47
    return IsPolyUnsigned ? Context.UnsignedShortTy : 
Context.ShortTy46
;
2047
48
  case NeonTypeFlags::Poly64:
2048
48
    if (IsInt64Long)
2049
48
      return Context.UnsignedLongTy;
2050
0
    else
2051
0
      return Context.UnsignedLongLongTy;
2052
0
  case NeonTypeFlags::Poly128:
2053
0
    break;
2054
93
  case NeonTypeFlags::Float16:
2055
93
    return Context.HalfTy;
2056
95
  case NeonTypeFlags::Float32:
2057
95
    return Context.FloatTy;
2058
47
  case NeonTypeFlags::Float64:
2059
47
    return Context.DoubleTy;
2060
116
  case NeonTypeFlags::BFloat16:
2061
116
    return Context.BFloat16Ty;
2062
0
  }
2063
0
  llvm_unreachable("Invalid NeonTypeFlag!");
2064
0
}
2065
2066
326k
bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2067
  // Range check SVE intrinsics that take immediate values.
2068
326k
  SmallVector<std::tuple<int,int,int>, 3> ImmChecks;
2069
2070
326k
  switch (BuiltinID) {
2071
322k
  default:
2072
322k
    return false;
2073
0
#define GET_SVE_IMMEDIATE_CHECK
2074
0
#include "clang/Basic/arm_sve_sema_rangechecks.inc"
2075
326k
#undef GET_SVE_IMMEDIATE_CHECK
2076
326k
  }
2077
2078
  // Perform all the immediate checks for this builtin call.
2079
3.55k
  bool HasError = false;
2080
3.99k
  for (auto &I : ImmChecks) {
2081
3.99k
    int ArgNum, CheckTy, ElementSizeInBits;
2082
3.99k
    std::tie(ArgNum, CheckTy, ElementSizeInBits) = I;
2083
2084
3.99k
    typedef bool(*OptionSetCheckFnTy)(int64_t Value);
2085
2086
    // Function that checks whether the operand (ArgNum) is an immediate
2087
    // that is one of the predefined values.
2088
3.99k
    auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm,
2089
484
                                   int ErrDiag) -> bool {
2090
      // We can't check the value of a dependent argument.
2091
484
      Expr *Arg = TheCall->getArg(ArgNum);
2092
484
      if (Arg->isTypeDependent() || Arg->isValueDependent())
2093
0
        return false;
2094
2095
      // Check constant-ness first.
2096
484
      llvm::APSInt Imm;
2097
484
      if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm))
2098
0
        return true;
2099
2100
484
      if (!CheckImm(Imm.getSExtValue()))
2101
166
        return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange();
2102
318
      return false;
2103
318
    };
2104
2105
3.99k
    switch ((SVETypeFlags::ImmCheckType)CheckTy) {
2106
484
    case SVETypeFlags::ImmCheck0_31:
2107
484
      if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31))
2108
0
        HasError = true;
2109
484
      break;
2110
271
    case SVETypeFlags::ImmCheck0_13:
2111
271
      if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13))
2112
16
        HasError = true;
2113
271
      break;
2114
640
    case SVETypeFlags::ImmCheck1_16:
2115
640
      if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16))
2116
352
        HasError = true;
2117
640
      break;
2118
32
    case SVETypeFlags::ImmCheck0_7:
2119
32
      if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7))
2120
12
        HasError = true;
2121
32
      break;
2122
78
    case SVETypeFlags::ImmCheckExtract:
2123
78
      if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2124
78
                                      (2048 / ElementSizeInBits) - 1))
2125
30
        HasError = true;
2126
78
      break;
2127
448
    case SVETypeFlags::ImmCheckShiftRight:
2128
448
      if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits))
2129
176
        HasError = true;
2130
448
      break;
2131
360
    case SVETypeFlags::ImmCheckShiftRightNarrow:
2132
360
      if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1,
2133
360
                                      ElementSizeInBits / 2))
2134
120
        HasError = true;
2135
360
      break;
2136
192
    case SVETypeFlags::ImmCheckShiftLeft:
2137
192
      if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2138
192
                                      ElementSizeInBits - 1))
2139
64
        HasError = true;
2140
192
      break;
2141
492
    case SVETypeFlags::ImmCheckLaneIndex:
2142
492
      if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2143
492
                                      (128 / (1 * ElementSizeInBits)) - 1))
2144
160
        HasError = true;
2145
492
      break;
2146
116
    case SVETypeFlags::ImmCheckLaneIndexCompRotate:
2147
116
      if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2148
116
                                      (128 / (2 * ElementSizeInBits)) - 1))
2149
48
        HasError = true;
2150
116
      break;
2151
60
    case SVETypeFlags::ImmCheckLaneIndexDot:
2152
60
      if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2153
60
                                      (128 / (4 * ElementSizeInBits)) - 1))
2154
16
        HasError = true;
2155
60
      break;
2156
136
    case SVETypeFlags::ImmCheckComplexRot90_270:
2157
136
      if (CheckImmediateInSet([](int64_t V) { return V == 90 || 
V == 27085
; },
2158
136
                              diag::err_rotation_argument_to_cadd))
2159
58
        HasError = true;
2160
136
      break;
2161
348
    case SVETypeFlags::ImmCheckComplexRotAll90:
2162
348
      if (CheckImmediateInSet(
2163
348
              [](int64_t V) {
2164
348
                return V == 0 || 
V == 90270
||
V == 180216
||
V == 270160
;
2165
348
              },
2166
348
              diag::err_rotation_argument_to_cmla))
2167
108
        HasError = true;
2168
348
      break;
2169
107
    case SVETypeFlags::ImmCheck0_1:
2170
107
      if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1))
2171
44
        HasError = true;
2172
107
      break;
2173
111
    case SVETypeFlags::ImmCheck0_2:
2174
111
      if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2))
2175
44
        HasError = true;
2176
111
      break;
2177
119
    case SVETypeFlags::ImmCheck0_3:
2178
119
      if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3))
2179
44
        HasError = true;
2180
119
      break;
2181
3.99k
    }
2182
3.99k
  }
2183
2184
3.55k
  return HasError;
2185
3.55k
}
2186
2187
bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI,
2188
363k
                                        unsigned BuiltinID, CallExpr *TheCall) {
2189
363k
  llvm::APSInt Result;
2190
363k
  uint64_t mask = 0;
2191
363k
  unsigned TV = 0;
2192
363k
  int PtrArgNum = -1;
2193
363k
  bool HasConstPtr = false;
2194
363k
  switch (BuiltinID) {
2195
0
#define GET_NEON_OVERLOAD_CHECK
2196
0
#include "clang/Basic/arm_neon.inc"
2197
363k
#include "clang/Basic/arm_fp16.inc"
2198
363k
#undef GET_NEON_OVERLOAD_CHECK
2199
363k
  }
2200
2201
  // For NEON intrinsics which are overloaded on vector element type, validate
2202
  // the immediate which specifies which variant to emit.
2203
363k
  unsigned ImmArg = TheCall->getNumArgs()-1;
2204
363k
  if (mask) {
2205
121k
    if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
2206
0
      return true;
2207
2208
121k
    TV = Result.getLimitedValue(64);
2209
121k
    if ((TV > 63) || (mask & (1ULL << TV)) == 0)
2210
0
      return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
2211
0
             << TheCall->getArg(ImmArg)->getSourceRange();
2212
363k
  }
2213
2214
363k
  if (PtrArgNum >= 0) {
2215
    // Check that pointer arguments have the specified type.
2216
1.46k
    Expr *Arg = TheCall->getArg(PtrArgNum);
2217
1.46k
    if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
2218
1.46k
      Arg = ICE->getSubExpr();
2219
1.46k
    ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
2220
1.46k
    QualType RHSTy = RHS.get()->getType();
2221
2222
1.46k
    llvm::Triple::ArchType Arch = TI.getTriple().getArch();
2223
1.46k
    bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
2224
546
                          Arch == llvm::Triple::aarch64_32 ||
2225
546
                          Arch == llvm::Triple::aarch64_be;
2226
1.46k
    bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong;
2227
1.46k
    QualType EltTy =
2228
1.46k
        getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
2229
1.46k
    if (HasConstPtr)
2230
824
      EltTy = EltTy.withConst();
2231
1.46k
    QualType LHSTy = Context.getPointerType(EltTy);
2232
1.46k
    AssignConvertType ConvTy;
2233
1.46k
    ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
2234
1.46k
    if (RHS.isInvalid())
2235
0
      return true;
2236
1.46k
    if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
2237
1.46k
                                 RHS.get(), AA_Assigning))
2238
0
      return true;
2239
363k
  }
2240
2241
  // For NEON intrinsics which take an immediate value as part of the
2242
  // instruction, range check them here.
2243
363k
  unsigned i = 0, l = 0, u = 0;
2244
363k
  switch (BuiltinID) {
2245
359k
  default:
2246
359k
    return false;
2247
0
  #define GET_NEON_IMMEDIATE_CHECK
2248
359k
  #include "clang/Basic/arm_neon.inc"
2249
0
  #include "clang/Basic/arm_fp16.inc"
2250
363k
  #undef GET_NEON_IMMEDIATE_CHECK
2251
363k
  }
2252
2253
3.60k
  return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2254
363k
}
2255
2256
36.3k
bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2257
36.3k
  switch (BuiltinID) {
2258
35.2k
  default:
2259
35.2k
    return false;
2260
78
  #include "clang/Basic/arm_mve_builtin_sema.inc"
2261
36.3k
  }
2262
36.3k
}
2263
2264
bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2265
36.2k
                                       CallExpr *TheCall) {
2266
36.2k
  bool Err = false;
2267
36.2k
  switch (BuiltinID) {
2268
36.0k
  default:
2269
36.0k
    return false;
2270
12
#include "clang/Basic/arm_cde_builtin_sema.inc"
2271
36.2k
  }
2272
2273
120
  if (Err)
2274
67
    return true;
2275
2276
53
  return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true);
2277
53
}
2278
2279
bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI,
2280
113
                                        const Expr *CoprocArg, bool WantCDE) {
2281
113
  if (isConstantEvaluated())
2282
0
    return false;
2283
2284
  // We can't check the value of a dependent argument.
2285
113
  if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent())
2286
0
    return false;
2287
2288
113
  llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context);
2289
113
  int64_t CoprocNo = CoprocNoAP.getExtValue();
2290
113
  assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative");
2291
2292
113
  uint32_t CDECoprocMask = TI.getARMCDECoprocMask();
2293
113
  bool IsCDECoproc = CoprocNo <= 7 && 
(CDECoprocMask & (1 << CoprocNo))97
;
2294
2295
113
  if (IsCDECoproc != WantCDE)
2296
19
    return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc)
2297
19
           << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange();
2298
2299
94
  return false;
2300
94
}
2301
2302
bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
2303
233
                                        unsigned MaxWidth) {
2304
233
  assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
2305
233
          BuiltinID == ARM::BI__builtin_arm_ldaex ||
2306
233
          BuiltinID == ARM::BI__builtin_arm_strex ||
2307
233
          BuiltinID == ARM::BI__builtin_arm_stlex ||
2308
233
          BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2309
233
          BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2310
233
          BuiltinID == AArch64::BI__builtin_arm_strex ||
2311
233
          BuiltinID == AArch64::BI__builtin_arm_stlex) &&
2312
233
         "unexpected ARM builtin");
2313
233
  bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
2314
199
                 BuiltinID == ARM::BI__builtin_arm_ldaex ||
2315
176
                 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2316
141
                 BuiltinID == AArch64::BI__builtin_arm_ldaex;
2317
2318
233
  DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2319
2320
  // Ensure that we have the proper number of arguments.
2321
233
  if (checkArgCount(*this, TheCall, IsLdrex ? 
1116
:
2117
))
2322
16
    return true;
2323
2324
  // Inspect the pointer argument of the atomic builtin.  This should always be
2325
  // a pointer type, whose element is an integral scalar or pointer type.
2326
  // Because it is a pointer type, we don't have to worry about any implicit
2327
  // casts here.
2328
217
  Expr *PointerArg = TheCall->getArg(IsLdrex ? 
0108
:
1109
);
2329
217
  ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
2330
217
  if (PointerArgRes.isInvalid())
2331
0
    return true;
2332
217
  PointerArg = PointerArgRes.get();
2333
2334
217
  const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2335
217
  if (!pointerType) {
2336
0
    Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
2337
0
        << PointerArg->getType() << PointerArg->getSourceRange();
2338
0
    return true;
2339
0
  }
2340
2341
  // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
2342
  // task is to insert the appropriate casts into the AST. First work out just
2343
  // what the appropriate type is.
2344
217
  QualType ValType = pointerType->getPointeeType();
2345
217
  QualType AddrType = ValType.getUnqualifiedType().withVolatile();
2346
217
  if (IsLdrex)
2347
108
    AddrType.addConst();
2348
2349
  // Issue a warning if the cast is dodgy.
2350
217
  CastKind CastNeeded = CK_NoOp;
2351
217
  if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
2352
4
    CastNeeded = CK_BitCast;
2353
4
    Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
2354
4
        << PointerArg->getType() << Context.getPointerType(AddrType)
2355
4
        << AA_Passing << PointerArg->getSourceRange();
2356
4
  }
2357
2358
  // Finally, do the cast and replace the argument with the corrected version.
2359
217
  AddrType = Context.getPointerType(AddrType);
2360
217
  PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
2361
217
  if (PointerArgRes.isInvalid())
2362
0
    return true;
2363
217
  PointerArg = PointerArgRes.get();
2364
2365
109
  TheCall->setArg(IsLdrex ? 
0108
: 1, PointerArg);
2366
2367
  // In general, we allow ints, floats and pointers to be loaded and stored.
2368
217
  if (!ValType->isIntegerType() && 
!ValType->isAnyPointerType()72
&&
2369
40
      !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
2370
8
    Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
2371
8
        << PointerArg->getType() << PointerArg->getSourceRange();
2372
8
    return true;
2373
8
  }
2374
2375
  // But ARM doesn't have instructions to deal with 128-bit versions.
2376
209
  if (Context.getTypeSize(ValType) > MaxWidth) {
2377
4
    assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
2378
4
    Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
2379
4
        << PointerArg->getType() << PointerArg->getSourceRange();
2380
4
    return true;
2381
4
  }
2382
2383
205
  switch (ValType.getObjCLifetime()) {
2384
205
  case Qualifiers::OCL_None:
2385
205
  case Qualifiers::OCL_ExplicitNone:
2386
    // okay
2387
205
    break;
2388
2389
0
  case Qualifiers::OCL_Weak:
2390
0
  case Qualifiers::OCL_Strong:
2391
0
  case Qualifiers::OCL_Autoreleasing:
2392
0
    Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
2393
0
        << ValType << PointerArg->getSourceRange();
2394
0
    return true;
2395
205
  }
2396
2397
205
  if (IsLdrex) {
2398
102
    TheCall->setType(ValType);
2399
102
    return false;
2400
102
  }
2401
2402
  // Initialize the argument to be stored.
2403
103
  ExprResult ValArg = TheCall->getArg(0);
2404
103
  InitializedEntity Entity = InitializedEntity::InitializeParameter(
2405
103
      Context, ValType, /*consume*/ false);
2406
103
  ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2407
103
  if (ValArg.isInvalid())
2408
4
    return true;
2409
99
  TheCall->setArg(0, ValArg.get());
2410
2411
  // __builtin_arm_strex always returns an int. It's marked as such in the .def,
2412
  // but the custom checker bypasses all default analysis.
2413
99
  TheCall->setType(Context.IntTy);
2414
99
  return false;
2415
99
}
2416
2417
bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2418
36.5k
                                       CallExpr *TheCall) {
2419
36.5k
  if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
2420
36.4k
      BuiltinID == ARM::BI__builtin_arm_ldaex ||
2421
36.4k
      BuiltinID == ARM::BI__builtin_arm_strex ||
2422
36.4k
      BuiltinID == ARM::BI__builtin_arm_stlex) {
2423
115
    return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
2424
115
  }
2425
2426
36.3k
  if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
2427
8
    return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2428
5
      SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
2429
8
  }
2430
2431
36.3k
  if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
2432
36.3k
      BuiltinID == ARM::BI__builtin_arm_wsr64)
2433
11
    return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
2434
2435
36.3k
  if (BuiltinID == ARM::BI__builtin_arm_rsr ||
2436
36.3k
      BuiltinID == ARM::BI__builtin_arm_rsrp ||
2437
36.3k
      BuiltinID == ARM::BI__builtin_arm_wsr ||
2438
36.3k
      BuiltinID == ARM::BI__builtin_arm_wsrp)
2439
22
    return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2440
2441
36.3k
  if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2442
46
    return true;
2443
36.3k
  if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall))
2444
94
    return true;
2445
36.2k
  if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall))
2446
68
    return true;
2447
2448
  // For intrinsics which take an immediate value as part of the instruction,
2449
  // range check them here.
2450
  // FIXME: VFP Intrinsics should error if VFP not present.
2451
36.1k
  switch (BuiltinID) {
2452
36.0k
  default: return false;
2453
13
  case ARM::BI__builtin_arm_ssat:
2454
13
    return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
2455
11
  case ARM::BI__builtin_arm_usat:
2456
11
    return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
2457
8
  case ARM::BI__builtin_arm_ssat16:
2458
8
    return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
2459
6
  case ARM::BI__builtin_arm_usat16:
2460
6
    return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
2461
20
  case ARM::BI__builtin_arm_vcvtr_f:
2462
20
  case ARM::BI__builtin_arm_vcvtr_d:
2463
20
    return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
2464
20
  case ARM::BI__builtin_arm_dmb:
2465
20
  case ARM::BI__builtin_arm_dsb:
2466
20
  case ARM::BI__builtin_arm_isb:
2467
20
  case ARM::BI__builtin_arm_dbg:
2468
20
    return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
2469
60
  case ARM::BI__builtin_arm_cdp:
2470
60
  case ARM::BI__builtin_arm_cdp2:
2471
60
  case ARM::BI__builtin_arm_mcr:
2472
60
  case ARM::BI__builtin_arm_mcr2:
2473
60
  case ARM::BI__builtin_arm_mrc:
2474
60
  case ARM::BI__builtin_arm_mrc2:
2475
60
  case ARM::BI__builtin_arm_mcrr:
2476
60
  case ARM::BI__builtin_arm_mcrr2:
2477
60
  case ARM::BI__builtin_arm_mrrc:
2478
60
  case ARM::BI__builtin_arm_mrrc2:
2479
60
  case ARM::BI__builtin_arm_ldc:
2480
60
  case ARM::BI__builtin_arm_ldcl:
2481
60
  case ARM::BI__builtin_arm_ldc2:
2482
60
  case ARM::BI__builtin_arm_ldc2l:
2483
60
  case ARM::BI__builtin_arm_stc:
2484
60
  case ARM::BI__builtin_arm_stcl:
2485
60
  case ARM::BI__builtin_arm_stc2:
2486
60
  case ARM::BI__builtin_arm_stc2l:
2487
60
    return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) ||
2488
60
           CheckARMCoprocessorImmediate(TI, TheCall->getArg(0),
2489
60
                                        /*WantCDE*/ false);
2490
36.1k
  }
2491
36.1k
}
2492
2493
bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI,
2494
                                           unsigned BuiltinID,
2495
326k
                                           CallExpr *TheCall) {
2496
326k
  if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2497
326k
      BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2498
326k
      BuiltinID == AArch64::BI__builtin_arm_strex ||
2499
326k
      BuiltinID == AArch64::BI__builtin_arm_stlex) {
2500
118
    return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
2501
118
  }
2502
2503
326k
  if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
2504
20
    return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2505
18
      SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
2506
16
      SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
2507
14
      SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
2508
20
  }
2509
2510
326k
  if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
2511
326k
      BuiltinID == AArch64::BI__builtin_arm_wsr64)
2512
21
    return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2513
2514
  // Memory Tagging Extensions (MTE) Intrinsics
2515
326k
  if (BuiltinID == AArch64::BI__builtin_arm_irg ||
2516
326k
      BuiltinID == AArch64::BI__builtin_arm_addg ||
2517
326k
      BuiltinID == AArch64::BI__builtin_arm_gmi ||
2518
326k
      BuiltinID == AArch64::BI__builtin_arm_ldg ||
2519
326k
      BuiltinID == AArch64::BI__builtin_arm_stg ||
2520
326k
      BuiltinID == AArch64::BI__builtin_arm_subp) {
2521
54
    return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
2522
54
  }
2523
2524
326k
  if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
2525
326k
      BuiltinID == AArch64::BI__builtin_arm_rsrp ||
2526
326k
      BuiltinID == AArch64::BI__builtin_arm_wsr ||
2527
326k
      BuiltinID == AArch64::BI__builtin_arm_wsrp)
2528
34
    return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2529
2530
  // Only check the valid encoding range. Any constant in this range would be
2531
  // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
2532
  // an exception for incorrect registers. This matches MSVC behavior.
2533
326k
  if (BuiltinID == AArch64::BI_ReadStatusReg ||
2534
326k
      BuiltinID == AArch64::BI_WriteStatusReg)
2535
82
    return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
2536
2537
326k
  if (BuiltinID == AArch64::BI__getReg)
2538
4
    return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
2539
2540
326k
  if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2541
350
    return true;
2542
2543
326k
  if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall))
2544
1.29k
    return true;
2545
2546
  // For intrinsics which take an immediate value as part of the instruction,
2547
  // range check them here.
2548
325k
  unsigned i = 0, l = 0, u = 0;
2549
325k
  switch (BuiltinID) {
2550
324k
  default: return false;
2551
17
  case AArch64::BI__builtin_arm_dmb:
2552
17
  case AArch64::BI__builtin_arm_dsb:
2553
17
  case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
2554
6
  case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
2555
23
  }
2556
2557
23
  return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2558
23
}
2559
2560
15
static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) {
2561
15
  if (Arg->getType()->getAsPlaceholderType())
2562
0
    return false;
2563
2564
  // The first argument needs to be a record field access.
2565
  // If it is an array element access, we delay decision
2566
  // to BPF backend to check whether the access is a
2567
  // field access or not.
2568
15
  return (Arg->IgnoreParens()->getObjectKind() == OK_BitField ||
2569
10
          dyn_cast<MemberExpr>(Arg->IgnoreParens()) ||
2570
4
          dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens()));
2571
15
}
2572
2573
13
static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) {
2574
13
  QualType ArgType = Arg->getType();
2575
13
  if (ArgType->getAsPlaceholderType())
2576
0
    return false;
2577
2578
  // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type
2579
  // format:
2580
  //   1. __builtin_preserve_type_info(*(<type> *)0, flag);
2581
  //   2. <type> var;
2582
  //      __builtin_preserve_type_info(var, flag);
2583
13
  if (!dyn_cast<DeclRefExpr>(Arg->IgnoreParens()) &&
2584
7
      !dyn_cast<UnaryOperator>(Arg->IgnoreParens()))
2585
1
    return false;
2586
2587
  // Typedef type.
2588
12
  if (ArgType->getAs<TypedefType>())
2589
4
    return true;
2590
2591
  // Record type or Enum type.
2592
8
  const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2593
8
  if (const auto *RT = Ty->getAs<RecordType>()) {
2594
4
    if (!RT->getDecl()->getDeclName().isEmpty())
2595
4
      return true;
2596
4
  } else if (const auto *ET = Ty->getAs<EnumType>()) {
2597
4
    if (!ET->getDecl()->getDeclName().isEmpty())
2598
4
      return true;
2599
0
  }
2600
2601
0
  return false;
2602
0
}
2603
2604
8
static bool isValidBPFPreserveEnumValueArg(Expr *Arg) {
2605
8
  QualType ArgType = Arg->getType();
2606
8
  if (ArgType->getAsPlaceholderType())
2607
0
    return false;
2608
2609
  // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type
2610
  // format:
2611
  //   __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>,
2612
  //                                 flag);
2613
8
  const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens());
2614
8
  if (!UO)
2615
0
    return false;
2616
2617
8
  const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr());
2618
8
  if (!CE || CE->getCastKind() != CK_IntegralToPointer)
2619
1
    return false;
2620
2621
  // The integer must be from an EnumConstantDecl.
2622
7
  const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr());
2623
7
  if (!DR)
2624
0
    return false;
2625
2626
7
  const EnumConstantDecl *Enumerator =
2627
7
      dyn_cast<EnumConstantDecl>(DR->getDecl());
2628
7
  if (!Enumerator)
2629
0
    return false;
2630
2631
  // The type must be EnumType.
2632
7
  const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2633
7
  const auto *ET = Ty->getAs<EnumType>();
2634
7
  if (!ET)
2635
0
    return false;
2636
2637
  // The enum value must be supported.
2638
11
  
for (auto *EDI : ET->getDecl()->enumerators())7
{
2639
11
    if (EDI == Enumerator)
2640
6
      return true;
2641
11
  }
2642
2643
1
  return false;
2644
7
}
2645
2646
bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
2647
47
                                       CallExpr *TheCall) {
2648
47
  assert((BuiltinID == BPF::BI__builtin_preserve_field_info ||
2649
47
          BuiltinID == BPF::BI__builtin_btf_type_id ||
2650
47
          BuiltinID == BPF::BI__builtin_preserve_type_info ||
2651
47
          BuiltinID == BPF::BI__builtin_preserve_enum_value) &&
2652
47
         "unexpected BPF builtin");
2653
2654
47
  if (checkArgCount(*this, TheCall, 2))
2655
1
    return true;
2656
2657
  // The second argument needs to be a constant int
2658
46
  Expr *Arg = TheCall->getArg(1);
2659
46
  Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context);
2660
46
  diag::kind kind;
2661
46
  if (!Value) {
2662
3
    if (BuiltinID == BPF::BI__builtin_preserve_field_info)
2663
2
      kind = diag::err_preserve_field_info_not_const;
2664
1
    else if (BuiltinID == BPF::BI__builtin_btf_type_id)
2665
1
      kind = diag::err_btf_type_id_not_const;
2666
0
    else if (BuiltinID == BPF::BI__builtin_preserve_type_info)
2667
0
      kind = diag::err_preserve_type_info_not_const;
2668
0
    else
2669
0
      kind = diag::err_preserve_enum_value_not_const;
2670
3
    Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange();
2671
3
    return true;
2672
3
  }
2673
2674
  // The first argument
2675
43
  Arg = TheCall->getArg(0);
2676
43
  bool InvalidArg = false;
2677
43
  bool ReturnUnsignedInt = true;
2678
43
  if (BuiltinID == BPF::BI__builtin_preserve_field_info) {
2679
15
    if (!isValidBPFPreserveFieldInfoArg(Arg)) {
2680
2
      InvalidArg = true;
2681
2
      kind = diag::err_preserve_field_info_not_field;
2682
2
    }
2683
28
  } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) {
2684
13
    if (!isValidBPFPreserveTypeInfoArg(Arg)) {
2685
1
      InvalidArg = true;
2686
1
      kind = diag::err_preserve_type_info_invalid;
2687
1
    }
2688
15
  } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) {
2689
8
    if (!isValidBPFPreserveEnumValueArg(Arg)) {
2690
2
      InvalidArg = true;
2691
2
      kind = diag::err_preserve_enum_value_invalid;
2692
2
    }
2693
8
    ReturnUnsignedInt = false;
2694
8
  }
2695
2696
43
  if (InvalidArg) {
2697
5
    Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange();
2698
5
    return true;
2699
5
  }
2700
2701
38
  if (ReturnUnsignedInt)
2702
32
    TheCall->setType(Context.UnsignedIntTy);
2703
6
  else
2704
6
    TheCall->setType(Context.UnsignedLongTy);
2705
38
  return false;
2706
38
}
2707
2708
1.80k
bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2709
1.80k
  struct ArgInfo {
2710
1.80k
    uint8_t OpNum;
2711
1.80k
    bool IsSigned;
2712
1.80k
    uint8_t BitWidth;
2713
1.80k
    uint8_t Align;
2714
1.80k
  };
2715
1.80k
  struct BuiltinInfo {
2716
1.80k
    unsigned BuiltinID;
2717
1.80k
    ArgInfo Infos[2];
2718
1.80k
  };
2719
2720
1.80k
  static BuiltinInfo Infos[] = {
2721
1.80k
    { Hexagon::BI__builtin_circ_ldd,                  {{ 3, true,  4,  3 }} },
2722
1.80k
    { Hexagon::BI__builtin_circ_ldw,                  {{ 3, true,  4,  2 }} },
2723
1.80k
    { Hexagon::BI__builtin_circ_ldh,                  {{ 3, true,  4,  1 }} },
2724
1.80k
    { Hexagon::BI__builtin_circ_lduh,                 {{ 3, true,  4,  1 }} },
2725
1.80k
    { Hexagon::BI__builtin_circ_ldb,                  {{ 3, true,  4,  0 }} },
2726
1.80k
    { Hexagon::BI__builtin_circ_ldub,                 {{ 3, true,  4,  0 }} },
2727
1.80k
    { Hexagon::BI__builtin_circ_std,                  {{ 3, true,  4,  3 }} },
2728
1.80k
    { Hexagon::BI__builtin_circ_stw,                  {{ 3, true,  4,  2 }} },
2729
1.80k
    { Hexagon::BI__builtin_circ_sth,                  {{ 3, true,  4,  1 }} },
2730
1.80k
    { Hexagon::BI__builtin_circ_sthhi,                {{ 3, true,  4,  1 }} },
2731
1.80k
    { Hexagon::BI__builtin_circ_stb,                  {{ 3, true,  4,  0 }} },
2732
2733
1.80k
    { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci,    {{ 1, true,  4,  0 }} },
2734
1.80k
    { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci,     {{ 1, true,  4,  0 }} },
2735
1.80k
    { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci,    {{ 1, true,  4,  1 }} },
2736
1.80k
    { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci,     {{ 1, true,  4,  1 }} },
2737
1.80k
    { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci,     {{ 1, true,  4,  2 }} },
2738
1.80k
    { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci,     {{ 1, true,  4,  3 }} },
2739
1.80k
    { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci,    {{ 1, true,  4,  0 }} },
2740
1.80k
    { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci,    {{ 1, true,  4,  1 }} },
2741
1.80k
    { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci,    {{ 1, true,  4,  1 }} },
2742
1.80k
    { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci,    {{ 1, true,  4,  2 }} },
2743
1.80k
    { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci,    {{ 1, true,  4,  3 }} },
2744
2745
1.80k
    { Hexagon::BI__builtin_HEXAGON_A2_combineii,      {{ 1, true,  8,  0 }} },
2746
1.80k
    { Hexagon::BI__builtin_HEXAGON_A2_tfrih,          {{ 1, false, 16, 0 }} },
2747
1.80k
    { Hexagon::BI__builtin_HEXAGON_A2_tfril,          {{ 1, false, 16, 0 }} },
2748
1.80k
    { Hexagon::BI__builtin_HEXAGON_A2_tfrpi,          {{ 0, true,  8,  0 }} },
2749
1.80k
    { Hexagon::BI__builtin_HEXAGON_A4_bitspliti,      {{ 1, false, 5,  0 }} },
2750
1.80k
    { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi,        {{ 1, false, 8,  0 }} },
2751
1.80k
    { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti,        {{ 1, true,  8,  0 }} },
2752
1.80k
    { Hexagon::BI__builtin_HEXAGON_A4_cround_ri,      {{ 1, false, 5,  0 }} },
2753
1.80k
    { Hexagon::BI__builtin_HEXAGON_A4_round_ri,       {{ 1, false, 5,  0 }} },
2754
1.80k
    { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat,   {{ 1, false, 5,  0 }} },
2755
1.80k
    { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi,       {{ 1, false, 8,  0 }} },
2756
1.80k
    { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti,       {{ 1, true,  8,  0 }} },
2757
1.80k
    { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui,      {{ 1, false, 7,  0 }} },
2758
1.80k
    { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi,       {{ 1, true,  8,  0 }} },
2759
1.80k
    { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti,       {{ 1, true,  8,  0 }} },
2760
1.80k
    { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui,      {{ 1, false, 7,  0 }} },
2761
1.80k
    { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi,       {{ 1, true,  8,  0 }} },
2762
1.80k
    { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti,       {{ 1, true,  8,  0 }} },
2763
1.80k
    { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui,      {{ 1, false, 7,  0 }} },
2764
1.80k
    { Hexagon::BI__builtin_HEXAGON_C2_bitsclri,       {{ 1, false, 6,  0 }} },
2765
1.80k
    { Hexagon::BI__builtin_HEXAGON_C2_muxii,          {{ 2, true,  8,  0 }} },
2766
1.80k
    { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri,      {{ 1, false, 6,  0 }} },
2767
1.80k
    { Hexagon::BI__builtin_HEXAGON_F2_dfclass,        {{ 1, false, 5,  0 }} },
2768
1.80k
    { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n,        {{ 0, false, 10, 0 }} },
2769
1.80k
    { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p,        {{ 0, false, 10, 0 }} },
2770
1.80k
    { Hexagon::BI__builtin_HEXAGON_F2_sfclass,        {{ 1, false, 5,  0 }} },
2771
1.80k
    { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n,        {{ 0, false, 10, 0 }} },
2772
1.80k
    { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p,        {{ 0, false, 10, 0 }} },
2773
1.80k
    { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi,     {{ 2, false, 6,  0 }} },
2774
1.80k
    { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2,  {{ 1, false, 6,  2 }} },
2775
1.80k
    { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri,    {{ 2, false, 3,  0 }} },
2776
1.80k
    { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc,    {{ 2, false, 6,  0 }} },
2777
1.80k
    { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and,    {{ 2, false, 6,  0 }} },
2778
1.80k
    { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p,        {{ 1, false, 6,  0 }} },
2779
1.80k
    { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac,    {{ 2, false, 6,  0 }} },
2780
1.80k
    { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or,     {{ 2, false, 6,  0 }} },
2781
1.80k
    { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc,   {{ 2, false, 6,  0 }} },
2782
1.80k
    { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc,    {{ 2, false, 5,  0 }} },
2783
1.80k
    { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and,    {{ 2, false, 5,  0 }} },
2784
1.80k
    { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r,        {{ 1, false, 5,  0 }} },
2785
1.80k
    { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac,    {{ 2, false, 5,  0 }} },
2786
1.80k
    { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or,     {{ 2, false, 5,  0 }} },
2787
1.80k
    { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat,    {{ 1, false, 5,  0 }} },
2788
1.80k
    { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc,   {{ 2, false, 5,  0 }} },
2789
1.80k
    { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh,       {{ 1, false, 4,  0 }} },
2790
1.80k
    { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw,       {{ 1, false, 5,  0 }} },
2791
1.80k
    { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc,    {{ 2, false, 6,  0 }} },
2792
1.80k
    { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and,    {{ 2, false, 6,  0 }} },
2793
1.80k
    { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p,        {{ 1, false, 6,  0 }} },
2794
1.80k
    { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac,    {{ 2, false, 6,  0 }} },
2795
1.80k
    { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or,     {{ 2, false, 6,  0 }} },
2796
1.80k
    { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
2797
1.80k
                                                      {{ 1, false, 6,  0 }} },
2798
1.80k
    { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd,    {{ 1, false, 6,  0 }} },
2799
1.80k
    { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc,    {{ 2, false, 5,  0 }} },
2800
1.80k
    { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and,    {{ 2, false, 5,  0 }} },
2801
1.80k
    { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r,        {{ 1, false, 5,  0 }} },
2802
1.80k
    { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac,    {{ 2, false, 5,  0 }} },
2803
1.80k
    { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or,     {{ 2, false, 5,  0 }} },
2804
1.80k
    { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
2805
1.80k
                                                      {{ 1, false, 5,  0 }} },
2806
1.80k
    { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd,    {{ 1, false, 5,  0 }} },
2807
1.80k
    { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5,  0 }} },
2808
1.80k
    { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh,       {{ 1, false, 4,  0 }} },
2809
1.80k
    { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw,       {{ 1, false, 5,  0 }} },
2810
1.80k
    { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i,       {{ 1, false, 5,  0 }} },
2811
1.80k
    { Hexagon::BI__builtin_HEXAGON_S2_extractu,       {{ 1, false, 5,  0 },
2812
1.80k
                                                       { 2, false, 5,  0 }} },
2813
1.80k
    { Hexagon::BI__builtin_HEXAGON_S2_extractup,      {{ 1, false, 6,  0 },
2814
1.80k
                                                       { 2, false, 6,  0 }} },
2815
1.80k
    { Hexagon::BI__builtin_HEXAGON_S2_insert,         {{ 2, false, 5,  0 },
2816
1.80k
                                                       { 3, false, 5,  0 }} },
2817
1.80k
    { Hexagon::BI__builtin_HEXAGON_S2_insertp,        {{ 2, false, 6,  0 },
2818
1.80k
                                                       { 3, false, 6,  0 }} },
2819
1.80k
    { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc,    {{ 2, false, 6,  0 }} },
2820
1.80k
    { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and,    {{ 2, false, 6,  0 }} },
2821
1.80k
    { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p,        {{ 1, false, 6,  0 }} },
2822
1.80k
    { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac,    {{ 2, false, 6,  0 }} },
2823
1.80k
    { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or,     {{ 2, false, 6,  0 }} },
2824
1.80k
    { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc,   {{ 2, false, 6,  0 }} },
2825
1.80k
    { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc,    {{ 2, false, 5,  0 }} },
2826
1.80k
    { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and,    {{ 2, false, 5,  0 }} },
2827
1.80k
    { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r,        {{ 1, false, 5,  0 }} },
2828
1.80k
    { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac,    {{ 2, false, 5,  0 }} },
2829
1.80k
    { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or,     {{ 2, false, 5,  0 }} },
2830
1.80k
    { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc,   {{ 2, false, 5,  0 }} },
2831
1.80k
    { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh,       {{ 1, false, 4,  0 }} },
2832
1.80k
    { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw,       {{ 1, false, 5,  0 }} },
2833
1.80k
    { Hexagon::BI__builtin_HEXAGON_S2_setbit_i,       {{ 1, false, 5,  0 }} },
2834
1.80k
    { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
2835
1.80k
                                                      {{ 2, false, 4,  0 },
2836
1.80k
                                                       { 3, false, 5,  0 }} },
2837
1.80k
    { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
2838
1.80k
                                                      {{ 2, false, 4,  0 },
2839
1.80k
                                                       { 3, false, 5,  0 }} },
2840
1.80k
    { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
2841
1.80k
                                                      {{ 2, false, 4,  0 },
2842
1.80k
                                                       { 3, false, 5,  0 }} },
2843
1.80k
    { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
2844
1.80k
                                                      {{ 2, false, 4,  0 },
2845
1.80k
                                                       { 3, false, 5,  0 }} },
2846
1.80k
    { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i,    {{ 1, false, 5,  0 }} },
2847
1.80k
    { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i,       {{ 1, false, 5,  0 }} },
2848
1.80k
    { Hexagon::BI__builtin_HEXAGON_S2_valignib,       {{ 2, false, 3,  0 }} },
2849
1.80k
    { Hexagon::BI__builtin_HEXAGON_S2_vspliceib,      {{ 2, false, 3,  0 }} },
2850
1.80k
    { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri,    {{ 2, false, 5,  0 }} },
2851
1.80k
    { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri,    {{ 2, false, 5,  0 }} },
2852
1.80k
    { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri,    {{ 2, false, 5,  0 }} },
2853
1.80k
    { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri,    {{ 2, false, 5,  0 }} },
2854
1.80k
    { Hexagon::BI__builtin_HEXAGON_S4_clbaddi,        {{ 1, true , 6,  0 }} },
2855
1.80k
    { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi,       {{ 1, true,  6,  0 }} },
2856
1.80k
    { Hexagon::BI__builtin_HEXAGON_S4_extract,        {{ 1, false, 5,  0 },
2857
1.80k
                                                       { 2, false, 5,  0 }} },
2858
1.80k
    { Hexagon::BI__builtin_HEXAGON_S4_extractp,       {{ 1, false, 6,  0 },
2859
1.80k
                                                       { 2, false, 6,  0 }} },
2860
1.80k
    { Hexagon::BI__builtin_HEXAGON_S4_lsli,           {{ 0, true,  6,  0 }} },
2861
1.80k
    { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i,      {{ 1, false, 5,  0 }} },
2862
1.80k
    { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri,     {{ 2, false, 5,  0 }} },
2863
1.80k
    { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri,     {{ 2, false, 5,  0 }} },
2864
1.80k
    { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri,    {{ 2, false, 5,  0 }} },
2865
1.80k
    { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri,    {{ 2, false, 5,  0 }} },
2866
1.80k
    { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc,  {{ 3, false, 2,  0 }} },
2867
1.80k
    { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate,      {{ 2, false, 2,  0 }} },
2868
1.80k
    { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
2869
1.80k
                                                      {{ 1, false, 4,  0 }} },
2870
1.80k
    { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat,     {{ 1, false, 4,  0 }} },
2871
1.80k
    { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
2872
1.80k
                                                      {{ 1, false, 4,  0 }} },
2873
1.80k
    { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p,        {{ 1, false, 6,  0 }} },
2874
1.80k
    { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc,    {{ 2, false, 6,  0 }} },
2875
1.80k
    { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and,    {{ 2, false, 6,  0 }} },
2876
1.80k
    { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac,    {{ 2, false, 6,  0 }} },
2877
1.80k
    { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or,     {{ 2, false, 6,  0 }} },
2878
1.80k
    { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc,   {{ 2, false, 6,  0 }} },
2879
1.80k
    { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r,        {{ 1, false, 5,  0 }} },
2880
1.80k
    { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc,    {{ 2, false, 5,  0 }} },
2881
1.80k
    { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and,    {{ 2, false, 5,  0 }} },
2882
1.80k
    { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac,    {{ 2, false, 5,  0 }} },
2883
1.80k
    { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or,     {{ 2, false, 5,  0 }} },
2884
1.80k
    { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc,   {{ 2, false, 5,  0 }} },
2885
1.80k
    { Hexagon::BI__builtin_HEXAGON_V6_valignbi,       {{ 2, false, 3,  0 }} },
2886
1.80k
    { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B,  {{ 2, false, 3,  0 }} },
2887
1.80k
    { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi,      {{ 2, false, 3,  0 }} },
2888
1.80k
    { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3,  0 }} },
2889
1.80k
    { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi,      {{ 2, false, 1,  0 }} },
2890
1.80k
    { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1,  0 }} },
2891
1.80k
    { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc,  {{ 3, false, 1,  0 }} },
2892
1.80k
    { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
2893
1.80k
                                                      {{ 3, false, 1,  0 }} },
2894
1.80k
    { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi,       {{ 2, false, 1,  0 }} },
2895
1.80k
    { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B,  {{ 2, false, 1,  0 }} },
2896
1.80k
    { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc,   {{ 3, false, 1,  0 }} },
2897
1.80k
    { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
2898
1.80k
                                                      {{ 3, false, 1,  0 }} },
2899
1.80k
    { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi,       {{ 2, false, 1,  0 }} },
2900
1.80k
    { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B,  {{ 2, false, 1,  0 }} },
2901
1.80k
    { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc,   {{ 3, false, 1,  0 }} },
2902
1.80k
    { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
2903
1.80k
                                                      {{ 3, false, 1,  0 }} },
2904
1.80k
  };
2905
2906
  // Use a dynamically initialized static to sort the table exactly once on
2907
  // first run.
2908
1.80k
  static const bool SortOnce =
2909
1.80k
      (llvm::sort(Infos,
2910
36.5k
                 [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
2911
36.5k
                   return LHS.BuiltinID < RHS.BuiltinID;
2912
36.5k
                 }),
2913
1.80k
       true);
2914
1.80k
  (void)SortOnce;
2915
2916
1.80k
  const BuiltinInfo *F = llvm::partition_point(
2917
13.0k
      Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
2918
1.80k
  if (F == std::end(Infos) || 
F->BuiltinID != BuiltinID1.14k
)
2919
1.63k
    return false;
2920
2921
174
  bool Error = false;
2922
2923
348
  for (const ArgInfo &A : F->Infos) {
2924
    // Ignore empty ArgInfo elements.
2925
348
    if (A.BitWidth == 0)
2926
159
      continue;
2927
2928
189
    int32_t Min = A.IsSigned ? 
-(1 << (A.BitWidth - 1))39
:
0150
;
2929
150
    int32_t Max = (1 << (A.IsSigned ? 
A.BitWidth - 139
: A.BitWidth)) - 1;
2930
189
    if (!A.Align) {
2931
167
      Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
2932
22
    } else {
2933
22
      unsigned M = 1 << A.Align;
2934
22
      Min *= M;
2935
22
      Max *= M;
2936
22
      Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
2937
22
               SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
2938
22
    }
2939
189
  }
2940
174
  return Error;
2941
174
}
2942
2943
bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
2944
1.80k
                                           CallExpr *TheCall) {
2945
1.80k
  return CheckHexagonBuiltinArgument(BuiltinID, TheCall);
2946
1.80k
}
2947
2948
bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI,
2949
1.05k
                                        unsigned BuiltinID, CallExpr *TheCall) {
2950
1.05k
  return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) ||
2951
1.04k
         CheckMipsBuiltinArgument(BuiltinID, TheCall);
2952
1.05k
}
2953
2954
bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID,
2955
1.05k
                               CallExpr *TheCall) {
2956
2957
1.05k
  if (Mips::BI__builtin_mips_addu_qb <= BuiltinID &&
2958
1.05k
      BuiltinID <= Mips::BI__builtin_mips_lwx) {
2959
102
    if (!TI.hasFeature("dsp"))
2960
2
      return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp);
2961
1.04k
  }
2962
2963
1.04k
  if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID &&
2964
949
      BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) {
2965
58
    if (!TI.hasFeature("dspr2"))
2966
2
      return Diag(TheCall->getBeginLoc(),
2967
2
                  diag::err_mips_builtin_requires_dspr2);
2968
1.04k
  }
2969
2970
1.04k
  if (Mips::BI__builtin_msa_add_a_b <= BuiltinID &&
2971
891
      BuiltinID <= Mips::BI__builtin_msa_xori_b) {
2972
891
    if (!TI.hasFeature("msa"))
2973
2
      return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa);
2974
1.04k
  }
2975
2976
1.04k
  return false;
2977
1.04k
}
2978
2979
// CheckMipsBuiltinArgument - Checks the constant value passed to the
2980
// intrinsic is correct. The switch statement is ordered by DSP, MSA. The
2981
// ordering for DSP is unspecified. MSA is ordered by the data format used
2982
// by the underlying instruction i.e., df/m, df/n and then by size.
2983
//
2984
// FIXME: The size tests here should instead be tablegen'd along with the
2985
//        definitions from include/clang/Basic/BuiltinsMips.def.
2986
// FIXME: GCC is strict on signedness for some of these intrinsics, we should
2987
//        be too.
2988
1.04k
bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2989
1.04k
  unsigned i = 0, l = 0, u = 0, m = 0;
2990
1.04k
  switch (BuiltinID) {
2991
556
  default: return false;
2992
5
  case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
2993
3
  case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
2994
3
  case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
2995
3
  case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
2996
3
  case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
2997
3
  case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
2998
3
  case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
2999
  // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
3000
  // df/m field.
3001
  // These intrinsics take an unsigned 3 bit immediate.
3002
30
  case Mips::BI__builtin_msa_bclri_b:
3003
30
  case Mips::BI__builtin_msa_bnegi_b:
3004
30
  case Mips::BI__builtin_msa_bseti_b:
3005
30
  case Mips::BI__builtin_msa_sat_s_b:
3006
30
  case Mips::BI__builtin_msa_sat_u_b:
3007
30
  case Mips::BI__builtin_msa_slli_b:
3008
30
  case Mips::BI__builtin_msa_srai_b:
3009
30
  case Mips::BI__builtin_msa_srari_b:
3010
30
  case Mips::BI__builtin_msa_srli_b:
3011
30
  case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
3012
6
  case Mips::BI__builtin_msa_binsli_b:
3013
6
  case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
3014
  // These intrinsics take an unsigned 4 bit immediate.
3015
30
  case Mips::BI__builtin_msa_bclri_h:
3016
30
  case Mips::BI__builtin_msa_bnegi_h:
3017
30
  case Mips::BI__builtin_msa_bseti_h:
3018
30
  case Mips::BI__builtin_msa_sat_s_h:
3019
30
  case Mips::BI__builtin_msa_sat_u_h:
3020
30
  case Mips::BI__builtin_msa_slli_h:
3021
30
  case Mips::BI__builtin_msa_srai_h:
3022
30
  case Mips::BI__builtin_msa_srari_h:
3023
30
  case Mips::BI__builtin_msa_srli_h:
3024
30
  case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
3025
6
  case Mips::BI__builtin_msa_binsli_h:
3026
6
  case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
3027
  // These intrinsics take an unsigned 5 bit immediate.
3028
  // The first block of intrinsics actually have an unsigned 5 bit field,
3029
  // not a df/n field.
3030
4
  case Mips::BI__builtin_msa_cfcmsa:
3031
4
  case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
3032
106
  case Mips::BI__builtin_msa_clei_u_b:
3033
106
  case Mips::BI__builtin_msa_clei_u_h:
3034
106
  case Mips::BI__builtin_msa_clei_u_w:
3035
106
  case Mips::BI__builtin_msa_clei_u_d:
3036
106
  case Mips::BI__builtin_msa_clti_u_b:
3037
106
  case Mips::BI__builtin_msa_clti_u_h:
3038
106
  case Mips::BI__builtin_msa_clti_u_w:
3039
106
  case Mips::BI__builtin_msa_clti_u_d:
3040
106
  case Mips::BI__builtin_msa_maxi_u_b:
3041
106
  case Mips::BI__builtin_msa_maxi_u_h:
3042
106
  case Mips::BI__builtin_msa_maxi_u_w:
3043
106
  case Mips::BI__builtin_msa_maxi_u_d:
3044
106
  case Mips::BI__builtin_msa_mini_u_b:
3045
106
  case Mips::BI__builtin_msa_mini_u_h:
3046
106
  case Mips::BI__builtin_msa_mini_u_w:
3047
106
  case Mips::BI__builtin_msa_mini_u_d:
3048
106
  case Mips::BI__builtin_msa_addvi_b:
3049
106
  case Mips::BI__builtin_msa_addvi_h:
3050
106
  case Mips::BI__builtin_msa_addvi_w:
3051
106
  case Mips::BI__builtin_msa_addvi_d:
3052
106
  case Mips::BI__builtin_msa_bclri_w:
3053
106
  case Mips::BI__builtin_msa_bnegi_w:
3054
106
  case Mips::BI__builtin_msa_bseti_w:
3055
106
  case Mips::BI__builtin_msa_sat_s_w:
3056
106
  case Mips::BI__builtin_msa_sat_u_w:
3057
106
  case Mips::BI__builtin_msa_slli_w:
3058
106
  case Mips::BI__builtin_msa_srai_w:
3059
106
  case Mips::BI__builtin_msa_srari_w:
3060
106
  case Mips::BI__builtin_msa_srli_w:
3061
106
  case Mips::BI__builtin_msa_srlri_w:
3062
106
  case Mips::BI__builtin_msa_subvi_b:
3063
106
  case Mips::BI__builtin_msa_subvi_h:
3064
106
  case Mips::BI__builtin_msa_subvi_w:
3065
106
  case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
3066
6
  case Mips::BI__builtin_msa_binsli_w:
3067
6
  case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
3068
  // These intrinsics take an unsigned 6 bit immediate.
3069
30
  case Mips::BI__builtin_msa_bclri_d:
3070
30
  case Mips::BI__builtin_msa_bnegi_d:
3071
30
  case Mips::BI__builtin_msa_bseti_d:
3072
30
  case Mips::BI__builtin_msa_sat_s_d:
3073
30
  case Mips::BI__builtin_msa_sat_u_d:
3074
30
  case Mips::BI__builtin_msa_slli_d:
3075
30
  case Mips::BI__builtin_msa_srai_d:
3076
30
  case Mips::BI__builtin_msa_srari_d:
3077
30
  case Mips::BI__builtin_msa_srli_d:
3078
30
  case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
3079
6
  case Mips::BI__builtin_msa_binsli_d:
3080
6
  case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
3081
  // These intrinsics take a signed 5 bit immediate.
3082
60
  case Mips::BI__builtin_msa_ceqi_b:
3083
60
  case Mips::BI__builtin_msa_ceqi_h:
3084
60
  case Mips::BI__builtin_msa_ceqi_w:
3085
60
  case Mips::BI__builtin_msa_ceqi_d:
3086
60
  case Mips::BI__builtin_msa_clti_s_b:
3087
60
  case Mips::BI__builtin_msa_clti_s_h:
3088
60
  case Mips::BI__builtin_msa_clti_s_w:
3089
60
  case Mips::BI__builtin_msa_clti_s_d:
3090
60
  case Mips::BI__builtin_msa_clei_s_b:
3091
60
  case Mips::BI__builtin_msa_clei_s_h:
3092
60
  case Mips::BI__builtin_msa_clei_s_w:
3093
60
  case Mips::BI__builtin_msa_clei_s_d:
3094
60
  case Mips::BI__builtin_msa_maxi_s_b:
3095
60
  case Mips::BI__builtin_msa_maxi_s_h:
3096
60
  case Mips::BI__builtin_msa_maxi_s_w:
3097
60
  case Mips::BI__builtin_msa_maxi_s_d:
3098
60
  case Mips::BI__builtin_msa_mini_s_b:
3099
60
  case Mips::BI__builtin_msa_mini_s_h:
3100
60
  case Mips::BI__builtin_msa_mini_s_w:
3101
60
  case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
3102
  // These intrinsics take an unsigned 8 bit immediate.
3103
69
  case Mips::BI__builtin_msa_andi_b:
3104
69
  case Mips::BI__builtin_msa_nori_b:
3105
69
  case Mips::BI__builtin_msa_ori_b:
3106
69
  case Mips::BI__builtin_msa_shf_b:
3107
69
  case Mips::BI__builtin_msa_shf_h:
3108
69
  case Mips::BI__builtin_msa_shf_w:
3109
69
  case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
3110
9
  case Mips::BI__builtin_msa_bseli_b:
3111
9
  case Mips::BI__builtin_msa_bmnzi_b:
3112
9
  case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
3113
  // df/n format
3114
  // These intrinsics take an unsigned 4 bit immediate.
3115
12
  case Mips::BI__builtin_msa_copy_s_b:
3116
12
  case Mips::BI__builtin_msa_copy_u_b:
3117
12
  case Mips::BI__builtin_msa_insve_b:
3118
12
  case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
3119
3
  case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
3120
  // These intrinsics take an unsigned 3 bit immediate.
3121
12
  case Mips::BI__builtin_msa_copy_s_h:
3122
12
  case Mips::BI__builtin_msa_copy_u_h:
3123
12
  case Mips::BI__builtin_msa_insve_h:
3124
12
  case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
3125
3
  case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
3126
  // These intrinsics take an unsigned 2 bit immediate.
3127
12
  case Mips::BI__builtin_msa_copy_s_w:
3128
12
  case Mips::BI__builtin_msa_copy_u_w:
3129
12
  case Mips::BI__builtin_msa_insve_w:
3130
12
  case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
3131
3
  case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
3132
  // These intrinsics take an unsigned 1 bit immediate.
3133
12
  case Mips::BI__builtin_msa_copy_s_d:
3134
12
  case Mips::BI__builtin_msa_copy_u_d:
3135
12
  case Mips::BI__builtin_msa_insve_d:
3136
12
  case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
3137
3
  case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
3138
  // Memory offsets and immediate loads.
3139
  // These intrinsics take a signed 10 bit immediate.
3140
5
  case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
3141
9
  case Mips::BI__builtin_msa_ldi_h:
3142
9
  case Mips::BI__builtin_msa_ldi_w:
3143
9
  case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
3144
3
  case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
3145
4
  case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
3146
4
  case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
3147
4
  case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
3148
0
  case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break;
3149
0
  case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break;
3150
3
  case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
3151
4
  case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
3152
4
  case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
3153
4
  case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
3154
0
  case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break;
3155
0
  case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break;
3156
489
  }
3157
3158
489
  if (!m)
3159
459
    return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3160
3161
30
  return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
3162
14
         SemaBuiltinConstantArgMultiple(TheCall, i, m);
3163
30
}
3164
3165
bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3166
75.8k
                                       CallExpr *TheCall) {
3167
75.8k
  unsigned i = 0, l = 0, u = 0;
3168
75.8k
  bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
3169
75.8k
                      BuiltinID == PPC::BI__builtin_divdeu ||
3170
75.8k
                      BuiltinID == PPC::BI__builtin_bpermd;
3171
75.8k
  bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64;
3172
75.8k
  bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
3173
75.8k
                       BuiltinID == PPC::BI__builtin_divweu ||
3174
75.8k
                       BuiltinID == PPC::BI__builtin_divde ||
3175
75.8k
                       BuiltinID == PPC::BI__builtin_divdeu;
3176
3177
75.8k
  if (Is64BitBltin && 
!IsTarget64Bit25
)
3178
3
    return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3179
3
           << TheCall->getSourceRange();
3180
3181
75.8k
  if ((IsBltinExtDiv && 
!TI.hasFeature("extdiv")14
) ||
3182
75.8k
      (BuiltinID == PPC::BI__builtin_bpermd && 
!TI.hasFeature("bpermd")16
))
3183
5
    return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3184
5
           << TheCall->getSourceRange();
3185
3186
75.8k
  auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool {
3187
16
    if (!TI.hasFeature("vsx"))
3188
2
      return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3189
2
             << TheCall->getSourceRange();
3190
14
    return false;
3191
14
  };
3192
3193
75.8k
  switch (BuiltinID) {
3194
75.4k
  default: return false;
3195
22
  case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3196
22
  case PPC::BI__builtin_altivec_crypto_vshasigmad:
3197
22
    return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3198
18
           SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3199
7
  case PPC::BI__builtin_altivec_dss:
3200
7
    return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
3201
11
  case PPC::BI__builtin_tbegin:
3202
11
  case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
3203
2
  case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
3204
4
  case PPC::BI__builtin_tabortwc:
3205
4
  case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
3206
6
  case PPC::BI__builtin_tabortwci:
3207
6
  case PPC::BI__builtin_tabortdci:
3208
6
    return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3209
4
           SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
3210
24
  case PPC::BI__builtin_altivec_dst:
3211
24
  case PPC::BI__builtin_altivec_dstt:
3212
24
  case PPC::BI__builtin_altivec_dstst:
3213
24
  case PPC::BI__builtin_altivec_dststt:
3214
24
    return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
3215
134
  case PPC::BI__builtin_vsx_xxpermdi:
3216
134
  case PPC::BI__builtin_vsx_xxsldwi:
3217
134
    return SemaBuiltinVSX(TheCall);
3218
12
  case PPC::BI__builtin_unpack_vector_int128:
3219
12
    return SemaVSXCheck(TheCall) ||
3220
11
           SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3221
4
  case PPC::BI__builtin_pack_vector_int128:
3222
4
    return SemaVSXCheck(TheCall);
3223
6
  case PPC::BI__builtin_altivec_vgnb:
3224
6
     return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7);
3225
50
  case PPC::BI__builtin_vsx_xxeval:
3226
50
     return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255);
3227
16
  case PPC::BI__builtin_altivec_vsldbi:
3228
16
     return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3229
16
  case PPC::BI__builtin_altivec_vsrdbi:
3230
16
     return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3231
20
  case PPC::BI__builtin_vsx_xxpermx:
3232
20
     return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7);
3233
17
  }
3234
17
  return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3235
17
}
3236
3237
bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID,
3238
439
                                          CallExpr *TheCall) {
3239
  // position of memory order and scope arguments in the builtin
3240
439
  unsigned OrderIndex, ScopeIndex;
3241
439
  switch (BuiltinID) {
3242
64
  case AMDGPU::BI__builtin_amdgcn_atomic_inc32:
3243
64
  case AMDGPU::BI__builtin_amdgcn_atomic_inc64:
3244
64
  case AMDGPU::BI__builtin_amdgcn_atomic_dec32:
3245
64
  case AMDGPU::BI__builtin_amdgcn_atomic_dec64:
3246
64
    OrderIndex = 2;
3247
64
    ScopeIndex = 3;
3248
64
    break;
3249
11
  case AMDGPU::BI__builtin_amdgcn_fence:
3250
11
    OrderIndex = 0;
3251
11
    ScopeIndex = 1;
3252
11
    break;
3253
364
  default:
3254
364
    return false;
3255
75
  }
3256
3257
75
  ExprResult Arg = TheCall->getArg(OrderIndex);
3258
75
  auto ArgExpr = Arg.get();
3259
75
  Expr::EvalResult ArgResult;
3260
3261
75
  if (!ArgExpr->EvaluateAsInt(ArgResult, Context))
3262
0
    return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int)
3263
0
           << ArgExpr->getType();
3264
75
  int ord = ArgResult.Val.getInt().getZExtValue();
3265
3266
  // Check valididty of memory ordering as per C11 / C++11's memody model.
3267
75
  switch (static_cast<llvm::AtomicOrderingCABI>(ord)) {
3268
65
  case llvm::AtomicOrderingCABI::acquire:
3269
65
  case llvm::AtomicOrderingCABI::release:
3270
65
  case llvm::AtomicOrderingCABI::acq_rel:
3271
65
  case llvm::AtomicOrderingCABI::seq_cst:
3272
65
    break;
3273
10
  default: {
3274
10
    return Diag(ArgExpr->getBeginLoc(),
3275
10
                diag::warn_atomic_op_has_invalid_memory_order)
3276
10
           << ArgExpr->getSourceRange();
3277
65
  }
3278
65
  }
3279
3280
65
  Arg = TheCall->getArg(ScopeIndex);
3281
65
  ArgExpr = Arg.get();
3282
65
  Expr::EvalResult ArgResult1;
3283
  // Check that sync scope is a constant literal
3284
65
  if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Expr::EvaluateForCodeGen,
3285
65
                                       Context))
3286
5
    return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal)
3287
5
           << ArgExpr->getType();
3288
3289
60
  return false;
3290
60
}
3291
3292
bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
3293
16.2k
                                           CallExpr *TheCall) {
3294
16.2k
  if (BuiltinID == SystemZ::BI__builtin_tabort) {
3295
12
    Expr *Arg = TheCall->getArg(0);
3296
12
    if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context))
3297
8
      if (AbortCode->getSExtValue() >= 0 && 
AbortCode->getSExtValue() < 2566
)
3298
2
        return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
3299
2
               << Arg->getSourceRange();
3300
16.2k
  }
3301
3302
  // For intrinsics which take an immediate value as part of the instruction,
3303
  // range check them here.
3304
16.2k
  unsigned i = 0, l = 0, u = 0;
3305
16.2k
  switch (BuiltinID) {
3306
13.0k
  default: return false;
3307
22
  case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
3308
144
  case SystemZ::BI__builtin_s390_verimb:
3309
144
  case SystemZ::BI__builtin_s390_verimh:
3310
144
  case SystemZ::BI__builtin_s390_verimf:
3311
144
  case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
3312
1.66k
  case SystemZ::BI__builtin_s390_vfaeb:
3313
1.66k
  case SystemZ::BI__builtin_s390_vfaeh:
3314
1.66k
  case SystemZ::BI__builtin_s390_vfaef:
3315
1.66k
  case SystemZ::BI__builtin_s390_vfaebs:
3316
1.66k
  case SystemZ::BI__builtin_s390_vfaehs:
3317
1.66k
  case SystemZ::BI__builtin_s390_vfaefs:
3318
1.66k
  case SystemZ::BI__builtin_s390_vfaezb:
3319
1.66k
  case SystemZ::BI__builtin_s390_vfaezh:
3320
1.66k
  case SystemZ::BI__builtin_s390_vfaezf:
3321
1.66k
  case SystemZ::BI__builtin_s390_vfaezbs:
3322
1.66k
  case SystemZ::BI__builtin_s390_vfaezhs:
3323
1.66k
  case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
3324
260
  case SystemZ::BI__builtin_s390_vfisb:
3325
260
  case SystemZ::BI__builtin_s390_vfidb:
3326
260
    return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
3327
256
           SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3328
188
  case SystemZ::BI__builtin_s390_vftcisb:
3329
188
  case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
3330
50
  case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
3331
36
  case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
3332
100
  case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
3333
588
  case SystemZ::BI__builtin_s390_vstrcb:
3334
588
  case SystemZ::BI__builtin_s390_vstrch:
3335
588
  case SystemZ::BI__builtin_s390_vstrcf:
3336
588
  case SystemZ::BI__builtin_s390_vstrczb:
3337
588
  case SystemZ::BI__builtin_s390_vstrczh:
3338
588
  case SystemZ::BI__builtin_s390_vstrczf:
3339
588
  case SystemZ::BI__builtin_s390_vstrcbs:
3340
588
  case SystemZ::BI__builtin_s390_vstrchs:
3341
588
  case SystemZ::BI__builtin_s390_vstrcfs:
3342
588
  case SystemZ::BI__builtin_s390_vstrczbs:
3343
588
  case SystemZ::BI__builtin_s390_vstrczhs:
3344
588
  case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
3345
14
  case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
3346
65
  case SystemZ::BI__builtin_s390_vfminsb:
3347
65
  case SystemZ::BI__builtin_s390_vfmaxsb:
3348
65
  case SystemZ::BI__builtin_s390_vfmindb:
3349
65
  case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
3350
44
  case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
3351
44
  case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
3352
2.96k
  }
3353
2.96k
  return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3354
2.96k
}
3355
3356
/// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
3357
/// This checks that the target supports __builtin_cpu_supports and
3358
/// that the string argument is constant and valid.
3359
static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI,
3360
44
                                   CallExpr *TheCall) {
3361
44
  Expr *Arg = TheCall->getArg(0);
3362
3363
  // Check if the argument is a string literal.
3364
44
  if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3365
1
    return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3366
1
           << Arg->getSourceRange();
3367
3368
  // Check the contents of the string.
3369
43
  StringRef Feature =
3370
43
      cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3371
43
  if (!TI.validateCpuSupports(Feature))
3372
1
    return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
3373
1
           << Arg->getSourceRange();
3374
42
  return false;
3375
42
}
3376
3377
/// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
3378
/// This checks that the target supports __builtin_cpu_is and
3379
/// that the string argument is constant and valid.
3380
51
static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) {
3381
51
  Expr *Arg = TheCall->getArg(0);
3382
3383
  // Check if the argument is a string literal.
3384
51
  if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3385
0
    return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3386
0
           << Arg->getSourceRange();
3387
3388
  // Check the contents of the string.
3389
51
  StringRef Feature =
3390
51
      cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3391
51
  if (!TI.validateCpuIs(Feature))
3392
2
    return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
3393
2
           << Arg->getSourceRange();
3394
49
  return false;
3395
49
}
3396
3397
// Check if the rounding mode is legal.
3398
894k
bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
3399
  // Indicates if this instruction has rounding control or just SAE.
3400
894k
  bool HasRC = false;
3401
3402
894k
  unsigned ArgNum = 0;
3403
894k
  switch (BuiltinID) {
3404
846k
  default:
3405
846k
    return false;
3406
1.76k
  case X86::BI__builtin_ia32_vcvttsd2si32:
3407
1.76k
  case X86::BI__builtin_ia32_vcvttsd2si64:
3408
1.76k
  case X86::BI__builtin_ia32_vcvttsd2usi32:
3409
1.76k
  case X86::BI__builtin_ia32_vcvttsd2usi64:
3410
1.76k
  case X86::BI__builtin_ia32_vcvttss2si32:
3411
1.76k
  case X86::BI__builtin_ia32_vcvttss2si64:
3412
1.76k
  case X86::BI__builtin_ia32_vcvttss2usi32:
3413
1.76k
  case X86::BI__builtin_ia32_vcvttss2usi64:
3414
1.76k
    ArgNum = 1;
3415
1.76k
    break;
3416
984
  case X86::BI__builtin_ia32_maxpd512:
3417
984
  case X86::BI__builtin_ia32_maxps512:
3418
984
  case X86::BI__builtin_ia32_minpd512:
3419
984
  case X86::BI__builtin_ia32_minps512:
3420
984
    ArgNum = 2;
3421
984
    break;
3422
8.03k
  case X86::BI__builtin_ia32_cvtps2pd512_mask:
3423
8.03k
  case X86::BI__builtin_ia32_cvttpd2dq512_mask:
3424
8.03k
  case X86::BI__builtin_ia32_cvttpd2qq512_mask:
3425
8.03k
  case X86::BI__builtin_ia32_cvttpd2udq512_mask:
3426
8.03k
  case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
3427
8.03k
  case X86::BI__builtin_ia32_cvttps2dq512_mask:
3428
8.03k
  case X86::BI__builtin_ia32_cvttps2qq512_mask:
3429
8.03k
  case X86::BI__builtin_ia32_cvttps2udq512_mask:
3430
8.03k
  case X86::BI__builtin_ia32_cvttps2uqq512_mask:
3431
8.03k
  case X86::BI__builtin_ia32_exp2pd_mask:
3432
8.03k
  case X86::BI__builtin_ia32_exp2ps_mask:
3433
8.03k
  case X86::BI__builtin_ia32_getexppd512_mask:
3434
8.03k
  case X86::BI__builtin_ia32_getexpps512_mask:
3435
8.03k
  case X86::BI__builtin_ia32_rcp28pd_mask:
3436
8.03k
  case X86::BI__builtin_ia32_rcp28ps_mask:
3437
8.03k
  case X86::BI__builtin_ia32_rsqrt28pd_mask:
3438
8.03k
  case X86::BI__builtin_ia32_rsqrt28ps_mask:
3439
8.03k
  case X86::BI__builtin_ia32_vcomisd:
3440
8.03k
  case X86::BI__builtin_ia32_vcomiss:
3441
8.03k
  case X86::BI__builtin_ia32_vcvtph2ps512_mask:
3442
8.03k
    ArgNum = 3;
3443
8.03k
    break;
3444
6.36k
  case X86::BI__builtin_ia32_cmppd512_mask:
3445
6.36k
  case X86::BI__builtin_ia32_cmpps512_mask:
3446
6.36k
  case X86::BI__builtin_ia32_cmpsd_mask:
3447
6.36k
  case X86::BI__builtin_ia32_cmpss_mask:
3448
6.36k
  case X86::BI__builtin_ia32_cvtss2sd_round_mask:
3449
6.36k
  case X86::BI__builtin_ia32_getexpsd128_round_mask:
3450
6.36k
  case X86::BI__builtin_ia32_getexpss128_round_mask:
3451
6.36k
  case X86::BI__builtin_ia32_getmantpd512_mask:
3452
6.36k
  case X86::BI__builtin_ia32_getmantps512_mask:
3453
6.36k
  case X86::BI__builtin_ia32_maxsd_round_mask:
3454
6.36k
  case X86::BI__builtin_ia32_maxss_round_mask:
3455
6.36k
  case X86::BI__builtin_ia32_minsd_round_mask:
3456
6.36k
  case X86::BI__builtin_ia32_minss_round_mask:
3457
6.36k
  case X86::BI__builtin_ia32_rcp28sd_round_mask:
3458
6.36k
  case X86::BI__builtin_ia32_rcp28ss_round_mask:
3459
6.36k
  case X86::BI__builtin_ia32_reducepd512_mask:
3460
6.36k
  case X86::BI__builtin_ia32_reduceps512_mask:
3461
6.36k
  case X86::BI__builtin_ia32_rndscalepd_mask:
3462
6.36k
  case X86::BI__builtin_ia32_rndscaleps_mask:
3463
6.36k
  case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
3464
6.36k
  case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
3465
6.36k
    ArgNum = 4;
3466
6.36k
    break;
3467
131
  case X86::BI__builtin_ia32_fixupimmpd512_mask:
3468
131
  case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3469
131
  case X86::BI__builtin_ia32_fixupimmps512_mask:
3470
131
  case X86::BI__builtin_ia32_fixupimmps512_maskz:
3471
131
  case X86::BI__builtin_ia32_fixupimmsd_mask:
3472
131
  case X86::BI__builtin_ia32_fixupimmsd_maskz:
3473
131
  case X86::BI__builtin_ia32_fixupimmss_mask:
3474
131
  case X86::BI__builtin_ia32_fixupimmss_maskz:
3475
131
  case X86::BI__builtin_ia32_getmantsd_round_mask:
3476
131
  case X86::BI__builtin_ia32_getmantss_round_mask:
3477
131
  case X86::BI__builtin_ia32_rangepd512_mask:
3478
131
  case X86::BI__builtin_ia32_rangeps512_mask:
3479
131
  case X86::BI__builtin_ia32_rangesd128_round_mask:
3480
131
  case X86::BI__builtin_ia32_rangess128_round_mask:
3481
131
  case X86::BI__builtin_ia32_reducesd_mask:
3482
131
  case X86::BI__builtin_ia32_reducess_mask:
3483
131
  case X86::BI__builtin_ia32_rndscalesd_round_mask:
3484
131
  case X86::BI__builtin_ia32_rndscaless_round_mask:
3485
131
    ArgNum = 5;
3486
131
    break;
3487
1.38k
  case X86::BI__builtin_ia32_vcvtsd2si64:
3488
1.38k
  case X86::BI__builtin_ia32_vcvtsd2si32:
3489
1.38k
  case X86::BI__builtin_ia32_vcvtsd2usi32:
3490
1.38k
  case X86::BI__builtin_ia32_vcvtsd2usi64:
3491
1.38k
  case X86::BI__builtin_ia32_vcvtss2si32:
3492
1.38k
  case X86::BI__builtin_ia32_vcvtss2si64:
3493
1.38k
  case X86::BI__builtin_ia32_vcvtss2usi32:
3494
1.38k
  case X86::BI__builtin_ia32_vcvtss2usi64:
3495
1.38k
  case X86::BI__builtin_ia32_sqrtpd512:
3496
1.38k
  case X86::BI__builtin_ia32_sqrtps512:
3497
1.38k
    ArgNum = 1;
3498
1.38k
    HasRC = true;
3499
1.38k
    break;
3500
66
  case X86::BI__builtin_ia32_addpd512:
3501
66
  case X86::BI__builtin_ia32_addps512:
3502
66
  case X86::BI__builtin_ia32_divpd512:
3503
66
  case X86::BI__builtin_ia32_divps512:
3504
66
  case X86::BI__builtin_ia32_mulpd512:
3505
66
  case X86::BI__builtin_ia32_mulps512:
3506
66
  case X86::BI__builtin_ia32_subpd512:
3507
66
  case X86::BI__builtin_ia32_subps512:
3508
66
  case X86::BI__builtin_ia32_cvtsi2sd64:
3509
66
  case X86::BI__builtin_ia32_cvtsi2ss32:
3510
66
  case X86::BI__builtin_ia32_cvtsi2ss64:
3511
66
  case X86::BI__builtin_ia32_cvtusi2sd64:
3512
66
  case X86::BI__builtin_ia32_cvtusi2ss32:
3513
66
  case X86::BI__builtin_ia32_cvtusi2ss64:
3514
66
    ArgNum = 2;
3515
66
    HasRC = true;
3516
66
    break;
3517
7.98k
  case X86::BI__builtin_ia32_cvtdq2ps512_mask:
3518
7.98k
  case X86::BI__builtin_ia32_cvtudq2ps512_mask:
3519
7.98k
  case X86::BI__builtin_ia32_cvtpd2ps512_mask:
3520
7.98k
  case X86::BI__builtin_ia32_cvtpd2dq512_mask:
3521
7.98k
  case X86::BI__builtin_ia32_cvtpd2qq512_mask:
3522
7.98k
  case X86::BI__builtin_ia32_cvtpd2udq512_mask:
3523
7.98k
  case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
3524
7.98k
  case X86::BI__builtin_ia32_cvtps2dq512_mask:
3525
7.98k
  case X86::BI__builtin_ia32_cvtps2qq512_mask:
3526
7.98k
  case X86::BI__builtin_ia32_cvtps2udq512_mask:
3527
7.98k
  case X86::BI__builtin_ia32_cvtps2uqq512_mask:
3528
7.98k
  case X86::BI__builtin_ia32_cvtqq2pd512_mask:
3529
7.98k
  case X86::BI__builtin_ia32_cvtqq2ps512_mask:
3530
7.98k
  case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
3531
7.98k
  case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
3532
7.98k
    ArgNum = 3;
3533
7.98k
    HasRC = true;
3534
7.98k
    break;
3535
20.8k
  case X86::BI__builtin_ia32_addss_round_mask:
3536
20.8k
  case X86::BI__builtin_ia32_addsd_round_mask:
3537
20.8k
  case X86::BI__builtin_ia32_divss_round_mask:
3538
20.8k
  case X86::BI__builtin_ia32_divsd_round_mask:
3539
20.8k
  case X86::BI__builtin_ia32_mulss_round_mask:
3540
20.8k
  case X86::BI__builtin_ia32_mulsd_round_mask:
3541
20.8k
  case X86::BI__builtin_ia32_subss_round_mask:
3542
20.8k
  case X86::BI__builtin_ia32_subsd_round_mask:
3543
20.8k
  case X86::BI__builtin_ia32_scalefpd512_mask:
3544
20.8k
  case X86::BI__builtin_ia32_scalefps512_mask:
3545
20.8k
  case X86::BI__builtin_ia32_scalefsd_round_mask:
3546
20.8k
  case X86::BI__builtin_ia32_scalefss_round_mask:
3547
20.8k
  case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
3548
20.8k
  case X86::BI__builtin_ia32_sqrtsd_round_mask:
3549
20.8k
  case X86::BI__builtin_ia32_sqrtss_round_mask:
3550
20.8k
  case X86::BI__builtin_ia32_vfmaddsd3_mask:
3551
20.8k
  case X86::BI__builtin_ia32_vfmaddsd3_maskz:
3552
20.8k
  case X86::BI__builtin_ia32_vfmaddsd3_mask3:
3553
20.8k
  case X86::BI__builtin_ia32_vfmaddss3_mask:
3554
20.8k
  case X86::BI__builtin_ia32_vfmaddss3_maskz:
3555
20.8k
  case X86::BI__builtin_ia32_vfmaddss3_mask3:
3556
20.8k
  case X86::BI__builtin_ia32_vfmaddpd512_mask:
3557
20.8k
  case X86::BI__builtin_ia32_vfmaddpd512_maskz:
3558
20.8k
  case X86::BI__builtin_ia32_vfmaddpd512_mask3:
3559
20.8k
  case X86::BI__builtin_ia32_vfmsubpd512_mask3:
3560
20.8k
  case X86::BI__builtin_ia32_vfmaddps512_mask:
3561
20.8k
  case X86::BI__builtin_ia32_vfmaddps512_maskz:
3562
20.8k
  case X86::BI__builtin_ia32_vfmaddps512_mask3:
3563
20.8k
  case X86::BI__builtin_ia32_vfmsubps512_mask3:
3564
20.8k
  case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
3565
20.8k
  case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
3566
20.8k
  case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
3567
20.8k
  case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
3568
20.8k
  case X86::BI__builtin_ia32_vfmaddsubps512_mask:
3569
20.8k
  case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
3570
20.8k
  case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
3571
20.8k
  case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
3572
20.8k
    ArgNum = 4;
3573
20.8k
    HasRC = true;
3574
20.8k
    break;
3575
47.6k
  }
3576
3577
47.6k
  llvm::APSInt Result;
3578
3579
  // We can't check the value of a dependent argument.
3580
47.6k
  Expr *Arg = TheCall->getArg(ArgNum);
3581
47.6k
  if (Arg->isTypeDependent() || Arg->isValueDependent())
3582
0
    return false;
3583
3584
  // Check constant-ness first.
3585
47.6k
  if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3586
0
    return true;
3587
3588
  // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
3589
  // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
3590
  // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
3591
  // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
3592
47.6k
  if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
3593
731
      Result == 8/*ROUND_NO_EXC*/ ||
3594
390
      (!HasRC && 
Result == 124
/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
3595
389
      (HasRC && 
Result.getZExtValue() >= 8386
&&
Result.getZExtValue() <= 11386
))
3596
47.5k
    return false;
3597
3598
3
  return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
3599
3
         << Arg->getSourceRange();
3600
3
}
3601
3602
// Check if the gather/scatter scale is legal.
3603
bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
3604
894k
                                             CallExpr *TheCall) {
3605
894k
  unsigned ArgNum = 0;
3606
894k
  switch (BuiltinID) {
3607
893k
  default:
3608
893k
    return false;
3609
18
  case X86::BI__builtin_ia32_gatherpfdpd:
3610
18
  case X86::BI__builtin_ia32_gatherpfdps:
3611
18
  case X86::BI__builtin_ia32_gatherpfqpd:
3612
18
  case X86::BI__builtin_ia32_gatherpfqps:
3613
18
  case X86::BI__builtin_ia32_scatterpfdpd:
3614
18
  case X86::BI__builtin_ia32_scatterpfdps:
3615
18
  case X86::BI__builtin_ia32_scatterpfqpd:
3616
18
  case X86::BI__builtin_ia32_scatterpfqps:
3617
18
    ArgNum = 3;
3618
18
    break;
3619
177
  case X86::BI__builtin_ia32_gatherd_pd:
3620
177
  case X86::BI__builtin_ia32_gatherd_pd256:
3621
177
  case X86::BI__builtin_ia32_gatherq_pd:
3622
177
  case X86::BI__builtin_ia32_gatherq_pd256:
3623
177
  case X86::BI__builtin_ia32_gatherd_ps:
3624
177
  case X86::BI__builtin_ia32_gatherd_ps256:
3625
177
  case X86::BI__builtin_ia32_gatherq_ps:
3626
177
  case X86::BI__builtin_ia32_gatherq_ps256:
3627
177
  case X86::BI__builtin_ia32_gatherd_q:
3628
177
  case X86::BI__builtin_ia32_gatherd_q256:
3629
177
  case X86::BI__builtin_ia32_gatherq_q:
3630
177
  case X86::BI__builtin_ia32_gatherq_q256:
3631
177
  case X86::BI__builtin_ia32_gatherd_d:
3632
177
  case X86::BI__builtin_ia32_gatherd_d256:
3633
177
  case X86::BI__builtin_ia32_gatherq_d:
3634
177
  case X86::BI__builtin_ia32_gatherq_d256:
3635
177
  case X86::BI__builtin_ia32_gather3div2df:
3636
177
  case X86::BI__builtin_ia32_gather3div2di:
3637
177
  case X86::BI__builtin_ia32_gather3div4df:
3638
177
  case X86::BI__builtin_ia32_gather3div4di:
3639
177
  case X86::BI__builtin_ia32_gather3div4sf:
3640
177
  case X86::BI__builtin_ia32_gather3div4si:
3641
177
  case X86::BI__builtin_ia32_gather3div8sf:
3642
177
  case X86::BI__builtin_ia32_gather3div8si:
3643
177
  case X86::BI__builtin_ia32_gather3siv2df:
3644
177
  case X86::BI__builtin_ia32_gather3siv2di:
3645
177
  case X86::BI__builtin_ia32_gather3siv4df:
3646
177
  case X86::BI__builtin_ia32_gather3siv4di:
3647
177
  case X86::BI__builtin_ia32_gather3siv4sf:
3648
177
  case X86::BI__builtin_ia32_gather3siv4si:
3649
177
  case X86::BI__builtin_ia32_gather3siv8sf:
3650
177
  case X86::BI__builtin_ia32_gather3siv8si:
3651
177
  case X86::BI__builtin_ia32_gathersiv8df:
3652
177
  case X86::BI__builtin_ia32_gathersiv16sf:
3653
177
  case X86::BI__builtin_ia32_gatherdiv8df:
3654
177
  case X86::BI__builtin_ia32_gatherdiv16sf:
3655
177
  case X86::BI__builtin_ia32_gathersiv8di:
3656
177
  case X86::BI__builtin_ia32_gathersiv16si:
3657
177
  case X86::BI__builtin_ia32_gatherdiv8di:
3658
177
  case X86::BI__builtin_ia32_gatherdiv16si:
3659
177
  case X86::BI__builtin_ia32_scatterdiv2df:
3660
177
  case X86::BI__builtin_ia32_scatterdiv2di:
3661
177
  case X86::BI__builtin_ia32_scatterdiv4df:
3662
177
  case X86::BI__builtin_ia32_scatterdiv4di:
3663
177
  case X86::BI__builtin_ia32_scatterdiv4sf:
3664
177
  case X86::BI__builtin_ia32_scatterdiv4si:
3665
177
  case X86::BI__builtin_ia32_scatterdiv8sf:
3666
177
  case X86::BI__builtin_ia32_scatterdiv8si:
3667
177
  case X86::BI__builtin_ia32_scattersiv2df:
3668
177
  case X86::BI__builtin_ia32_scattersiv2di:
3669
177
  case X86::BI__builtin_ia32_scattersiv4df:
3670
177
  case X86::BI__builtin_ia32_scattersiv4di:
3671
177
  case X86::BI__builtin_ia32_scattersiv4sf:
3672
177
  case X86::BI__builtin_ia32_scattersiv4si:
3673
177
  case X86::BI__builtin_ia32_scattersiv8sf:
3674
177
  case X86::BI__builtin_ia32_scattersiv8si:
3675
177
  case X86::BI__builtin_ia32_scattersiv8df:
3676
177
  case X86::BI__builtin_ia32_scattersiv16sf:
3677
177
  case X86::BI__builtin_ia32_scatterdiv8df:
3678
177
  case X86::BI__builtin_ia32_scatterdiv16sf:
3679
177
  case X86::BI__builtin_ia32_scattersiv8di:
3680
177
  case X86::BI__builtin_ia32_scattersiv16si:
3681
177
  case X86::BI__builtin_ia32_scatterdiv8di:
3682
177
  case X86::BI__builtin_ia32_scatterdiv16si:
3683
177
    ArgNum = 4;
3684
177
    break;
3685
195
  }
3686
3687
195
  llvm::APSInt Result;
3688
3689
  // We can't check the value of a dependent argument.
3690
195
  Expr *Arg = TheCall->getArg(ArgNum);
3691
195
  if (Arg->isTypeDependent() || Arg->isValueDependent())
3692
0
    return false;
3693
3694
  // Check constant-ness first.
3695
195
  if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3696
0
    return true;
3697
3698
195
  if (Result == 1 || 
Result == 2186
||
Result == 42
||
Result == 82
)
3699
193
    return false;
3700
3701
2
  return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
3702
2
         << Arg->getSourceRange();
3703
2
}
3704
3705
enum { TileRegLow = 0, TileRegHigh = 7 };
3706
3707
bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall,
3708
20
                                             ArrayRef<int> ArgNums) {
3709
41
  for (int ArgNum : ArgNums) {
3710
41
    if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh))
3711
7
      return true;
3712
41
  }
3713
13
  return false;
3714
20
}
3715
3716
bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall,
3717
9
                                        ArrayRef<int> ArgNums) {
3718
  // Because the max number of tile register is TileRegHigh + 1, so here we use
3719
  // each bit to represent the usage of them in bitset.
3720
9
  std::bitset<TileRegHigh + 1> ArgValues;
3721
26
  for (int ArgNum : ArgNums) {
3722
26
    Expr *Arg = TheCall->getArg(ArgNum);
3723
26
    if (Arg->isTypeDependent() || Arg->isValueDependent())
3724
0
      continue;
3725
3726
26
    llvm::APSInt Result;
3727
26
    if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3728
0
      return true;
3729
26
    int ArgExtValue = Result.getExtValue();
3730
26
    assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) &&
3731
26
           "Incorrect tile register num.");
3732
26
    if (ArgValues.test(ArgExtValue))
3733
4
      return Diag(TheCall->getBeginLoc(),
3734
4
                  diag::err_x86_builtin_tile_arg_duplicate)
3735
4
             << TheCall->getArg(ArgNum)->getSourceRange();
3736
22
    ArgValues.set(ArgExtValue);
3737
22
  }
3738
5
  return false;
3739
9
}
3740
3741
bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall,
3742
12
                                                ArrayRef<int> ArgNums) {
3743
12
  return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) ||
3744
9
         CheckX86BuiltinTileDuplicate(TheCall, ArgNums);
3745
12
}
3746
3747
894k
bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) {
3748
894k
  switch (BuiltinID) {
3749
894k
  default:
3750
894k
    return false;
3751
8
  case X86::BI__builtin_ia32_tileloadd64:
3752
8
  case X86::BI__builtin_ia32_tileloaddt164:
3753
8
  case X86::BI__builtin_ia32_tilestored64:
3754
8
  case X86::BI__builtin_ia32_tilezero:
3755
8
    return CheckX86BuiltinTileArgumentsRange(TheCall, 0);
3756
12
  case X86::BI__builtin_ia32_tdpbssd:
3757
12
  case X86::BI__builtin_ia32_tdpbsud:
3758
12
  case X86::BI__builtin_ia32_tdpbusd:
3759
12
  case X86::BI__builtin_ia32_tdpbuud:
3760
12
  case X86::BI__builtin_ia32_tdpbf16ps:
3761
12
    return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2});
3762
894k
  }
3763
894k
}
3764
738k
static bool isX86_32Builtin(unsigned BuiltinID) {
3765
  // These builtins only work on x86-32 targets.
3766
738k
  switch (BuiltinID) {
3767
2
  case X86::BI__builtin_ia32_readeflags_u32:
3768
2
  case X86::BI__builtin_ia32_writeeflags_u32:
3769
2
    return true;
3770
738k
  }
3771
3772
738k
  return false;
3773
738k
}
3774
3775
bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3776
894k
                                       CallExpr *TheCall) {
3777
894k
  if (BuiltinID == X86::BI__builtin_cpu_supports)
3778
44
    return SemaBuiltinCpuSupports(*this, TI, TheCall);
3779
3780
894k
  if (BuiltinID == X86::BI__builtin_cpu_is)
3781
51
    return SemaBuiltinCpuIs(*this, TI, TheCall);
3782
3783
  // Check for 32-bit only builtins on a 64-bit target.
3784
894k
  const llvm::Triple &TT = TI.getTriple();
3785
894k
  if (TT.getArch() != llvm::Triple::x86 && 
isX86_32Builtin(BuiltinID)738k
)
3786
2
    return Diag(TheCall->getCallee()->getBeginLoc(),
3787
2
                diag::err_32_bit_builtin_64_bit_tgt);
3788
3789
  // If the intrinsic has rounding or SAE make sure its valid.
3790
894k
  if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
3791
3
    return true;
3792
3793
  // If the intrinsic has a gather/scatter scale immediate make sure its valid.
3794
894k
  if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
3795
2
    return true;
3796
3797
  // If the intrinsic has a tile arguments, make sure they are valid.
3798
894k
  if (CheckX86BuiltinTileArguments(BuiltinID, TheCall))
3799
11
    return true;
3800
3801
  // For intrinsics which take an immediate value as part of the instruction,
3802
  // range check them here.
3803
894k
  int i = 0, l = 0, u = 0;
3804
894k
  switch (BuiltinID) {
3805
830k
  default:
3806
830k
    return false;
3807
39.7k
  case X86::BI__builtin_ia32_vec_ext_v2si:
3808
39.7k
  case X86::BI__builtin_ia32_vec_ext_v2di:
3809
39.7k
  case X86::BI__builtin_ia32_vextractf128_pd256:
3810
39.7k
  case X86::BI__builtin_ia32_vextractf128_ps256:
3811
39.7k
  case X86::BI__builtin_ia32_vextractf128_si256:
3812
39.7k
  case X86::BI__builtin_ia32_extract128i256:
3813
39.7k
  case X86::BI__builtin_ia32_extractf64x4_mask:
3814
39.7k
  case X86::BI__builtin_ia32_extracti64x4_mask:
3815
39.7k
  case X86::BI__builtin_ia32_extractf32x8_mask:
3816
39.7k
  case X86::BI__builtin_ia32_extracti32x8_mask:
3817
39.7k
  case X86::BI__builtin_ia32_extractf64x2_256_mask:
3818
39.7k
  case X86::BI__builtin_ia32_extracti64x2_256_mask:
3819
39.7k
  case X86::BI__builtin_ia32_extractf32x4_256_mask:
3820
39.7k
  case X86::BI__builtin_ia32_extracti32x4_256_mask:
3821
39.7k
    i = 1; l = 0; u = 1;
3822
39.7k
    break;
3823
776
  case X86::BI__builtin_ia32_vec_set_v2di:
3824
776
  case X86::BI__builtin_ia32_vinsertf128_pd256:
3825
776
  case X86::BI__builtin_ia32_vinsertf128_ps256:
3826
776
  case X86::BI__builtin_ia32_vinsertf128_si256:
3827
776
  case X86::BI__builtin_ia32_insert128i256:
3828
776
  case X86::BI__builtin_ia32_insertf32x8:
3829
776
  case X86::BI__builtin_ia32_inserti32x8:
3830
776
  case X86::BI__builtin_ia32_insertf64x4:
3831
776
  case X86::BI__builtin_ia32_inserti64x4:
3832
776
  case X86::BI__builtin_ia32_insertf64x2_256:
3833
776
  case X86::BI__builtin_ia32_inserti64x2_256:
3834
776
  case X86::BI__builtin_ia32_insertf32x4_256:
3835
776
  case X86::BI__builtin_ia32_inserti32x4_256:
3836
776
    i = 2; l = 0; u = 1;
3837
776
    break;
3838
34
  case X86::BI__builtin_ia32_vpermilpd:
3839
34
  case X86::BI__builtin_ia32_vec_ext_v4hi:
3840
34
  case X86::BI__builtin_ia32_vec_ext_v4si:
3841
34
  case X86::BI__builtin_ia32_vec_ext_v4sf:
3842
34
  case X86::BI__builtin_ia32_vec_ext_v4di:
3843
34
  case X86::BI__builtin_ia32_extractf32x4_mask:
3844
34
  case X86::BI__builtin_ia32_extracti32x4_mask:
3845
34
  case X86::BI__builtin_ia32_extractf64x2_512_mask:
3846
34
  case X86::BI__builtin_ia32_extracti64x2_512_mask:
3847
34
    i = 1; l = 0; u = 3;
3848
34
    break;
3849
11
  case X86::BI_mm_prefetch:
3850
11
  case X86::BI__builtin_ia32_vec_ext_v8hi:
3851
11
  case X86::BI__builtin_ia32_vec_ext_v8si:
3852
11
    i = 1; l = 0; u = 7;
3853
11
    break;
3854
46
  case X86::BI__builtin_ia32_sha1rnds4:
3855
46
  case X86::BI__builtin_ia32_blendpd:
3856
46
  case X86::BI__builtin_ia32_shufpd:
3857
46
  case X86::BI__builtin_ia32_vec_set_v4hi:
3858
46
  case X86::BI__builtin_ia32_vec_set_v4si:
3859
46
  case X86::BI__builtin_ia32_vec_set_v4di:
3860
46
  case X86::BI__builtin_ia32_shuf_f32x4_256:
3861
46
  case X86::BI__builtin_ia32_shuf_f64x2_256:
3862
46
  case X86::BI__builtin_ia32_shuf_i32x4_256:
3863
46
  case X86::BI__builtin_ia32_shuf_i64x2_256:
3864
46
  case X86::BI__builtin_ia32_insertf64x2_512:
3865
46
  case X86::BI__builtin_ia32_inserti64x2_512:
3866
46
  case X86::BI__builtin_ia32_insertf32x4:
3867
46
  case X86::BI__builtin_ia32_inserti32x4:
3868
46
    i = 2; l = 0; u = 3;
3869
46
    break;
3870
8
  case X86::BI__builtin_ia32_vpermil2pd:
3871
8
  case X86::BI__builtin_ia32_vpermil2pd256:
3872
8
  case X86::BI__builtin_ia32_vpermil2ps:
3873
8
  case X86::BI__builtin_ia32_vpermil2ps256:
3874
8
    i = 3; l = 0; u = 3;
3875
8
    break;
3876
18.8k
  case X86::BI__builtin_ia32_cmpb128_mask:
3877
18.8k
  case X86::BI__builtin_ia32_cmpw128_mask:
3878
18.8k
  case X86::BI__builtin_ia32_cmpd128_mask:
3879
18.8k
  case X86::BI__builtin_ia32_cmpq128_mask:
3880
18.8k
  case X86::BI__builtin_ia32_cmpb256_mask:
3881
18.8k
  case X86::BI__builtin_ia32_cmpw256_mask:
3882
18.8k
  case X86::BI__builtin_ia32_cmpd256_mask:
3883
18.8k
  case X86::BI__builtin_ia32_cmpq256_mask:
3884
18.8k
  case X86::BI__builtin_ia32_cmpb512_mask:
3885
18.8k
  case X86::BI__builtin_ia32_cmpw512_mask:
3886
18.8k
  case X86::BI__builtin_ia32_cmpd512_mask:
3887
18.8k
  case X86::BI__builtin_ia32_cmpq512_mask:
3888
18.8k
  case X86::BI__builtin_ia32_ucmpb128_mask:
3889
18.8k
  case X86::BI__builtin_ia32_ucmpw128_mask:
3890
18.8k
  case X86::BI__builtin_ia32_ucmpd128_mask:
3891
18.8k
  case X86::BI__builtin_ia32_ucmpq128_mask:
3892
18.8k
  case X86::BI__builtin_ia32_ucmpb256_mask:
3893
18.8k
  case X86::BI__builtin_ia32_ucmpw256_mask:
3894
18.8k
  case X86::BI__builtin_ia32_ucmpd256_mask:
3895
18.8k
  case X86::BI__builtin_ia32_ucmpq256_mask:
3896
18.8k
  case X86::BI__builtin_ia32_ucmpb512_mask:
3897
18.8k
  case X86::BI__builtin_ia32_ucmpw512_mask:
3898
18.8k
  case X86::BI__builtin_ia32_ucmpd512_mask:
3899
18.8k
  case X86::BI__builtin_ia32_ucmpq512_mask:
3900
18.8k
  case X86::BI__builtin_ia32_vpcomub:
3901
18.8k
  case X86::BI__builtin_ia32_vpcomuw:
3902
18.8k
  case X86::BI__builtin_ia32_vpcomud:
3903
18.8k
  case X86::BI__builtin_ia32_vpcomuq:
3904
18.8k
  case X86::BI__builtin_ia32_vpcomb:
3905
18.8k
  case X86::BI__builtin_ia32_vpcomw:
3906
18.8k
  case X86::BI__builtin_ia32_vpcomd:
3907
18.8k
  case X86::BI__builtin_ia32_vpcomq:
3908
18.8k
  case X86::BI__builtin_ia32_vec_set_v8hi:
3909
18.8k
  case X86::BI__builtin_ia32_vec_set_v8si:
3910
18.8k
    i = 2; l = 0; u = 7;
3911
18.8k
    break;
3912
99
  case X86::BI__builtin_ia32_vpermilpd256:
3913
99
  case X86::BI__builtin_ia32_roundps:
3914
99
  case X86::BI__builtin_ia32_roundpd:
3915
99
  case X86::BI__builtin_ia32_roundps256:
3916
99
  case X86::BI__builtin_ia32_roundpd256:
3917
99
  case X86::BI__builtin_ia32_getmantpd128_mask:
3918
99
  case X86::BI__builtin_ia32_getmantpd256_mask:
3919
99
  case X86::BI__builtin_ia32_getmantps128_mask:
3920
99
  case X86::BI__builtin_ia32_getmantps256_mask:
3921
99
  case X86::BI__builtin_ia32_getmantpd512_mask:
3922
99
  case X86::BI__builtin_ia32_getmantps512_mask:
3923
99
  case X86::BI__builtin_ia32_vec_ext_v16qi:
3924
99
  case X86::BI__builtin_ia32_vec_ext_v16hi:
3925
99
    i = 1; l = 0; u = 15;
3926
99
    break;
3927
79
  case X86::BI__builtin_ia32_pblendd128:
3928
79
  case X86::BI__builtin_ia32_blendps:
3929
79
  case X86::BI__builtin_ia32_blendpd256:
3930
79
  case X86::BI__builtin_ia32_shufpd256:
3931
79
  case X86::BI__builtin_ia32_roundss:
3932
79
  case X86::BI__builtin_ia32_roundsd:
3933
79
  case X86::BI__builtin_ia32_rangepd128_mask:
3934
79
  case X86::BI__builtin_ia32_rangepd256_mask:
3935
79
  case X86::BI__builtin_ia32_rangepd512_mask:
3936
79
  case X86::BI__builtin_ia32_rangeps128_mask:
3937
79
  case X86::BI__builtin_ia32_rangeps256_mask:
3938
79
  case X86::BI__builtin_ia32_rangeps512_mask:
3939
79
  case X86::BI__builtin_ia32_getmantsd_round_mask:
3940
79
  case X86::BI__builtin_ia32_getmantss_round_mask:
3941
79
  case X86::BI__builtin_ia32_vec_set_v16qi:
3942
79
  case X86::BI__builtin_ia32_vec_set_v16hi:
3943
79
    i = 2; l = 0; u = 15;
3944
79
    break;
3945
3
  case X86::BI__builtin_ia32_vec_ext_v32qi:
3946
3
    i = 1; l = 0; u = 31;
3947
3
    break;
3948
1.63k
  case X86::BI__builtin_ia32_cmpps:
3949
1.63k
  case X86::BI__builtin_ia32_cmpss:
3950
1.63k
  case X86::BI__builtin_ia32_cmppd:
3951
1.63k
  case X86::BI__builtin_ia32_cmpsd:
3952
1.63k
  case X86::BI__builtin_ia32_cmpps256:
3953
1.63k
  case X86::BI__builtin_ia32_cmppd256:
3954
1.63k
  case X86::BI__builtin_ia32_cmpps128_mask:
3955
1.63k
  case X86::BI__builtin_ia32_cmppd128_mask:
3956
1.63k
  case X86::BI__builtin_ia32_cmpps256_mask:
3957
1.63k
  case X86::BI__builtin_ia32_cmppd256_mask:
3958
1.63k
  case X86::BI__builtin_ia32_cmpps512_mask:
3959
1.63k
  case X86::BI__builtin_ia32_cmppd512_mask:
3960
1.63k
  case X86::BI__builtin_ia32_cmpsd_mask:
3961
1.63k
  case X86::BI__builtin_ia32_cmpss_mask:
3962
1.63k
  case X86::BI__builtin_ia32_vec_set_v32qi:
3963
1.63k
    i = 2; l = 0; u = 31;
3964
1.63k
    break;
3965
2.28k
  case X86::BI__builtin_ia32_permdf256:
3966
2.28k
  case X86::BI__builtin_ia32_permdi256:
3967
2.28k
  case X86::BI__builtin_ia32_permdf512:
3968
2.28k
  case X86::BI__builtin_ia32_permdi512:
3969
2.28k
  case X86::BI__builtin_ia32_vpermilps:
3970
2.28k
  case X86::BI__builtin_ia32_vpermilps256:
3971
2.28k
  case X86::BI__builtin_ia32_vpermilpd512:
3972
2.28k
  case X86::BI__builtin_ia32_vpermilps512:
3973
2.28k
  case X86::BI__builtin_ia32_pshufd:
3974
2.28k
  case X86::BI__builtin_ia32_pshufd256:
3975
2.28k
  case X86::BI__builtin_ia32_pshufd512:
3976
2.28k
  case X86::BI__builtin_ia32_pshufhw:
3977
2.28k
  case X86::BI__builtin_ia32_pshufhw256:
3978
2.28k
  case X86::BI__builtin_ia32_pshufhw512:
3979
2.28k
  case X86::BI__builtin_ia32_pshuflw:
3980
2.28k
  case X86::BI__builtin_ia32_pshuflw256:
3981
2.28k
  case X86::BI__builtin_ia32_pshuflw512:
3982
2.28k
  case X86::BI__builtin_ia32_vcvtps2ph:
3983
2.28k
  case X86::BI__builtin_ia32_vcvtps2ph_mask:
3984
2.28k
  case X86::BI__builtin_ia32_vcvtps2ph256:
3985
2.28k
  case X86::BI__builtin_ia32_vcvtps2ph256_mask:
3986
2.28k
  case X86::BI__builtin_ia32_vcvtps2ph512_mask:
3987
2.28k
  case X86::BI__builtin_ia32_rndscaleps_128_mask:
3988
2.28k
  case X86::BI__builtin_ia32_rndscalepd_128_mask:
3989
2.28k
  case X86::BI__builtin_ia32_rndscaleps_256_mask:
3990
2.28k
  case X86::BI__builtin_ia32_rndscalepd_256_mask:
3991
2.28k
  case X86::BI__builtin_ia32_rndscaleps_mask:
3992
2.28k
  case X86::BI__builtin_ia32_rndscalepd_mask:
3993
2.28k
  case X86::BI__builtin_ia32_reducepd128_mask:
3994
2.28k
  case X86::BI__builtin_ia32_reducepd256_mask:
3995
2.28k
  case X86::BI__builtin_ia32_reducepd512_mask:
3996
2.28k
  case X86::BI__builtin_ia32_reduceps128_mask:
3997
2.28k
  case X86::BI__builtin_ia32_reduceps256_mask:
3998
2.28k
  case X86::BI__builtin_ia32_reduceps512_mask:
3999
2.28k
  case X86::BI__builtin_ia32_prold512:
4000
2.28k
  case X86::BI__builtin_ia32_prolq512:
4001
2.28k
  case X86::BI__builtin_ia32_prold128:
4002
2.28k
  case X86::BI__builtin_ia32_prold256:
4003
2.28k
  case X86::BI__builtin_ia32_prolq128:
4004
2.28k
  case X86::BI__builtin_ia32_prolq256:
4005
2.28k
  case X86::BI__builtin_ia32_prord512:
4006
2.28k
  case X86::BI__builtin_ia32_prorq512:
4007
2.28k
  case X86::BI__builtin_ia32_prord128:
4008
2.28k
  case X86::BI__builtin_ia32_prord256:
4009
2.28k
  case X86::BI__builtin_ia32_prorq128:
4010
2.28k
  case X86::BI__builtin_ia32_prorq256:
4011
2.28k
  case X86::BI__builtin_ia32_fpclasspd128_mask:
4012
2.28k
  case X86::BI__builtin_ia32_fpclasspd256_mask:
4013
2.28k
  case X86::BI__builtin_ia32_fpclassps128_mask:
4014
2.28k
  case X86::BI__builtin_ia32_fpclassps256_mask:
4015
2.28k
  case X86::BI__builtin_ia32_fpclassps512_mask:
4016
2.28k
  case X86::BI__builtin_ia32_fpclasspd512_mask:
4017
2.28k
  case X86::BI__builtin_ia32_fpclasssd_mask:
4018
2.28k
  case X86::BI__builtin_ia32_fpclassss_mask:
4019
2.28k
  case X86::BI__builtin_ia32_pslldqi128_byteshift:
4020
2.28k
  case X86::BI__builtin_ia32_pslldqi256_byteshift:
4021
2.28k
  case X86::BI__builtin_ia32_pslldqi512_byteshift:
4022
2.28k
  case X86::BI__builtin_ia32_psrldqi128_byteshift:
4023
2.28k
  case X86::BI__builtin_ia32_psrldqi256_byteshift:
4024
2.28k
  case X86::BI__builtin_ia32_psrldqi512_byteshift:
4025
2.28k
  case X86::BI__builtin_ia32_kshiftliqi:
4026
2.28k
  case X86::BI__builtin_ia32_kshiftlihi:
4027
2.28k
  case X86::BI__builtin_ia32_kshiftlisi:
4028
2.28k
  case X86::BI__builtin_ia32_kshiftlidi:
4029
2.28k
  case X86::BI__builtin_ia32_kshiftriqi:
4030
2.28k
  case X86::BI__builtin_ia32_kshiftrihi:
4031
2.28k
  case X86::BI__builtin_ia32_kshiftrisi:
4032
2.28k
  case X86::BI__builtin_ia32_kshiftridi:
4033
2.28k
    i = 1; l = 0; u = 255;
4034
2.28k
    break;
4035
223
  case X86::BI__builtin_ia32_vperm2f128_pd256:
4036
223
  case X86::BI__builtin_ia32_vperm2f128_ps256:
4037
223
  case X86::BI__builtin_ia32_vperm2f128_si256:
4038
223
  case X86::BI__builtin_ia32_permti256:
4039
223
  case X86::BI__builtin_ia32_pblendw128:
4040
223
  case X86::BI__builtin_ia32_pblendw256:
4041
223
  case X86::BI__builtin_ia32_blendps256:
4042
223
  case X86::BI__builtin_ia32_pblendd256:
4043
223
  case X86::BI__builtin_ia32_palignr128:
4044
223
  case X86::BI__builtin_ia32_palignr256:
4045
223
  case X86::BI__builtin_ia32_palignr512:
4046
223
  case X86::BI__builtin_ia32_alignq512:
4047
223
  case X86::BI__builtin_ia32_alignd512:
4048
223
  case X86::BI__builtin_ia32_alignd128:
4049
223
  case X86::BI__builtin_ia32_alignd256:
4050
223
  case X86::BI__builtin_ia32_alignq128:
4051
223
  case X86::BI__builtin_ia32_alignq256:
4052
223
  case X86::BI__builtin_ia32_vcomisd:
4053
223
  case X86::BI__builtin_ia32_vcomiss:
4054
223
  case X86::BI__builtin_ia32_shuf_f32x4:
4055
223
  case X86::BI__builtin_ia32_shuf_f64x2:
4056
223
  case X86::BI__builtin_ia32_shuf_i32x4:
4057
223
  case X86::BI__builtin_ia32_shuf_i64x2:
4058
223
  case X86::BI__builtin_ia32_shufpd512:
4059
223
  case X86::BI__builtin_ia32_shufps:
4060
223
  case X86::BI__builtin_ia32_shufps256:
4061
223
  case X86::BI__builtin_ia32_shufps512:
4062
223
  case X86::BI__builtin_ia32_dbpsadbw128:
4063
223
  case X86::BI__builtin_ia32_dbpsadbw256:
4064
223
  case X86::BI__builtin_ia32_dbpsadbw512:
4065
223
  case X86::BI__builtin_ia32_vpshldd128:
4066
223
  case X86::BI__builtin_ia32_vpshldd256:
4067
223
  case X86::BI__builtin_ia32_vpshldd512:
4068
223
  case X86::BI__builtin_ia32_vpshldq128:
4069
223
  case X86::BI__builtin_ia32_vpshldq256:
4070
223
  case X86::BI__builtin_ia32_vpshldq512:
4071
223
  case X86::BI__builtin_ia32_vpshldw128:
4072
223
  case X86::BI__builtin_ia32_vpshldw256:
4073
223
  case X86::BI__builtin_ia32_vpshldw512:
4074
223
  case X86::BI__builtin_ia32_vpshrdd128:
4075
223
  case X86::BI__builtin_ia32_vpshrdd256:
4076
223
  case X86::BI__builtin_ia32_vpshrdd512:
4077
223
  case X86::BI__builtin_ia32_vpshrdq128:
4078
223
  case X86::BI__builtin_ia32_vpshrdq256:
4079
223
  case X86::BI__builtin_ia32_vpshrdq512:
4080
223
  case X86::BI__builtin_ia32_vpshrdw128:
4081
223
  case X86::BI__builtin_ia32_vpshrdw256:
4082
223
  case X86::BI__builtin_ia32_vpshrdw512:
4083
223
    i = 2; l = 0; u = 255;
4084
223
    break;
4085
84
  case X86::BI__builtin_ia32_fixupimmpd512_mask:
4086
84
  case X86::BI__builtin_ia32_fixupimmpd512_maskz:
4087
84
  case X86::BI__builtin_ia32_fixupimmps512_mask:
4088
84
  case X86::BI__builtin_ia32_fixupimmps512_maskz:
4089
84
  case X86::BI__builtin_ia32_fixupimmsd_mask:
4090
84
  case X86::BI__builtin_ia32_fixupimmsd_maskz:
4091
84
  case X86::BI__builtin_ia32_fixupimmss_mask:
4092
84
  case X86::BI__builtin_ia32_fixupimmss_maskz:
4093
84
  case X86::BI__builtin_ia32_fixupimmpd128_mask:
4094
84
  case X86::BI__builtin_ia32_fixupimmpd128_maskz:
4095
84
  case X86::BI__builtin_ia32_fixupimmpd256_mask:
4096
84
  case X86::BI__builtin_ia32_fixupimmpd256_maskz:
4097
84
  case X86::BI__builtin_ia32_fixupimmps128_mask:
4098
84
  case X86::BI__builtin_ia32_fixupimmps128_maskz:
4099
84
  case X86::BI__builtin_ia32_fixupimmps256_mask:
4100
84
  case X86::BI__builtin_ia32_fixupimmps256_maskz:
4101
84
  case X86::BI__builtin_ia32_pternlogd512_mask:
4102
84
  case X86::BI__builtin_ia32_pternlogd512_maskz:
4103
84
  case X86::BI__builtin_ia32_pternlogq512_mask:
4104
84
  case X86::BI__builtin_ia32_pternlogq512_maskz:
4105
84
  case X86::BI__builtin_ia32_pternlogd128_mask:
4106
84
  case X86::BI__builtin_ia32_pternlogd128_maskz:
4107
84
  case X86::BI__builtin_ia32_pternlogd256_mask:
4108
84
  case X86::BI__builtin_ia32_pternlogd256_maskz:
4109
84
  case X86::BI__builtin_ia32_pternlogq128_mask:
4110
84
  case X86::BI__builtin_ia32_pternlogq128_maskz:
4111
84
  case X86::BI__builtin_ia32_pternlogq256_mask:
4112
84
  case X86::BI__builtin_ia32_pternlogq256_maskz:
4113
84
    i = 3; l = 0; u = 255;
4114
84
    break;
4115
17
  case X86::BI__builtin_ia32_gatherpfdpd:
4116
17
  case X86::BI__builtin_ia32_gatherpfdps:
4117
17
  case X86::BI__builtin_ia32_gatherpfqpd:
4118
17
  case X86::BI__builtin_ia32_gatherpfqps:
4119
17
  case X86::BI__builtin_ia32_scatterpfdpd:
4120
17
  case X86::BI__builtin_ia32_scatterpfdps:
4121
17
  case X86::BI__builtin_ia32_scatterpfqpd:
4122
17
  case X86::BI__builtin_ia32_scatterpfqps:
4123
17
    i = 4; l = 2; u = 3;
4124
17
    break;
4125
34
  case X86::BI__builtin_ia32_reducesd_mask:
4126
34
  case X86::BI__builtin_ia32_reducess_mask:
4127
34
  case X86::BI__builtin_ia32_rndscalesd_round_mask:
4128
34
  case X86::BI__builtin_ia32_rndscaless_round_mask:
4129
34
    i = 4; l = 0; u = 255;
4130
34
    break;
4131
63.9k
  }
4132
4133
  // Note that we don't force a hard error on the range check here, allowing
4134
  // template-generated or macro-generated dead code to potentially have out-of-
4135
  // range values. These need to code generate, but don't need to necessarily
4136
  // make any sense. We use a warning that defaults to an error.
4137
63.9k
  return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
4138
63.9k
}
4139
4140
/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
4141
/// parameter with the FormatAttr's correct format_idx and firstDataArg.
4142
/// Returns true when the format fits the function and the FormatStringInfo has
4143
/// been populated.
4144
bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
4145
18.7k
                               FormatStringInfo *FSI) {
4146
18.7k
  FSI->HasVAListArg = Format->getFirstArg() == 0;
4147
18.7k
  FSI->FormatIdx = Format->getFormatIdx() - 1;
4148
18.5k
  FSI->FirstDataArg = FSI->HasVAListArg ? 
0156
: Format->getFirstArg() - 1;
4149
4150
  // The way the format attribute works in GCC, the implicit this argument
4151
  // of member functions is counted. However, it doesn't appear in our own
4152
  // lists, so decrement format_idx in that case.
4153
18.7k
  if (IsCXXMember) {
4154
19
    if(FSI->FormatIdx == 0)
4155
0
      return false;
4156
19
    --FSI->FormatIdx;
4157
19
    if (FSI->FirstDataArg != 0)
4158
19
      --FSI->FirstDataArg;
4159
19
  }
4160
18.7k
  return true;
4161
18.7k
}
4162
4163
/// Checks if a the given expression evaluates to null.
4164
///
4165
/// Returns true if the value evaluates to null.
4166
30.0k
static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
4167
  // If the expression has non-null type, it doesn't evaluate to null.
4168
30.0k
  if (auto nullability
4169
2.61k
        = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
4170
2.61k
    if (*nullability == NullabilityKind::NonNull)
4171
2.49k
      return false;
4172
27.5k
  }
4173
4174
  // As a special case, transparent unions initialized with zero are
4175
  // considered null for the purposes of the nonnull attribute.
4176
27.5k
  if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
4177
14
    if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
4178
14
      if (const CompoundLiteralExpr *CLE =
4179
13
          dyn_cast<CompoundLiteralExpr>(Expr))
4180
13
        if (const InitListExpr *ILE =
4181
13
            dyn_cast<InitListExpr>(CLE->getInitializer()))
4182
13
          Expr = ILE->getInit(0);
4183
14
  }
4184
4185
27.5k
  bool Result;
4186
27.5k
  return (!Expr->isValueDependent() &&
4187
27.5k
          Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
4188
4.87k
          !Result);
4189
27.5k
}
4190
4191
static void CheckNonNullArgument(Sema &S,
4192
                                 const Expr *ArgExpr,
4193
28.8k
                                 SourceLocation CallSiteLoc) {
4194
28.8k
  if (CheckNonNullExpr(S, ArgExpr))
4195
197
    S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
4196
197
                          S.PDiag(diag::warn_null_arg)
4197
197
                              << ArgExpr->getSourceRange());
4198
28.8k
}
4199
4200
1.70k
bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
4201
1.70k
  FormatStringInfo FSI;
4202
1.70k
  if ((GetFormatStringType(Format) == FST_NSString) &&
4203
627
      getFormatStringInfo(Format, false, &FSI)) {
4204
627
    Idx = FSI.FormatIdx;
4205
627
    return true;
4206
627
  }
4207
1.08k
  return false;
4208
1.08k
}
4209
4210
/// Diagnose use of %s directive in an NSString which is being passed
4211
/// as formatting string to formatting method.
4212
static void
4213
DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
4214
                                        const NamedDecl *FDecl,
4215
                                        Expr **Args,
4216
246k
                                        unsigned NumArgs) {
4217
246k
  unsigned Idx = 0;
4218
246k
  bool Format = false;
4219
246k
  ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
4220
246k
  if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
4221
24
    Idx = 2;
4222
24
    Format = true;
4223
24
  }
4224
246k
  else
4225
246k
    for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4226
1.69k
      if (S.GetFormatNSStringIdx(I, Idx)) {
4227
613
        Format = true;
4228
613
        break;
4229
613
      }
4230
1.69k
    }
4231
246k
  if (!Format || 
NumArgs <= Idx637
)
4232
246k
    return;
4233
633
  const Expr *FormatExpr = Args[Idx];
4234
633
  if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
4235
9
    FormatExpr = CSCE->getSubExpr();
4236
633
  const StringLiteral *FormatString;
4237
633
  if (const ObjCStringLiteral *OSL =
4238
605
      dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
4239
605
    FormatString = OSL->getString();
4240
28
  else
4241
28
    FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
4242
633
  if (!FormatString)
4243
26
    return;
4244
607
  if (S.FormatStringHasSArg(FormatString)) {
4245
55
    S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
4246
55
      << "%s" << 1 << 1;
4247
55
    S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
4248
55
      << FDecl->getDeclName();
4249
55
  }
4250
607
}
4251
4252
/// Determine whether the given type has a non-null nullability annotation.
4253
7.67M
static bool isNonNullType(ASTContext &ctx, QualType type) {
4254
7.67M
  if (auto nullability = type->getNullability(ctx))
4255
29.3k
    return *nullability == NullabilityKind::NonNull;
4256
4257
7.64M
  return false;
4258
7.64M
}
4259
4260
static void CheckNonNullArguments(Sema &S,
4261
                                  const NamedDecl *FDecl,
4262
                                  const FunctionProtoType *Proto,
4263
                                  ArrayRef<const Expr *> Args,
4264
3.29M
                                  SourceLocation CallSiteLoc) {
4265
3.29M
  assert((FDecl || Proto) && "Need a function declaration or prototype");
4266
4267
  // Already checked by by constant evaluator.
4268
3.29M
  if (S.isConstantEvaluated())
4269
6.57k
    return;
4270
  // Check the attributes attached to the method/function itself.
4271
3.29M
  llvm::SmallBitVector NonNullArgs;
4272
3.29M
  if (FDecl) {
4273
    // Handle the nonnull attribute on the function/method declaration itself.
4274
1.44k
    for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4275
1.44k
      if (!NonNull->args_size()) {
4276
        // Easy case: all pointer arguments are nonnull.
4277
475
        for (const auto *Arg : Args)
4278
921
          if (S.isValidPointerAttrType(Arg->getType()))
4279
877
            CheckNonNullArgument(S, Arg, CallSiteLoc);
4280
475
        return;
4281
475
      }
4282
4283
985
      
for (const ParamIdx &Idx : NonNull->args())967
{
4284
985
        unsigned IdxAST = Idx.getASTIndex();
4285
985
        if (IdxAST >= Args.size())
4286
2
          continue;
4287
983
        if (NonNullArgs.empty())
4288
516
          NonNullArgs.resize(Args.size());
4289
983
        NonNullArgs.set(IdxAST);
4290
983
      }
4291
967
    }
4292
3.28M
  }
4293
4294
3.29M
  if (FDecl && 
(3.28M
isa<FunctionDecl>(FDecl)3.28M
||
isa<ObjCMethodDecl>(FDecl)31.1k
)) {
4295
    // Handle the nonnull attribute on the parameters of the
4296
    // function/method.
4297
3.28M
    ArrayRef<ParmVarDecl*> parms;
4298
3.28M
    if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4299
3.25M
      parms = FD->parameters();
4300
24.7k
    else
4301
24.7k
      parms = cast<ObjCMethodDecl>(FDecl)->parameters();
4302
4303
3.28M
    unsigned ParamIndex = 0;
4304
3.28M
    for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4305
8.73M
         I != E; 
++I, ++ParamIndex5.45M
) {
4306
5.45M
      const ParmVarDecl *PVD = *I;
4307
5.45M
      if (PVD->hasAttr<NonNullAttr>() ||
4308
5.45M
          isNonNullType(S.Context, PVD->getType())) {
4309
20.6k
        if (NonNullArgs.empty())
4310
16.2k
          NonNullArgs.resize(Args.size());
4311
4312
20.6k
        NonNullArgs.set(ParamIndex);
4313
20.6k
      }
4314
5.45M
    }
4315
10.1k
  } else {
4316
    // If we have a non-function, non-method declaration but no
4317
    // function prototype, try to dig out the function prototype.
4318
10.1k
    if (!Proto) {
4319
102
      if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4320
102
        QualType type = VD->getType().getNonReferenceType();
4321
102
        if (auto pointerType = type->getAs<PointerType>())
4322
35
          type = pointerType->getPointeeType();
4323
67
        else if (auto blockType = type->getAs<BlockPointerType>())
4324
67
          type = blockType->getPointeeType();
4325
        // FIXME: data member pointers?
4326
4327
        // Dig out the function prototype, if there is one.
4328
102
        Proto = type->getAs<FunctionProtoType>();
4329
102
      }
4330
102
    }
4331
4332
    // Fill in non-null argument information from the nullability
4333
    // information on the parameter types (if we have them).
4334
10.1k
    if (Proto) {
4335
10.0k
      unsigned Index = 0;
4336
17.9k
      for (auto paramType : Proto->getParamTypes()) {
4337
17.9k
        if (isNonNullType(S.Context, paramType)) {
4338
1.60k
          if (NonNullArgs.empty())
4339
1.33k
            NonNullArgs.resize(Args.size());
4340
4341
1.60k
          NonNullArgs.set(Index);
4342
1.60k
        }
4343
4344
17.9k
        ++Index;
4345
17.9k
      }
4346
10.0k
    }
4347
10.1k
  }
4348
4349
  // Check for non-null arguments.
4350
3.29M
  for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4351
3.32M
       ArgIndex != ArgIndexEnd; 
++ArgIndex29.9k
) {
4352
29.9k
    if (NonNullArgs[ArgIndex])
4353
22.3k
      CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
4354
29.9k
  }
4355
3.29M
}
4356
4357
/// Handles the checks for format strings, non-POD arguments to vararg
4358
/// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
4359
/// attributes.
4360
void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
4361
                     const Expr *ThisArg, ArrayRef<const Expr *> Args,
4362
                     bool IsMemberFunction, SourceLocation Loc,
4363
3.50M
                     SourceRange Range, VariadicCallType CallType) {
4364
  // FIXME: We should check as much as we can in the template definition.
4365
3.50M
  if (CurContext->isDependentContext())
4366
208k
    return;
4367
4368
  // Printf and scanf checking.
4369
3.29M
  llvm::SmallBitVector CheckedVarArgs;
4370
3.29M
  if (FDecl) {
4371
18.0k
    for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4372
      // Only create vector if there are format attributes.
4373
18.0k
      CheckedVarArgs.resize(Args.size());
4374
4375
18.0k
      CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
4376
18.0k
                           CheckedVarArgs);
4377
18.0k
    }
4378
3.29M
  }
4379
4380
  // Refuse POD arguments that weren't caught by the format string
4381
  // checks above.
4382
3.29M
  auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4383
3.29M
  if (CallType != VariadicDoesNotApply &&
4384
52.0k
      (!FD || 
FD->getBuiltinID() != Builtin::BI__noop50.7k
)) {
4385
50.9k
    unsigned NumParams = Proto ? Proto->getNumParams()
4386
1.15k
                       : FDecl && isa<FunctionDecl>(FDecl)
4387
0
                           ? cast<FunctionDecl>(FDecl)->getNumParams()
4388
1.15k
                       : FDecl && isa<ObjCMethodDecl>(FDecl)
4389
1.15k
                           ? cast<ObjCMethodDecl>(FDecl)->param_size()
4390
0
                       : 0;
4391
4392
114k
    for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); 
++ArgIdx62.5k
) {
4393
      // Args[ArgIdx] can be null in malformed code.
4394
62.5k
      if (const Expr *Arg = Args[ArgIdx]) {
4395
62.5k
        if (CheckedVarArgs.empty() || 
!CheckedVarArgs[ArgIdx]23.3k
)
4396
58.9k
          checkVariadicArgument(Arg, CallType);
4397
62.5k
      }
4398
62.5k
    }
4399
52.0k
  }
4400
4401
3.29M
  if (FDecl || 
Proto3.74k
) {
4402
3.29M
    CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
4403
4404
    // Type safety checking.
4405
3.29M
    if (FDecl) {
4406
3.29M
      for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4407
404
        CheckArgumentWithTypeTag(I, Args, Loc);
4408
3.29M
    }
4409
3.29M
  }
4410
4411
3.29M
  if (FDecl && 
FDecl->hasAttr<AllocAlignAttr>()3.29M
) {
4412
229
    auto *AA = FDecl->getAttr<AllocAlignAttr>();
4413
229
    const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
4414
229
    if (!Arg->isValueDependent()) {
4415
229
      Expr::EvalResult Align;
4416
229
      if (Arg->EvaluateAsInt(Align, Context)) {
4417
202
        const llvm::APSInt &I = Align.Val.getInt();
4418
202
        if (!I.isPowerOf2())
4419
16
          Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
4420
16
              << Arg->getSourceRange();
4421
4422
202
        if (I > Sema::MaximumAlignment)
4423
3
          Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
4424
3
              << Arg->getSourceRange() << Sema::MaximumAlignment;
4425
202
      }
4426
229
    }
4427
229
  }
4428
4429
3.29M
  if (FD)
4430
3.26M
    diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
4431
3.29M
}
4432
4433
/// CheckConstructorCall - Check a constructor call for correctness and safety
4434
/// properties not enforced by the C type system.
4435
void Sema::CheckConstructorCall(FunctionDecl *FDecl,
4436
                                ArrayRef<const Expr *> Args,
4437
                                const FunctionProtoType *Proto,
4438
325k
                                SourceLocation Loc) {
4439
325k
  VariadicCallType CallType =
4440
325k
    Proto->isVariadic() ? 
VariadicConstructor100
: VariadicDoesNotApply;
4441
325k
  checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4442
325k
            Loc, SourceRange(), CallType);
4443
325k
}
4444
4445
/// CheckFunctionCall - Check a direct function call for various correctness
4446
/// and safety properties not strictly enforced by the C type system.
4447
bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
4448
3.08M
                             const FunctionProtoType *Proto) {
4449
3.08M
  bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4450
36.4k
                              isa<CXXMethodDecl>(FDecl);
4451
3.08M
  bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4452
2.90M
                          IsMemberOperatorCall;
4453
3.08M
  VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4454
3.08M
                                                  TheCall->getCallee());
4455
3.08M
  Expr** Args = TheCall->getArgs();
4456
3.08M
  unsigned NumArgs = TheCall->getNumArgs();
4457
4458
3.08M
  Expr *ImplicitThis = nullptr;
4459
3.08M
  if (IsMemberOperatorCall) {
4460
    // If this is a call to a member operator, hide the first argument
4461
    // from checkCall.
4462
    // FIXME: Our choice of AST representation here is less than ideal.
4463
36.2k
    ImplicitThis = Args[0];
4464
36.2k
    ++Args;
4465
36.2k
    --NumArgs;
4466
3.04M
  } else if (IsMemberFunction)
4467
178k
    ImplicitThis =
4468
178k
        cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4469
4470
3.08M
  checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
4471
3.08M
            IsMemberFunction, TheCall->getRParenLoc(),
4472
3.08M
            TheCall->getCallee()->getSourceRange(), CallType);
4473
4474
3.08M
  IdentifierInfo *FnInfo = FDecl->getIdentifier();
4475
  // None of the checks below are needed for functions that don't have
4476
  // simple names (e.g., C++ conversion functions).
4477
3.08M
  if (!FnInfo)
4478
49.0k
    return false;
4479
4480
3.03M
  CheckAbsoluteValueFunction(TheCall, FDecl);
4481
3.03M
  CheckMaxUnsignedZero(TheCall, FDecl);
4482
4483
3.03M
  if (getLangOpts().ObjC)
4484
246k
    DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
4485
4486
3.03M
  unsigned CMId = FDecl->getMemoryFunctionKind();
4487
3.03M
  if (CMId == 0)
4488
3.02M
    return false;
4489
4490
  // Handle memory setting and copying functions.
4491
8.53k
  if (CMId == Builtin::BIstrlcpy || 
CMId == Builtin::BIstrlcat8.43k
)
4492
151
    CheckStrlcpycatArguments(TheCall, FnInfo);
4493
8.38k
  else if (CMId == Builtin::BIstrncat)
4494
173
    CheckStrncatArguments(TheCall, FnInfo);
4495
8.21k
  else
4496
8.21k
    CheckMemaccessArguments(TheCall, CMId, FnInfo);
4497
4498
8.53k
  return false;
4499
8.53k
}
4500
4501
bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
4502
24.7k
                               ArrayRef<const Expr *> Args) {
4503
24.7k
  VariadicCallType CallType =
4504
23.5k
      Method->isVariadic() ? 
VariadicMethod1.15k
: VariadicDoesNotApply;
4505
4506
24.7k
  checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
4507
24.7k
            /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
4508
24.7k
            CallType);
4509
4510
24.7k
  return false;
4511
24.7k
}
4512
4513
bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4514
7.28k
                            const FunctionProtoType *Proto) {
4515
7.28k
  QualType Ty;
4516
7.28k
  if (const auto *V = dyn_cast<VarDecl>(NDecl))
4517
3.70k
    Ty = V->getType().getNonReferenceType();
4518
3.58k
  else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
4519
3.54k
    Ty = F->getType().getNonReferenceType();
4520
35
  else
4521
35
    return false;
4522
4523
7.25k
  if (!Ty->isBlockPointerType() && 
!Ty->isFunctionPointerType()6.66k
&&
4524
11
      !Ty->isFunctionProtoType())
4525
3
    return false;
4526
4527
7.24k
  VariadicCallType CallType;
4528
7.24k
  if (!Proto || 
!Proto->isVariadic()7.14k
) {
4529
7.17k
    CallType = VariadicDoesNotApply;
4530
77
  } else if (Ty->isBlockPointerType()) {
4531
35
    CallType = VariadicBlock;
4532
42
  } else { // Ty->isFunctionPointerType()
4533
42
    CallType = VariadicFunction;
4534
42
  }
4535
4536
7.24k
  checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
4537
7.24k
            llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4538
7.24k
            /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4539
7.24k
            TheCall->getCallee()->getSourceRange(), CallType);
4540
4541
7.24k
  return false;
4542
7.24k
}
4543
4544
/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
4545
/// such as function pointers returned from functions.
4546
3.95k
bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4547
3.95k
  VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4548
3.95k
                                                  TheCall->getCallee());
4549
3.95k
  checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4550
3.95k
            llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4551
3.95k
            /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4552
3.95k
            TheCall->getCallee()->getSourceRange(), CallType);
4553
4554
3.95k
  return false;
4555
3.95k
}
4556
4557
2.41k
static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4558
2.41k
  if (!llvm::isValidAtomicOrderingCABI(Ordering))
4559
2
    return false;
4560
4561
2.41k
  auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4562
2.41k
  switch (Op) {
4563
0
  case AtomicExpr::AO__c11_atomic_init:
4564
0
  case AtomicExpr::AO__opencl_atomic_init:
4565
0
    llvm_unreachable("There is no ordering argument for an init");
4566
4567
645
  case AtomicExpr::AO__c11_atomic_load:
4568
645
  case AtomicExpr::AO__opencl_atomic_load:
4569
645
  case AtomicExpr::AO__atomic_load_n:
4570
645
  case AtomicExpr::AO__atomic_load:
4571
645
    return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4572
638
           OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4573
4574
222
  case AtomicExpr::AO__c11_atomic_store:
4575
222
  case AtomicExpr::AO__opencl_atomic_store:
4576
222
  case AtomicExpr::AO__atomic_store:
4577
222
  case AtomicExpr::AO__atomic_store_n:
4578
222
    return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4579
219
           OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4580
214
           OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4581
4582
1.54k
  default:
4583
1.54k
    return true;
4584
2.41k
  }
4585
2.41k
}
4586
4587
ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
4588
5.17k
                                         AtomicExpr::AtomicOp Op) {
4589
5.17k
  CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
4590
5.17k
  DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4591
5.17k
  MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
4592
5.17k
  return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
4593
5.17k
                         DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
4594
5.17k
                         Op);
4595
5.17k
}
4596
4597
ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
4598
                                 SourceLocation RParenLoc, MultiExprArg Args,
4599
                                 AtomicExpr::AtomicOp Op,
4600
5.18k
                                 AtomicArgumentOrder ArgOrder) {
4601
  // All the non-OpenCL operations take one of the following forms.
4602
  // The OpenCL operations take the __c11 forms with one extra argument for
4603
  // synchronization scope.
4604
5.18k
  enum {
4605
    // C    __c11_atomic_init(A *, C)
4606
5.18k
    Init,
4607
4608
    // C    __c11_atomic_load(A *, int)
4609
5.18k
    Load,
4610
4611
    // void __atomic_load(A *, CP, int)
4612
5.18k
    LoadCopy,
4613
4614
    // void __atomic_store(A *, CP, int)
4615
5.18k
    Copy,
4616
4617
    // C    __c11_atomic_add(A *, M, int)
4618
5.18k
    Arithmetic,
4619
4620
    // C    __atomic_exchange_n(A *, CP, int)
4621
5.18k
    Xchg,
4622
4623
    // void __atomic_exchange(A *, C *, CP, int)
4624
5.18k
    GNUXchg,
4625
4626
    // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
4627
5.18k
    C11CmpXchg,
4628
4629
    // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
4630
5.18k
    GNUCmpXchg
4631
5.18k
  } Form = Init;
4632
4633
5.18k
  const unsigned NumForm = GNUCmpXchg + 1;
4634
5.18k
  const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
4635
5.18k
  const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
4636
  // where:
4637
  //   C is an appropriate type,
4638
  //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
4639
  //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
4640
  //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
4641
  //   the int parameters are for orderings.
4642
4643
5.18k
  static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
4644
5.18k
      && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
4645
5.18k
      "need to update code for modified forms");
4646
5.18k
  static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
4647
5.18k
                    AtomicExpr::AO__c11_atomic_fetch_min + 1 ==
4648
5.18k
                        AtomicExpr::AO__atomic_load,
4649
5.18k
                "need to update code for modified C11 atomics");
4650
5.18k
  bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
4651
328
                  Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
4652
5.18k
  bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
4653
5.18k
               Op <= AtomicExpr::AO__c11_atomic_fetch_min) ||
4654
2.08k
               IsOpenCL;
4655
5.18k
  bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
4656
4.76k
             Op == AtomicExpr::AO__atomic_store_n ||
4657
4.73k
             Op == AtomicExpr::AO__atomic_exchange_n ||
4658
4.71k
             Op == AtomicExpr::AO__atomic_compare_exchange_n;
4659
5.18k
  bool IsAddSub = false;
4660
4661
5.18k
  switch (Op) {
4662
49
  case AtomicExpr::AO__c11_atomic_init:
4663
49
  case AtomicExpr::AO__opencl_atomic_init:
4664
49
    Form = Init;
4665
49
    break;
4666
4667
1.40k
  case AtomicExpr::AO__c11_atomic_load:
4668
1.40k
  case AtomicExpr::AO__opencl_atomic_load:
4669
1.40k
  case AtomicExpr::AO__atomic_load_n:
4670
1.40k
    Form = Load;
4671
1.40k
    break;
4672
4673
113
  case AtomicExpr::AO__atomic_load:
4674
113
    Form = LoadCopy;
4675
113
    break;
4676
4677
1.10k
  case AtomicExpr::AO__c11_atomic_store:
4678
1.10k
  case AtomicExpr::AO__opencl_atomic_store:
4679
1.10k
  case AtomicExpr::AO__atomic_store:
4680
1.10k
  case AtomicExpr::AO__atomic_store_n:
4681
1.10k
    Form = Copy;
4682
1.10k
    break;
4683
4684
1.15k
  case AtomicExpr::AO__c11_atomic_fetch_add:
4685
1.15k
  case AtomicExpr::AO__c11_atomic_fetch_sub:
4686
1.15k
  case AtomicExpr::AO__opencl_atomic_fetch_add:
4687
1.15k
  case AtomicExpr::AO__opencl_atomic_fetch_sub:
4688
1.15k
  case AtomicExpr::AO__atomic_fetch_add:
4689
1.15k
  case AtomicExpr::AO__atomic_fetch_sub:
4690
1.15k
  case AtomicExpr::AO__atomic_add_fetch:
4691
1.15k
  case AtomicExpr::AO__atomic_sub_fetch:
4692
1.15k
    IsAddSub = true;
4693
1.15k
    LLVM_FALLTHROUGH;
4694
1.43k
  case AtomicExpr::AO__c11_atomic_fetch_and:
4695
1.43k
  case AtomicExpr::AO__c11_atomic_fetch_or:
4696
1.43k
  case AtomicExpr::AO__c11_atomic_fetch_xor:
4697
1.43k
  case AtomicExpr::AO__opencl_atomic_fetch_and:
4698
1.43k
  case AtomicExpr::AO__opencl_atomic_fetch_or:
4699
1.43k
  case AtomicExpr::AO__opencl_atomic_fetch_xor:
4700
1.43k
  case AtomicExpr::AO__atomic_fetch_and:
4701
1.43k
  case AtomicExpr::AO__atomic_fetch_or:
4702
1.43k
  case AtomicExpr::AO__atomic_fetch_xor:
4703
1.43k
  case AtomicExpr::AO__atomic_fetch_nand:
4704
1.43k
  case AtomicExpr::AO__atomic_and_fetch:
4705
1.43k
  case AtomicExpr::AO__atomic_or_fetch:
4706
1.43k
  case AtomicExpr::AO__atomic_xor_fetch:
4707
1.43k
  case AtomicExpr::AO__atomic_nand_fetch:
4708
1.43k
  case AtomicExpr::AO__c11_atomic_fetch_min:
4709
1.43k
  case AtomicExpr::AO__c11_atomic_fetch_max:
4710
1.43k
  case AtomicExpr::AO__opencl_atomic_fetch_min:
4711
1.43k
  case AtomicExpr::AO__opencl_atomic_fetch_max:
4712
1.43k
  case AtomicExpr::AO__atomic_min_fetch:
4713
1.43k
  case AtomicExpr::AO__atomic_max_fetch:
4714
1.43k
  case AtomicExpr::AO__atomic_fetch_min:
4715
1.43k
  case AtomicExpr::AO__atomic_fetch_max:
4716
1.43k
    Form = Arithmetic;
4717
1.43k
    break;
4718
4719
846
  case AtomicExpr::AO__c11_atomic_exchange:
4720
846
  case AtomicExpr::AO__opencl_atomic_exchange:
4721
846
  case AtomicExpr::AO__atomic_exchange_n:
4722
846
    Form = Xchg;
4723
846
    break;
4724
4725
32
  case AtomicExpr::AO__atomic_exchange:
4726
32
    Form = GNUXchg;
4727
32
    break;
4728
4729
127
  case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
4730
127
  case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
4731
127
  case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
4732
127
  case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
4733
127
    Form = C11CmpXchg;
4734
127
    break;
4735
4736
70
  case AtomicExpr::AO__atomic_compare_exchange:
4737
70
  case AtomicExpr::AO__atomic_compare_exchange_n:
4738
70
    Form = GNUCmpXchg;
4739
70
    break;
4740
5.18k
  }
4741
4742
5.18k
  unsigned AdjustedNumArgs = NumArgs[Form];
4743
5.18k
  if (IsOpenCL && 
Op != AtomicExpr::AO__opencl_atomic_init301
)
4744
287
    ++AdjustedNumArgs;
4745
  // Check we have the right number of arguments.
4746
5.18k
  if (Args.size() < AdjustedNumArgs) {
4747
5
    Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
4748
5
        << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4749
5
        << ExprRange;
4750
5
    return ExprError();
4751
5.17k
  } else if (Args.size() > AdjustedNumArgs) {
4752
4
    Diag(Args[AdjustedNumArgs]->getBeginLoc(),
4753
4
         diag::err_typecheck_call_too_many_args)
4754
4
        << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4755
4
        << ExprRange;
4756
4
    return ExprError();
4757
4
  }
4758
4759
  // Inspect the first argument of the atomic operation.
4760
5.17k
  Expr *Ptr = Args[0];
4761
5.17k
  ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
4762
5.17k
  if (ConvertedPtr.isInvalid())
4763
1
    return ExprError();
4764
4765
5.17k
  Ptr = ConvertedPtr.get();
4766
5.17k
  const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
4767
5.17k
  if (!pointerType) {
4768
3
    Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
4769
3
        << Ptr->getType() << Ptr->getSourceRange();
4770
3
    return ExprError();
4771
3
  }
4772
4773
  // For a __c11 builtin, this should be a pointer to an _Atomic type.
4774
5.16k
  QualType AtomTy = pointerType->getPointeeType(); // 'A'
4775
5.16k
  QualType ValType = AtomTy; // 'C'
4776
5.16k
  if (IsC11) {
4777
3.39k
    if (!AtomTy->isAtomicType()) {
4778
10
      Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
4779
10
          << Ptr->getType() << Ptr->getSourceRange();
4780
10
      return ExprError();
4781
10
    }
4782
3.38k
    if ((Form != Load && 
Form != LoadCopy2.39k
&&
AtomTy.isConstQualified()2.39k
) ||
4783
3.36k
        AtomTy.getAddressSpace() == LangAS::opencl_constant) {
4784
19
      Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
4785
15
          << (AtomTy.isConstQualified() ? 0 : 
14
) << Ptr->getType()
4786
19
          << Ptr->getSourceRange();
4787
19
      return ExprError();
4788
19
    }
4789
3.36k
    ValType = AtomTy->castAs<AtomicType>()->getValueType();
4790
1.77k
  } else if (Form != Load && 
Form != LoadCopy1.35k
) {
4791
1.24k
    if (ValType.isConstQualified()) {
4792
6
      Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
4793
6
          << Ptr->getType() << Ptr->getSourceRange();
4794
6
      return ExprError();
4795
6
    }
4796
5.13k
  }
4797
4798
  // For an arithmetic operation, the implied arithmetic must be well-formed.
4799
5.13k
  if (Form == Arithmetic) {
4800
    // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
4801
1.43k
    if (IsAddSub && 
!ValType->isIntegerType()1.15k
4802
20
        && !ValType->isPointerType()) {
4803
6
      Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4804
6
          << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4805
6
      return ExprError();
4806
6
    }
4807
1.42k
    if (!IsAddSub && 
!ValType->isIntegerType()280
) {
4808
14
      Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int)
4809
14
          << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4810
14
      return ExprError();
4811
14
    }
4812
1.41k
    if (IsC11 && 
ValType->isPointerType()429
&&
4813
8
        RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
4814
1
                            diag::err_incomplete_type)) {
4815
1
      return ExprError();
4816
1
    }
4817
3.70k
  } else if (IsN && 
!ValType->isIntegerType()497
&&
!ValType->isPointerType()12
) {
4818
    // For __atomic_*_n operations, the value type must be a scalar integral or
4819
    // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
4820
5
    Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4821
5
        << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4822
5
    return ExprError();
4823
5
  }
4824
4825
5.10k
  if (!IsC11 && 
!AtomTy.isTriviallyCopyableType(Context)1.75k
&&
4826
2
      !AtomTy->isScalarType()) {
4827
    // For GNU atomics, require a trivially-copyable type. This is not part of
4828
    // the GNU atomics specification, but we enforce it for sanity.
4829
2
    Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
4830
2
        << Ptr->getType() << Ptr->getSourceRange();
4831
2
    return ExprError();
4832
2
  }
4833
4834
5.10k
  switch (ValType.getObjCLifetime()) {
4835
5.10k
  case Qualifiers::OCL_None:
4836
5.10k
  case Qualifiers::OCL_ExplicitNone:
4837
    // okay
4838
5.10k
    break;
4839
4840
0
  case Qualifiers::OCL_Weak:
4841
0
  case Qualifiers::OCL_Strong:
4842
0
  case Qualifiers::OCL_Autoreleasing:
4843
    // FIXME: Can this happen? By this point, ValType should be known
4844
    // to be trivially copyable.
4845
0
    Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
4846
0
        << ValType << Ptr->getSourceRange();
4847
0
    return ExprError();
4848
5.10k
  }
4849
4850
  // All atomic operations have an overload which takes a pointer to a volatile
4851
  // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
4852
  // into the result or the other operands. Similarly atomic_load takes a
4853
  // pointer to a const 'A'.
4854
5.10k
  ValType.removeLocalVolatile();
4855
5.10k
  ValType.removeLocalConst();
4856
5.10k
  QualType ResultType = ValType;
4857
5.10k
  if (Form == Copy || 
Form == LoadCopy4.02k
||
Form == GNUXchg3.91k
||
4858
3.88k
      Form == Init)
4859
1.26k
    ResultType = Context.VoidTy;
4860
3.84k
  else if (Form == C11CmpXchg || 
Form == GNUCmpXchg3.72k
)
4861
194
    ResultType = Context.BoolTy;
4862
4863
  // The type of a parameter passed 'by value'. In the GNU atomics, such
4864
  // arguments are actually passed as pointers.
4865
5.10k
  QualType ByValType = ValType; // 'CP'
4866
5.10k
  bool IsPassedByAddress = false;
4867
5.10k
  if (!IsC11 && 
!IsN1.75k
) {
4868
1.26k
    ByValType = Ptr->getType();
4869
1.26k
    IsPassedByAddress = true;
4870
1.26k
  }
4871
4872
5.10k
  SmallVector<Expr *, 5> APIOrderedArgs;
4873
5.10k
  if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
4874
4
    APIOrderedArgs.push_back(Args[0]);
4875
4
    switch (Form) {
4876
0
    case Init:
4877
0
    case Load:
4878
0
      APIOrderedArgs.push_back(Args[1]); // Val1/Order
4879
0
      break;
4880
2
    case LoadCopy:
4881
2
    case Copy:
4882
2
    case Arithmetic:
4883
2
    case Xchg:
4884
2
      APIOrderedArgs.push_back(Args[2]); // Val1
4885
2
      APIOrderedArgs.push_back(Args[1]); // Order
4886
2
      break;
4887
0
    case GNUXchg:
4888
0
      APIOrderedArgs.push_back(Args[2]); // Val1
4889
0
      APIOrderedArgs.push_back(Args[3]); // Val2
4890
0
      APIOrderedArgs.push_back(Args[1]); // Order
4891
0
      break;
4892
0
    case C11CmpXchg:
4893
0
      APIOrderedArgs.push_back(Args[2]); // Val1
4894
0
      APIOrderedArgs.push_back(Args[4]); // Val2
4895
0
      APIOrderedArgs.push_back(Args[1]); // Order
4896
0
      APIOrderedArgs.push_back(Args[3]); // OrderFail
4897
0
      break;
4898
2
    case GNUCmpXchg:
4899
2
      APIOrderedArgs.push_back(Args[2]); // Val1
4900
2
      APIOrderedArgs.push_back(Args[4]); // Val2
4901
2
      APIOrderedArgs.push_back(Args[5]); // Weak
4902
2
      APIOrderedArgs.push_back(Args[1]); // Order
4903
2
      APIOrderedArgs.push_back(Args[3]); // OrderFail
4904
2
      break;
4905
5.10k
    }
4906
5.10k
  } else
4907
5.10k
    APIOrderedArgs.append(Args.begin(), Args.end());
4908
4909
  // The first argument's non-CV pointer type is used to deduce the type of
4910
  // subsequent arguments, except for:
4911
  //  - weak flag (always converted to bool)
4912
  //  - memory order (always converted to int)
4913
  //  - scope  (always converted to int)
4914
19.7k
  
for (unsigned i = 0; 5.10k
i != APIOrderedArgs.size();
++i14.6k
) {
4915
14.6k
    QualType Ty;
4916
14.6k
    if (i < NumVals[Form] + 1) {
4917
9.10k
      switch (i) {
4918
5.10k
      case 0:
4919
        // The first argument is always a pointer. It has a fixed type.
4920
        // It is always dereferenced, a nullptr is undefined.
4921
5.10k
        CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
4922
        // Nothing else to do: we already know all we want about this pointer.
4923
5.10k
        continue;
4924
3.70k
      case 1:
4925
        // The second argument is the non-atomic operand. For arithmetic, this
4926
        // is always passed by value, and for a compare_exchange it is always
4927
        // passed by address. For the rest, GNU uses by-address and C11 uses
4928
        // by-value.
4929
3.70k
        assert(Form != Load);
4930
3.70k
        if (Form == Init || 
(3.66k
Form == Arithmetic3.66k
&&
ValType->isIntegerType()1.41k
))
4931
1.43k
          Ty = ValType;
4932
2.26k
        else if (Form == Copy || 
Form == Xchg1.19k
) {
4933
1.92k
          if (IsPassedByAddress) {
4934
            // The value pointer is always dereferenced, a nullptr is undefined.
4935
99
            CheckNonNullArgument(*this, APIOrderedArgs[i],
4936
99
                                 ExprRange.getBegin());
4937
99
          }
4938
1.92k
          Ty = ByValType;
4939
349
        } else if (Form == Arithmetic)
4940
13
          Ty = Context.getPointerDiffType();
4941
336
        else {
4942
336
          Expr *ValArg = APIOrderedArgs[i];
4943
          // The value pointer is always dereferenced, a nullptr is undefined.
4944
336
          CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
4945
336
          LangAS AS = LangAS::Default;
4946
          // Keep address space of non-atomic pointer type.
4947
336
          if (const PointerType *PtrTy =
4948
331
                  ValArg->getType()->getAs<PointerType>()) {
4949
331
            AS = PtrTy->getPointeeType().getAddressSpace();
4950
331
          }
4951
336
          Ty = Context.getPointerType(
4952
336
              Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
4953
336
        }
4954
3.70k
        break;
4955
225
      case 2:
4956
        // The third argument to compare_exchange / GNU exchange is the desired
4957
        // value, either by-value (for the C11 and *_n variant) or as a pointer.
4958
225
        if (IsPassedByAddress)
4959
69
          CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
4960
225
        Ty = ByValType;
4961
225
        break;
4962
68
      case 3:
4963
        // The fourth argument to GNU compare_exchange is a 'weak' flag.
4964
68
        Ty = Context.BoolTy;
4965
68
        break;
4966
5.52k
      }
4967
5.52k
    } else {
4968
      // The order(s) and scope are always converted to int.
4969
5.52k
      Ty = Context.IntTy;
4970
5.52k
    }
4971
4972
9.52k
    InitializedEntity Entity =
4973
9.52k
        InitializedEntity::InitializeParameter(Context, Ty, false);
4974
9.52k
    ExprResult Arg = APIOrderedArgs[i];
4975
9.52k
    Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4976
9.52k
    if (Arg.isInvalid())
4977
4
      return true;
4978
9.51k
    APIOrderedArgs[i] = Arg.get();
4979
9.51k
  }
4980
4981
  // Permute the arguments into a 'consistent' order.
4982
5.10k
  SmallVector<Expr*, 5> SubExprs;
4983
5.10k
  SubExprs.push_back(Ptr);
4984
5.10k
  switch (Form) {
4985
39
  case Init:
4986
    // Note, AtomicExpr::getVal1() has a special case for this atomic.
4987
39
    SubExprs.push_back(APIOrderedArgs[1]); // Val1
4988
39
    break;
4989
1.39k
  case Load:
4990
1.39k
    SubExprs.push_back(APIOrderedArgs[1]); // Order
4991
1.39k
    break;
4992
3.44k
  case LoadCopy:
4993
3.44k
  case Copy:
4994
3.44k
  case Arithmetic:
4995
3.44k
  case Xchg:
4996
3.44k
    SubExprs.push_back(APIOrderedArgs[2]); // Order
4997
3.44k
    SubExprs.push_back(APIOrderedArgs[1]); // Val1
4998
3.44k
    break;
4999
31
  case GNUXchg:
5000
    // Note, AtomicExpr::getVal2() has a special case for this atomic.
5001
31
    SubExprs.push_back(APIOrderedArgs[3]); // Order
5002
31
    SubExprs.push_back(APIOrderedArgs[1]); // Val1
5003
31
    SubExprs.push_back(APIOrderedArgs[2]); // Val2
5004
31
    break;
5005
126
  case C11CmpXchg:
5006
126
    SubExprs.push_back(APIOrderedArgs[3]); // Order
5007
126
    SubExprs.push_back(APIOrderedArgs[1]); // Val1
5008
126
    SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
5009
126
    SubExprs.push_back(APIOrderedArgs[2]); // Val2
5010
126
    break;
5011
68
  case GNUCmpXchg:
5012
68
    SubExprs.push_back(APIOrderedArgs[4]); // Order
5013
68
    SubExprs.push_back(APIOrderedArgs[1]); // Val1
5014
68
    SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
5015
68
    SubExprs.push_back(APIOrderedArgs[2]); // Val2
5016
68
    SubExprs.push_back(APIOrderedArgs[3]); // Weak
5017
68
    break;
5018
5.10k
  }
5019
5020
5.10k
  if (SubExprs.size() >= 2 && Form != Init) {
5021
5.06k
    if (Optional<llvm::APSInt> Result =
5022
2.41k
            SubExprs[1]->getIntegerConstantExpr(Context))
5023
2.41k
      if (!isValidOrderingForOp(Result->getSExtValue(), Op))
5024
27
        Diag(SubExprs[1]->getBeginLoc(),
5025
27
             diag::warn_atomic_op_has_invalid_memory_order)
5026
27
            << SubExprs[1]->getSourceRange();
5027
5.06k
  }
5028
5029
5.10k
  if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
5030
257
    auto *Scope = Args[Args.size() - 1];
5031
257
    if (Optional<llvm::APSInt> Result =
5032
245
            Scope->getIntegerConstantExpr(Context)) {
5033
245
      if (!ScopeModel->isValid(Result->getZExtValue()))
5034
4
        Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
5035
4
            << Scope->getSourceRange();
5036
245
    }
5037
257
    SubExprs.push_back(Scope);
5038
257
  }
5039
5040
5.10k
  AtomicExpr *AE = new (Context)
5041
5.10k
      AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
5042
5043
5.10k
  if ((Op == AtomicExpr::AO__c11_atomic_load ||
5044
4.19k
       Op == AtomicExpr::AO__c11_atomic_store ||
5045
3.27k
       Op == AtomicExpr::AO__opencl_atomic_load ||
5046
3.21k
       Op == AtomicExpr::AO__opencl_atomic_store ) &&
5047
1.92k
      Context.AtomicUsesUnsupportedLibcall(AE))
5048
2
    Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
5049
2
        << ((Op == AtomicExpr::AO__c11_atomic_load ||
5050
1
             Op == AtomicExpr::AO__opencl_atomic_load)
5051
1
                ? 0
5052
1
                : 1);
5053
5054
5.10k
  if (ValType->isExtIntType()) {
5055
2
    Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_ext_int_prohibit);
5056
2
    return ExprError();
5057
2
  }
5058
5059
5.10k
  return AE;
5060
5.10k
}
5061
5062
/// checkBuiltinArgument - Given a call to a builtin function, perform
5063
/// normal type-checking on the given argument, updating the call in
5064
/// place.  This is useful when a builtin function requires custom
5065
/// type-checking for some of its arguments but not necessarily all of
5066
/// them.
5067
///
5068
/// Returns true on error.
5069
557
static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
5070
557
  FunctionDecl *Fn = E->getDirectCallee();
5071
557
  assert(Fn && "builtin call without direct callee!");
5072
5073
557
  ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
5074
557
  InitializedEntity Entity =
5075
557
    InitializedEntity::InitializeParameter(S.Context, Param);
5076
5077
557
  ExprResult Arg = E->getArg(0);
5078
557
  Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
5079
557
  if (Arg.isInvalid())
5080
4
    return true;
5081
5082
553
  E->setArg(ArgIndex, Arg.get());
5083
553
  return false;
5084
553
}
5085
5086
/// We have a call to a function like __sync_fetch_and_add, which is an
5087
/// overloaded function based on the pointer type of its first argument.
5088
/// The main BuildCallExpr routines have already promoted the types of
5089
/// arguments because all of these calls are prototyped as void(...).
5090
///
5091
/// This function goes through and does final semantic checking for these
5092
/// builtins, as well as generating any warnings.
5093
ExprResult
5094
266
Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
5095
266
  CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
5096
266
  Expr *Callee = TheCall->getCallee();
5097
266
  DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
5098
266
  FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5099
5100
  // Ensure that we have at least one argument to do type inference from.
5101
266
  if (TheCall->getNumArgs() < 1) {
5102
1
    Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5103
1
        << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
5104
1
    return ExprError();
5105
1
  }
5106
5107
  // Inspect the first argument of the atomic builtin.  This should always be
5108
  // a pointer type, whose element is an integral scalar or pointer type.
5109
  // Because it is a pointer type, we don't have to worry about any implicit
5110
  // casts here.
5111
  // FIXME: We don't allow floating point scalars as input.
5112
265
  Expr *FirstArg = TheCall->getArg(0);
5113
265
  ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
5114
265
  if (FirstArgResult.isInvalid())
5115
0
    return ExprError();
5116
265
  FirstArg = FirstArgResult.get();
5117
265
  TheCall->setArg(0, FirstArg);
5118
5119
265
  const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
5120
265
  if (!pointerType) {
5121
0
    Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
5122
0
        << FirstArg->getType() << FirstArg->getSourceRange();
5123
0
    return ExprError();
5124
0
  }
5125
5126
265
  QualType ValType = pointerType->getPointeeType();
5127
265
  if (!ValType->isIntegerType() && 
!ValType->isAnyPointerType()15
&&
5128
0
      !ValType->isBlockPointerType()) {
5129
0
    Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
5130
0
        << FirstArg->getType() << FirstArg->getSourceRange();
5131
0
    return ExprError();
5132
0
  }
5133
5134
265
  if (ValType.isConstQualified()) {
5135
1
    Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
5136
1
        << FirstArg->getType() << FirstArg->getSourceRange();
5137
1
    return ExprError();
5138
1
  }
5139
5140
264
  switch (ValType.getObjCLifetime()) {
5141
262
  case Qualifiers::OCL_None:
5142
262
  case Qualifiers::OCL_ExplicitNone:
5143
    // okay
5144
262
    break;
5145
5146
2
  case Qualifiers::OCL_Weak:
5147
2
  case Qualifiers::OCL_Strong:
5148
2
  case Qualifiers::OCL_Autoreleasing:
5149
2
    Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
5150
2
        << ValType << FirstArg->getSourceRange();
5151
2
    return ExprError();
5152
262
  }
5153
5154
  // Strip any qualifiers off ValType.
5155
262
  ValType = ValType.getUnqualifiedType();
5156
5157
  // The majority of builtins return a value, but a few have special return
5158
  // types, so allow them to override appropriately below.
5159