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
getLocationOfStringLiteralByte(const StringLiteral * SL,unsigned ByteNo) const104 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
105 unsigned ByteNo) const {
106 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
107 Context.getTargetInfo());
108 }
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.
checkArgCount(Sema & S,CallExpr * call,unsigned desiredArgCount)112 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
113 unsigned argCount = call->getNumArgs();
114 if (argCount == desiredArgCount) return false;
115
116 if (argCount < desiredArgCount)
117 return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args)
118 << 0 /*function call*/ << desiredArgCount << argCount
119 << call->getSourceRange();
120
121 // Highlight all the excess arguments.
122 SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(),
123 call->getArg(argCount - 1)->getEndLoc());
124
125 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
126 << 0 /*function call*/ << desiredArgCount << argCount
127 << call->getArg(1)->getSourceRange();
128 }
129
130 /// Check that the first argument to __builtin_annotation is an integer
131 /// and the second argument is a non-wide string literal.
SemaBuiltinAnnotation(Sema & S,CallExpr * TheCall)132 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
133 if (checkArgCount(S, TheCall, 2))
134 return true;
135
136 // First argument should be an integer.
137 Expr *ValArg = TheCall->getArg(0);
138 QualType Ty = ValArg->getType();
139 if (!Ty->isIntegerType()) {
140 S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
141 << ValArg->getSourceRange();
142 return true;
143 }
144
145 // Second argument should be a constant string.
146 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
147 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
148 if (!Literal || !Literal->isAscii()) {
149 S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
150 << StrArg->getSourceRange();
151 return true;
152 }
153
154 TheCall->setType(Ty);
155 return false;
156 }
157
SemaBuiltinMSVCAnnotation(Sema & S,CallExpr * TheCall)158 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
159 // We need at least one argument.
160 if (TheCall->getNumArgs() < 1) {
161 S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
162 << 0 << 1 << TheCall->getNumArgs()
163 << TheCall->getCallee()->getSourceRange();
164 return true;
165 }
166
167 // All arguments should be wide string literals.
168 for (Expr *Arg : TheCall->arguments()) {
169 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
170 if (!Literal || !Literal->isWide()) {
171 S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
172 << Arg->getSourceRange();
173 return true;
174 }
175 }
176
177 return false;
178 }
179
180 /// Check that the argument to __builtin_addressof is a glvalue, and set the
181 /// result type to the corresponding pointer type.
SemaBuiltinAddressof(Sema & S,CallExpr * TheCall)182 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
183 if (checkArgCount(S, TheCall, 1))
184 return true;
185
186 ExprResult Arg(TheCall->getArg(0));
187 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
188 if (ResultType.isNull())
189 return true;
190
191 TheCall->setArg(0, Arg.get());
192 TheCall->setType(ResultType);
193 return false;
194 }
195
196 /// Check the number of arguments and set the result type to
197 /// the argument type.
SemaBuiltinPreserveAI(Sema & S,CallExpr * TheCall)198 static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
199 if (checkArgCount(S, TheCall, 1))
200 return true;
201
202 TheCall->setType(TheCall->getArg(0)->getType());
203 return false;
204 }
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.
SemaBuiltinAlignment(Sema & S,CallExpr * TheCall,unsigned ID)209 static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) {
210 if (checkArgCount(S, TheCall, 2))
211 return true;
212
213 clang::Expr *Source = TheCall->getArg(0);
214 bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned;
215
216 auto IsValidIntegerType = [](QualType Ty) {
217 return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType();
218 };
219 QualType SrcTy = Source->getType();
220 // We should also be able to use it with arrays (but not functions!).
221 if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) {
222 SrcTy = S.Context.getDecayedType(SrcTy);
223 }
224 if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) ||
225 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 S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand)
229 << SrcTy;
230 return true;
231 }
232
233 clang::Expr *AlignOp = TheCall->getArg(1);
234 if (!IsValidIntegerType(AlignOp->getType())) {
235 S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int)
236 << AlignOp->getType();
237 return true;
238 }
239 Expr::EvalResult AlignResult;
240 unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1;
241 // We can't check validity of alignment if it is value dependent.
242 if (!AlignOp->isValueDependent() &&
243 AlignOp->EvaluateAsInt(AlignResult, S.Context,
244 Expr::SE_AllowSideEffects)) {
245 llvm::APSInt AlignValue = AlignResult.Val.getInt();
246 llvm::APSInt MaxValue(
247 llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits));
248 if (AlignValue < 1) {
249 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1;
250 return true;
251 }
252 if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) {
253 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big)
254 << MaxValue.toString(10);
255 return true;
256 }
257 if (!AlignValue.isPowerOf2()) {
258 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two);
259 return true;
260 }
261 if (AlignValue == 1) {
262 S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless)
263 << IsBooleanAlignBuiltin;
264 }
265 }
266
267 ExprResult SrcArg = S.PerformCopyInitialization(
268 InitializedEntity::InitializeParameter(S.Context, SrcTy, false),
269 SourceLocation(), Source);
270 if (SrcArg.isInvalid())
271 return true;
272 TheCall->setArg(0, SrcArg.get());
273 ExprResult AlignArg =
274 S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
275 S.Context, AlignOp->getType(), false),
276 SourceLocation(), AlignOp);
277 if (AlignArg.isInvalid())
278 return true;
279 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 TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy);
284 return false;
285 }
286
SemaBuiltinOverflow(Sema & S,CallExpr * TheCall,unsigned BuiltinID)287 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall,
288 unsigned BuiltinID) {
289 if (checkArgCount(S, TheCall, 3))
290 return true;
291
292 // First two arguments should be integers.
293 for (unsigned I = 0; I < 2; ++I) {
294 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(I));
295 if (Arg.isInvalid()) return true;
296 TheCall->setArg(I, Arg.get());
297
298 QualType Ty = Arg.get()->getType();
299 if (!Ty->isIntegerType()) {
300 S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
301 << Ty << Arg.get()->getSourceRange();
302 return true;
303 }
304 }
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 {
310 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(2));
311 if (Arg.isInvalid()) return true;
312 TheCall->setArg(2, Arg.get());
313
314 QualType Ty = Arg.get()->getType();
315 const auto *PtrTy = Ty->getAs<PointerType>();
316 if (!PtrTy ||
317 !PtrTy->getPointeeType()->isIntegerType() ||
318 PtrTy->getPointeeType().isConstQualified()) {
319 S.Diag(Arg.get()->getBeginLoc(),
320 diag::err_overflow_builtin_must_be_ptr_int)
321 << Ty << Arg.get()->getSourceRange();
322 return true;
323 }
324 }
325
326 // Disallow signed ExtIntType args larger than 128 bits to mul function until
327 // we improve backend support.
328 if (BuiltinID == Builtin::BI__builtin_mul_overflow) {
329 for (unsigned I = 0; I < 3; ++I) {
330 const auto Arg = TheCall->getArg(I);
331 // Third argument will be a pointer.
332 auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType();
333 if (Ty->isExtIntType() && Ty->isSignedIntegerType() &&
334 S.getASTContext().getIntWidth(Ty) > 128)
335 return S.Diag(Arg->getBeginLoc(),
336 diag::err_overflow_builtin_ext_int_max_size)
337 << 128;
338 }
339 }
340
341 return false;
342 }
343
SemaBuiltinCallWithStaticChain(Sema & S,CallExpr * BuiltinCall)344 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
345 if (checkArgCount(S, BuiltinCall, 2))
346 return true;
347
348 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
349 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
350 Expr *Call = BuiltinCall->getArg(0);
351 Expr *Chain = BuiltinCall->getArg(1);
352
353 if (Call->getStmtClass() != Stmt::CallExprClass) {
354 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
355 << Call->getSourceRange();
356 return true;
357 }
358
359 auto CE = cast<CallExpr>(Call);
360 if (CE->getCallee()->getType()->isBlockPointerType()) {
361 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
362 << Call->getSourceRange();
363 return true;
364 }
365
366 const Decl *TargetDecl = CE->getCalleeDecl();
367 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
368 if (FD->getBuiltinID()) {
369 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
370 << Call->getSourceRange();
371 return true;
372 }
373
374 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
375 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
376 << Call->getSourceRange();
377 return true;
378 }
379
380 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
381 if (ChainResult.isInvalid())
382 return true;
383 if (!ChainResult.get()->getType()->isPointerType()) {
384 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
385 << Chain->getSourceRange();
386 return true;
387 }
388
389 QualType ReturnTy = CE->getCallReturnType(S.Context);
390 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
391 QualType BuiltinTy = S.Context.getFunctionType(
392 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
393 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
394
395 Builtin =
396 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
397
398 BuiltinCall->setType(CE->getType());
399 BuiltinCall->setValueKind(CE->getValueKind());
400 BuiltinCall->setObjectKind(CE->getObjectKind());
401 BuiltinCall->setCallee(Builtin);
402 BuiltinCall->setArg(1, ChainResult.get());
403
404 return false;
405 }
406
407 namespace {
408
409 class EstimateSizeFormatHandler
410 : public analyze_format_string::FormatStringHandler {
411 size_t Size;
412
413 public:
EstimateSizeFormatHandler(StringRef Format)414 EstimateSizeFormatHandler(StringRef Format)
415 : Size(std::min(Format.find(0), Format.size()) +
416 1 /* null byte always written by sprintf */) {}
417
HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier & FS,const char *,unsigned SpecifierLen)418 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
419 const char *, unsigned SpecifierLen) override {
420
421 const size_t FieldWidth = computeFieldWidth(FS);
422 const size_t Precision = computePrecision(FS);
423
424 // The actual format.
425 switch (FS.getConversionSpecifier().getKind()) {
426 // Just a char.
427 case analyze_format_string::ConversionSpecifier::cArg:
428 case analyze_format_string::ConversionSpecifier::CArg:
429 Size += std::max(FieldWidth, (size_t)1);
430 break;
431 // Just an integer.
432 case analyze_format_string::ConversionSpecifier::dArg:
433 case analyze_format_string::ConversionSpecifier::DArg:
434 case analyze_format_string::ConversionSpecifier::iArg:
435 case analyze_format_string::ConversionSpecifier::oArg:
436 case analyze_format_string::ConversionSpecifier::OArg:
437 case analyze_format_string::ConversionSpecifier::uArg:
438 case analyze_format_string::ConversionSpecifier::UArg:
439 case analyze_format_string::ConversionSpecifier::xArg:
440 case analyze_format_string::ConversionSpecifier::XArg:
441 Size += std::max(FieldWidth, Precision);
442 break;
443
444 // %g style conversion switches between %f or %e style dynamically.
445 // %f always takes less space, so default to it.
446 case analyze_format_string::ConversionSpecifier::gArg:
447 case analyze_format_string::ConversionSpecifier::GArg:
448
449 // Floating point number in the form '[+]ddd.ddd'.
450 case analyze_format_string::ConversionSpecifier::fArg:
451 case analyze_format_string::ConversionSpecifier::FArg:
452 Size += std::max(FieldWidth, 1 /* integer part */ +
453 (Precision ? 1 + Precision
454 : 0) /* period + decimal */);
455 break;
456
457 // Floating point number in the form '[-]d.ddde[+-]dd'.
458 case analyze_format_string::ConversionSpecifier::eArg:
459 case analyze_format_string::ConversionSpecifier::EArg:
460 Size +=
461 std::max(FieldWidth,
462 1 /* integer part */ +
463 (Precision ? 1 + Precision : 0) /* period + decimal */ +
464 1 /* e or E letter */ + 2 /* exponent */);
465 break;
466
467 // Floating point number in the form '[-]0xh.hhhhp±dd'.
468 case analyze_format_string::ConversionSpecifier::aArg:
469 case analyze_format_string::ConversionSpecifier::AArg:
470 Size +=
471 std::max(FieldWidth,
472 2 /* 0x */ + 1 /* integer part */ +
473 (Precision ? 1 + Precision : 0) /* period + decimal */ +
474 1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
475 break;
476
477 // Just a string.
478 case analyze_format_string::ConversionSpecifier::sArg:
479 case analyze_format_string::ConversionSpecifier::SArg:
480 Size += FieldWidth;
481 break;
482
483 // Just a pointer in the form '0xddd'.
484 case analyze_format_string::ConversionSpecifier::pArg:
485 Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision);
486 break;
487
488 // A plain percent.
489 case analyze_format_string::ConversionSpecifier::PercentArg:
490 Size += 1;
491 break;
492
493 default:
494 break;
495 }
496
497 Size += FS.hasPlusPrefix() || FS.hasSpacePrefix();
498
499 if (FS.hasAlternativeForm()) {
500 switch (FS.getConversionSpecifier().getKind()) {
501 default:
502 break;
503 // Force a leading '0'.
504 case analyze_format_string::ConversionSpecifier::oArg:
505 Size += 1;
506 break;
507 // Force a leading '0x'.
508 case analyze_format_string::ConversionSpecifier::xArg:
509 case analyze_format_string::ConversionSpecifier::XArg:
510 Size += 2;
511 break;
512 // Force a period '.' before decimal, even if precision is 0.
513 case analyze_format_string::ConversionSpecifier::aArg:
514 case analyze_format_string::ConversionSpecifier::AArg:
515 case analyze_format_string::ConversionSpecifier::eArg:
516 case analyze_format_string::ConversionSpecifier::EArg:
517 case analyze_format_string::ConversionSpecifier::fArg:
518 case analyze_format_string::ConversionSpecifier::FArg:
519 case analyze_format_string::ConversionSpecifier::gArg:
520 case analyze_format_string::ConversionSpecifier::GArg:
521 Size += (Precision ? 0 : 1);
522 break;
523 }
524 }
525 assert(SpecifierLen <= Size && "no underflow");
526 Size -= SpecifierLen;
527 return true;
528 }
529
getSizeLowerBound() const530 size_t getSizeLowerBound() const { return Size; }
531
532 private:
computeFieldWidth(const analyze_printf::PrintfSpecifier & FS)533 static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
534 const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
535 size_t FieldWidth = 0;
536 if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant)
537 FieldWidth = FW.getConstantAmount();
538 return FieldWidth;
539 }
540
computePrecision(const analyze_printf::PrintfSpecifier & FS)541 static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
542 const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
543 size_t Precision = 0;
544
545 // See man 3 printf for default precision value based on the specifier.
546 switch (FW.getHowSpecified()) {
547 case analyze_format_string::OptionalAmount::NotSpecified:
548 switch (FS.getConversionSpecifier().getKind()) {
549 default:
550 break;
551 case analyze_format_string::ConversionSpecifier::dArg: // %d
552 case analyze_format_string::ConversionSpecifier::DArg: // %D
553 case analyze_format_string::ConversionSpecifier::iArg: // %i
554 Precision = 1;
555 break;
556 case analyze_format_string::ConversionSpecifier::oArg: // %d
557 case analyze_format_string::ConversionSpecifier::OArg: // %D
558 case analyze_format_string::ConversionSpecifier::uArg: // %d
559 case analyze_format_string::ConversionSpecifier::UArg: // %D
560 case analyze_format_string::ConversionSpecifier::xArg: // %d
561 case analyze_format_string::ConversionSpecifier::XArg: // %D
562 Precision = 1;
563 break;
564 case analyze_format_string::ConversionSpecifier::fArg: // %f
565 case analyze_format_string::ConversionSpecifier::FArg: // %F
566 case analyze_format_string::ConversionSpecifier::eArg: // %e
567 case analyze_format_string::ConversionSpecifier::EArg: // %E
568 case analyze_format_string::ConversionSpecifier::gArg: // %g
569 case analyze_format_string::ConversionSpecifier::GArg: // %G
570 Precision = 6;
571 break;
572 case analyze_format_string::ConversionSpecifier::pArg: // %d
573 Precision = 1;
574 break;
575 }
576 break;
577 case analyze_format_string::OptionalAmount::Constant:
578 Precision = FW.getConstantAmount();
579 break;
580 default:
581 break;
582 }
583 return Precision;
584 }
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.
checkFortifiedBuiltinMemoryFunction(FunctionDecl * FD,CallExpr * TheCall)592 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
593 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 if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
598 isConstantEvaluated())
599 return;
600
601 unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true);
602 if (!BuiltinID)
603 return;
604
605 const TargetInfo &TI = getASTContext().getTargetInfo();
606 unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
607
608 unsigned DiagID = 0;
609 bool IsChkVariant = false;
610 Optional<llvm::APSInt> UsedSize;
611 unsigned SizeIndex, ObjectIndex;
612 switch (BuiltinID) {
613 default:
614 return;
615 case Builtin::BIsprintf:
616 case Builtin::BI__builtin___sprintf_chk: {
617 size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;
618 auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
619
620 if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) {
621
622 if (!Format->isAscii() && !Format->isUTF8())
623 return;
624
625 StringRef FormatStrRef = Format->getString();
626 EstimateSizeFormatHandler H(FormatStrRef);
627 const char *FormatBytes = FormatStrRef.data();
628 const ConstantArrayType *T =
629 Context.getAsConstantArrayType(Format->getType());
630 assert(T && "String literal not of constant array type!");
631 size_t TypeSize = T->getSize().getZExtValue();
632
633 // In case there's a null byte somewhere.
634 size_t StrLen =
635 std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
636 if (!analyze_format_string::ParsePrintfString(
637 H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
638 Context.getTargetInfo(), false)) {
639 DiagID = diag::warn_fortify_source_format_overflow;
640 UsedSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound())
641 .extOrTrunc(SizeTypeWidth);
642 if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
643 IsChkVariant = true;
644 ObjectIndex = 2;
645 } else {
646 IsChkVariant = false;
647 ObjectIndex = 0;
648 }
649 break;
650 }
651 }
652 return;
653 }
654 case Builtin::BI__builtin___memcpy_chk:
655 case Builtin::BI__builtin___memmove_chk:
656 case Builtin::BI__builtin___memset_chk:
657 case Builtin::BI__builtin___strlcat_chk:
658 case Builtin::BI__builtin___strlcpy_chk:
659 case Builtin::BI__builtin___strncat_chk:
660 case Builtin::BI__builtin___strncpy_chk:
661 case Builtin::BI__builtin___stpncpy_chk:
662 case Builtin::BI__builtin___memccpy_chk:
663 case Builtin::BI__builtin___mempcpy_chk: {
664 DiagID = diag::warn_builtin_chk_overflow;
665 IsChkVariant = true;
666 SizeIndex = TheCall->getNumArgs() - 2;
667 ObjectIndex = TheCall->getNumArgs() - 1;
668 break;
669 }
670
671 case Builtin::BI__builtin___snprintf_chk:
672 case Builtin::BI__builtin___vsnprintf_chk: {
673 DiagID = diag::warn_builtin_chk_overflow;
674 IsChkVariant = true;
675 SizeIndex = 1;
676 ObjectIndex = 3;
677 break;
678 }
679
680 case Builtin::BIstrncat:
681 case Builtin::BI__builtin_strncat:
682 case Builtin::BIstrncpy:
683 case Builtin::BI__builtin_strncpy:
684 case Builtin::BIstpncpy:
685 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 DiagID = diag::warn_fortify_source_size_mismatch;
692 SizeIndex = TheCall->getNumArgs() - 1;
693 ObjectIndex = 0;
694 break;
695 }
696
697 case Builtin::BImemcpy:
698 case Builtin::BI__builtin_memcpy:
699 case Builtin::BImemmove:
700 case Builtin::BI__builtin_memmove:
701 case Builtin::BImemset:
702 case Builtin::BI__builtin_memset:
703 case Builtin::BImempcpy:
704 case Builtin::BI__builtin_mempcpy: {
705 DiagID = diag::warn_fortify_source_overflow;
706 SizeIndex = TheCall->getNumArgs() - 1;
707 ObjectIndex = 0;
708 break;
709 }
710 case Builtin::BIsnprintf:
711 case Builtin::BI__builtin_snprintf:
712 case Builtin::BIvsnprintf:
713 case Builtin::BI__builtin_vsnprintf: {
714 DiagID = diag::warn_fortify_source_size_mismatch;
715 SizeIndex = 1;
716 ObjectIndex = 0;
717 break;
718 }
719 }
720
721 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 if (IsChkVariant) {
725 Expr::EvalResult Result;
726 Expr *SizeArg = TheCall->getArg(ObjectIndex);
727 if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
728 return;
729 ObjectSize = Result.Val.getInt();
730
731 // Otherwise, try to evaluate an imaginary call to __builtin_object_size.
732 } 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 int BOSType = 0;
737 if (const auto *POS =
738 FD->getParamDecl(ObjectIndex)->getAttr<PassObjectSizeAttr>())
739 BOSType = POS->getType();
740
741 Expr *ObjArg = TheCall->getArg(ObjectIndex);
742 uint64_t Result;
743 if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
744 return;
745 // Get the object size in the target's size_t width.
746 ObjectSize = llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
747 }
748
749 // Evaluate the number of bytes of the object that this call will use.
750 if (!UsedSize) {
751 Expr::EvalResult Result;
752 Expr *UsedSizeArg = TheCall->getArg(SizeIndex);
753 if (!UsedSizeArg->EvaluateAsInt(Result, getASTContext()))
754 return;
755 UsedSize = Result.Val.getInt().extOrTrunc(SizeTypeWidth);
756 }
757
758 if (UsedSize.getValue().ule(ObjectSize))
759 return;
760
761 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 if (IsChkVariant) {
765 FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
766 FunctionName = FunctionName.drop_back(std::strlen("_chk"));
767 } else if (FunctionName.startswith("__builtin_")) {
768 FunctionName = FunctionName.drop_front(std::strlen("__builtin_"));
769 }
770
771 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
772 PDiag(DiagID)
773 << FunctionName << ObjectSize.toString(/*Radix=*/10)
774 << UsedSize.getValue().toString(/*Radix=*/10));
775 }
776
SemaBuiltinSEHScopeCheck(Sema & SemaRef,CallExpr * TheCall,Scope::ScopeFlags NeededScopeFlags,unsigned DiagID)777 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
778 Scope::ScopeFlags NeededScopeFlags,
779 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 if (SemaRef.inTemplateInstantiation())
784 return false;
785
786 Scope *S = SemaRef.getCurScope();
787 while (S && !S->isSEHExceptScope())
788 S = S->getParent();
789 if (!S || !(S->getFlags() & NeededScopeFlags)) {
790 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
791 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
792 << DRE->getDecl()->getIdentifier();
793 return true;
794 }
795
796 return false;
797 }
798
isBlockPointer(Expr * Arg)799 static inline bool isBlockPointer(Expr *Arg) {
800 return Arg->getType()->isBlockPointerType();
801 }
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.
checkOpenCLBlockArgs(Sema & S,Expr * BlockArg)805 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
806 const BlockPointerType *BPT =
807 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
808 ArrayRef<QualType> Params =
809 BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes();
810 unsigned ArgCounter = 0;
811 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 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
815 I != E; ++I, ++ArgCounter) {
816 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
817 (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
818 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 SourceLocation ErrorLoc;
823 if (isa<BlockExpr>(BlockArg)) {
824 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
825 ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
826 } else if (isa<DeclRefExpr>(BlockArg)) {
827 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
828 }
829 S.Diag(ErrorLoc,
830 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
831 IllegalParams = true;
832 }
833 }
834
835 return IllegalParams;
836 }
837
checkOpenCLSubgroupExt(Sema & S,CallExpr * Call)838 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
839 if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
840 S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
841 << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
842 return true;
843 }
844 return false;
845 }
846
SemaOpenCLBuiltinNDRangeAndBlock(Sema & S,CallExpr * TheCall)847 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
848 if (checkArgCount(S, TheCall, 2))
849 return true;
850
851 if (checkOpenCLSubgroupExt(S, TheCall))
852 return true;
853
854 // First argument is an ndrange_t type.
855 Expr *NDRangeArg = TheCall->getArg(0);
856 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
857 S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
858 << TheCall->getDirectCallee() << "'ndrange_t'";
859 return true;
860 }
861
862 Expr *BlockArg = TheCall->getArg(1);
863 if (!isBlockPointer(BlockArg)) {
864 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
865 << TheCall->getDirectCallee() << "block";
866 return true;
867 }
868 return checkOpenCLBlockArgs(S, BlockArg);
869 }
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.
SemaOpenCLBuiltinKernelWorkGroupSize(Sema & S,CallExpr * TheCall)874 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
875 if (checkArgCount(S, TheCall, 1))
876 return true;
877
878 Expr *BlockArg = TheCall->getArg(0);
879 if (!isBlockPointer(BlockArg)) {
880 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
881 << TheCall->getDirectCallee() << "block";
882 return true;
883 }
884 return checkOpenCLBlockArgs(S, BlockArg);
885 }
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
checkOpenCLEnqueueLocalSizeArgs(Sema & S,CallExpr * TheCall,unsigned Start,unsigned End)891 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
892 unsigned Start, unsigned End) {
893 bool IllegalParams = false;
894 for (unsigned I = Start; I <= End; ++I)
895 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
896 S.Context.getSizeType());
897 return IllegalParams;
898 }
899
900 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
901 /// 'local void*' parameter of passed block.
checkOpenCLEnqueueVariadicArgs(Sema & S,CallExpr * TheCall,Expr * BlockArg,unsigned NumNonVarArgs)902 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
903 Expr *BlockArg,
904 unsigned NumNonVarArgs) {
905 const BlockPointerType *BPT =
906 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
907 unsigned NumBlockParams =
908 BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams();
909 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 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
914 S.Diag(TheCall->getBeginLoc(),
915 diag::err_opencl_enqueue_kernel_local_size_args);
916 return true;
917 }
918
919 // Check that the sizes of the local memory are specified by integers.
920 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
921 TotalNumArgs - 1);
922 }
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, ...)
SemaOpenCLBuiltinEnqueueKernel(Sema & S,CallExpr * TheCall)950 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
951 unsigned NumArgs = TheCall->getNumArgs();
952
953 if (NumArgs < 4) {
954 S.Diag(TheCall->getBeginLoc(),
955 diag::err_typecheck_call_too_few_args_at_least)
956 << 0 << 4 << NumArgs;
957 return true;
958 }
959
960 Expr *Arg0 = TheCall->getArg(0);
961 Expr *Arg1 = TheCall->getArg(1);
962 Expr *Arg2 = TheCall->getArg(2);
963 Expr *Arg3 = TheCall->getArg(3);
964
965 // First argument always needs to be a queue_t type.
966 if (!Arg0->getType()->isQueueT()) {
967 S.Diag(TheCall->getArg(0)->getBeginLoc(),
968 diag::err_opencl_builtin_expected_type)
969 << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
970 return true;
971 }
972
973 // Second argument always needs to be a kernel_enqueue_flags_t enum value.
974 if (!Arg1->getType()->isIntegerType()) {
975 S.Diag(TheCall->getArg(1)->getBeginLoc(),
976 diag::err_opencl_builtin_expected_type)
977 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
978 return true;
979 }
980
981 // Third argument is always an ndrange_t type.
982 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
983 S.Diag(TheCall->getArg(2)->getBeginLoc(),
984 diag::err_opencl_builtin_expected_type)
985 << TheCall->getDirectCallee() << "'ndrange_t'";
986 return true;
987 }
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 if (NumArgs == 4) {
992 // check that the last argument is the right block type.
993 if (!isBlockPointer(Arg3)) {
994 S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
995 << TheCall->getDirectCallee() << "block";
996 return true;
997 }
998 // we have a block type, check the prototype
999 const BlockPointerType *BPT =
1000 cast<BlockPointerType>(Arg3->getType().getCanonicalType());
1001 if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) {
1002 S.Diag(Arg3->getBeginLoc(),
1003 diag::err_opencl_enqueue_kernel_blocks_no_args);
1004 return true;
1005 }
1006 return false;
1007 }
1008 // we can have block + varargs.
1009 if (isBlockPointer(Arg3))
1010 return (checkOpenCLBlockArgs(S, Arg3) ||
1011 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
1012 // last two cases with either exactly 7 args or 7 args and varargs.
1013 if (NumArgs >= 7) {
1014 // check common block argument.
1015 Expr *Arg6 = TheCall->getArg(6);
1016 if (!isBlockPointer(Arg6)) {
1017 S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1018 << TheCall->getDirectCallee() << "block";
1019 return true;
1020 }
1021 if (checkOpenCLBlockArgs(S, Arg6))
1022 return true;
1023
1024 // Forth argument has to be any integer type.
1025 if (!Arg3->getType()->isIntegerType()) {
1026 S.Diag(TheCall->getArg(3)->getBeginLoc(),
1027 diag::err_opencl_builtin_expected_type)
1028 << TheCall->getDirectCallee() << "integer";
1029 return true;
1030 }
1031 // check remaining common arguments.
1032 Expr *Arg4 = TheCall->getArg(4);
1033 Expr *Arg5 = TheCall->getArg(5);
1034
1035 // Fifth argument is always passed as a pointer to clk_event_t.
1036 if (!Arg4->isNullPointerConstant(S.Context,
1037 Expr::NPC_ValueDependentIsNotNull) &&
1038 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
1039 S.Diag(TheCall->getArg(4)->getBeginLoc(),
1040 diag::err_opencl_builtin_expected_type)
1041 << TheCall->getDirectCallee()
1042 << S.Context.getPointerType(S.Context.OCLClkEventTy);
1043 return true;
1044 }
1045
1046 // Sixth argument is always passed as a pointer to clk_event_t.
1047 if (!Arg5->isNullPointerConstant(S.Context,
1048 Expr::NPC_ValueDependentIsNotNull) &&
1049 !(Arg5->getType()->isPointerType() &&
1050 Arg5->getType()->getPointeeType()->isClkEventT())) {
1051 S.Diag(TheCall->getArg(5)->getBeginLoc(),
1052 diag::err_opencl_builtin_expected_type)
1053 << TheCall->getDirectCallee()
1054 << S.Context.getPointerType(S.Context.OCLClkEventTy);
1055 return true;
1056 }
1057
1058 if (NumArgs == 7)
1059 return false;
1060
1061 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
1062 }
1063
1064 // None of the specific case has been detected, give generic error
1065 S.Diag(TheCall->getBeginLoc(),
1066 diag::err_opencl_enqueue_kernel_incorrect_args);
1067 return true;
1068 }
1069
1070 /// Returns OpenCL access qual.
getOpenCLArgAccess(const Decl * D)1071 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
1072 return D->getAttr<OpenCLAccessAttr>();
1073 }
1074
1075 /// Returns true if pipe element type is different from the pointer.
checkOpenCLPipeArg(Sema & S,CallExpr * Call)1076 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
1077 const Expr *Arg0 = Call->getArg(0);
1078 // First argument type should always be pipe.
1079 if (!Arg0->getType()->isPipeType()) {
1080 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1081 << Call->getDirectCallee() << Arg0->getSourceRange();
1082 return true;
1083 }
1084 OpenCLAccessAttr *AccessQual =
1085 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 switch (Call->getDirectCallee()->getBuiltinID()) {
1091 case Builtin::BIread_pipe:
1092 case Builtin::BIreserve_read_pipe:
1093 case Builtin::BIcommit_read_pipe:
1094 case Builtin::BIwork_group_reserve_read_pipe:
1095 case Builtin::BIsub_group_reserve_read_pipe:
1096 case Builtin::BIwork_group_commit_read_pipe:
1097 case Builtin::BIsub_group_commit_read_pipe:
1098 if (!(!AccessQual || AccessQual->isReadOnly())) {
1099 S.Diag(Arg0->getBeginLoc(),
1100 diag::err_opencl_builtin_pipe_invalid_access_modifier)
1101 << "read_only" << Arg0->getSourceRange();
1102 return true;
1103 }
1104 break;
1105 case Builtin::BIwrite_pipe:
1106 case Builtin::BIreserve_write_pipe:
1107 case Builtin::BIcommit_write_pipe:
1108 case Builtin::BIwork_group_reserve_write_pipe:
1109 case Builtin::BIsub_group_reserve_write_pipe:
1110 case Builtin::BIwork_group_commit_write_pipe:
1111 case Builtin::BIsub_group_commit_write_pipe:
1112 if (!(AccessQual && AccessQual->isWriteOnly())) {
1113 S.Diag(Arg0->getBeginLoc(),
1114 diag::err_opencl_builtin_pipe_invalid_access_modifier)
1115 << "write_only" << Arg0->getSourceRange();
1116 return true;
1117 }
1118 break;
1119 default:
1120 break;
1121 }
1122 return false;
1123 }
1124
1125 /// Returns true if pipe element type is different from the pointer.
checkOpenCLPipePacketType(Sema & S,CallExpr * Call,unsigned Idx)1126 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
1127 const Expr *Arg0 = Call->getArg(0);
1128 const Expr *ArgIdx = Call->getArg(Idx);
1129 const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
1130 const QualType EltTy = PipeTy->getElementType();
1131 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 if (!ArgTy ||
1135 !S.Context.hasSameType(
1136 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
1137 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1138 << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
1139 << ArgIdx->getType() << ArgIdx->getSourceRange();
1140 return true;
1141 }
1142 return false;
1143 }
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.
SemaBuiltinRWPipe(Sema & S,CallExpr * Call)1149 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 switch (Call->getNumArgs()) {
1153 case 2:
1154 if (checkOpenCLPipeArg(S, Call))
1155 return true;
1156 // The call with 2 arguments should be
1157 // read/write_pipe(pipe T, T*).
1158 // Check packet type T.
1159 if (checkOpenCLPipePacketType(S, Call, 1))
1160 return true;
1161 break;
1162
1163 case 4: {
1164 if (checkOpenCLPipeArg(S, Call))
1165 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 if (!Call->getArg(1)->getType()->isReserveIDT()) {
1170 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1171 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1172 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1173 return true;
1174 }
1175
1176 // Check the index.
1177 const Expr *Arg2 = Call->getArg(2);
1178 if (!Arg2->getType()->isIntegerType() &&
1179 !Arg2->getType()->isUnsignedIntegerType()) {
1180 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1181 << Call->getDirectCallee() << S.Context.UnsignedIntTy
1182 << Arg2->getType() << Arg2->getSourceRange();
1183 return true;
1184 }
1185
1186 // Check packet type T.
1187 if (checkOpenCLPipePacketType(S, Call, 3))
1188 return true;
1189 } break;
1190 default:
1191 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
1192 << Call->getDirectCallee() << Call->getSourceRange();
1193 return true;
1194 }
1195
1196 return false;
1197 }
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.
SemaBuiltinReserveRWPipe(Sema & S,CallExpr * Call)1204 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
1205 if (checkArgCount(S, Call, 2))
1206 return true;
1207
1208 if (checkOpenCLPipeArg(S, Call))
1209 return true;
1210
1211 // Check the reserve size.
1212 if (!Call->getArg(1)->getType()->isIntegerType() &&
1213 !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
1214 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1215 << Call->getDirectCallee() << S.Context.UnsignedIntTy
1216 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1217 return true;
1218 }
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 Call->setType(S.Context.OCLReserveIDTy);
1224
1225 return false;
1226 }
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.
SemaBuiltinCommitRWPipe(Sema & S,CallExpr * Call)1233 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
1234 if (checkArgCount(S, Call, 2))
1235 return true;
1236
1237 if (checkOpenCLPipeArg(S, Call))
1238 return true;
1239
1240 // Check reserve_id_t.
1241 if (!Call->getArg(1)->getType()->isReserveIDT()) {
1242 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1243 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1244 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1245 return true;
1246 }
1247
1248 return false;
1249 }
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.
SemaBuiltinPipePackets(Sema & S,CallExpr * Call)1256 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
1257 if (checkArgCount(S, Call, 1))
1258 return true;
1259
1260 if (!Call->getArg(0)->getType()->isPipeType()) {
1261 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1262 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
1263 return true;
1264 }
1265
1266 return false;
1267 }
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.
SemaOpenCLBuiltinToAddr(Sema & S,unsigned BuiltinID,CallExpr * Call)1275 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
1276 CallExpr *Call) {
1277 if (checkArgCount(S, Call, 1))
1278 return true;
1279
1280 auto RT = Call->getArg(0)->getType();
1281 if (!RT->isPointerType() || RT->getPointeeType()
1282 .getAddressSpace() == LangAS::opencl_constant) {
1283 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
1284 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
1285 return true;
1286 }
1287
1288 if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
1289 S.Diag(Call->getArg(0)->getBeginLoc(),
1290 diag::warn_opencl_generic_address_space_arg)
1291 << Call->getDirectCallee()->getNameInfo().getAsString()
1292 << Call->getArg(0)->getSourceRange();
1293 }
1294
1295 RT = RT->getPointeeType();
1296 auto Qual = RT.getQualifiers();
1297 switch (BuiltinID) {
1298 case Builtin::BIto_global:
1299 Qual.setAddressSpace(LangAS::opencl_global);
1300 break;
1301 case Builtin::BIto_local:
1302 Qual.setAddressSpace(LangAS::opencl_local);
1303 break;
1304 case Builtin::BIto_private:
1305 Qual.setAddressSpace(LangAS::opencl_private);
1306 break;
1307 default:
1308 llvm_unreachable("Invalid builtin function");
1309 }
1310 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
1311 RT.getUnqualifiedType(), Qual)));
1312
1313 return false;
1314 }
1315
SemaBuiltinLaunder(Sema & S,CallExpr * TheCall)1316 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) {
1317 if (checkArgCount(S, TheCall, 1))
1318 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 QualType ParamTy = [&]() {
1326 QualType ArgTy = TheCall->getArg(0)->getType();
1327 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1328 return S.Context.getPointerType(Ty->getElementType());
1329 if (ArgTy->isFunctionType()) {
1330 return S.Context.getPointerType(ArgTy);
1331 }
1332 return ArgTy;
1333 }();
1334
1335 TheCall->setType(ParamTy);
1336
1337 auto DiagSelect = [&]() -> llvm::Optional<unsigned> {
1338 if (!ParamTy->isPointerType())
1339 return 0;
1340 if (ParamTy->isFunctionPointerType())
1341 return 1;
1342 if (ParamTy->isVoidPointerType())
1343 return 2;
1344 return llvm::Optional<unsigned>{};
1345 }();
1346 if (DiagSelect.hasValue()) {
1347 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1348 << DiagSelect.getValue() << TheCall->getSourceRange();
1349 return ExprError();
1350 }
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 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1359 diag::err_incomplete_type))
1360 return ExprError();
1361
1362 assert(ParamTy->getPointeeType()->isObjectType() &&
1363 "Unhandled non-object pointer case");
1364
1365 InitializedEntity Entity =
1366 InitializedEntity::InitializeParameter(S.Context, ParamTy, false);
1367 ExprResult Arg =
1368 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1369 if (Arg.isInvalid())
1370 return ExprError();
1371 TheCall->setArg(0, Arg.get());
1372
1373 return TheCall;
1374 }
1375
1376 // Emit an error and return true if the current architecture is not in the list
1377 // of supported architectures.
1378 static bool
CheckBuiltinTargetSupport(Sema & S,unsigned BuiltinID,CallExpr * TheCall,ArrayRef<llvm::Triple::ArchType> SupportedArchs)1379 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
1380 ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
1381 llvm::Triple::ArchType CurArch =
1382 S.getASTContext().getTargetInfo().getTriple().getArch();
1383 if (llvm::is_contained(SupportedArchs, CurArch))
1384 return false;
1385 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
1386 << TheCall->getSourceRange();
1387 return true;
1388 }
1389
1390 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
1391 SourceLocation CallSiteLoc);
1392
CheckTSBuiltinFunctionCall(const TargetInfo & TI,unsigned BuiltinID,CallExpr * TheCall)1393 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
1394 CallExpr *TheCall) {
1395 switch (TI.getTriple().getArch()) {
1396 default:
1397 // Some builtins don't require additional checking, so just consider these
1398 // acceptable.
1399 return false;
1400 case llvm::Triple::arm:
1401 case llvm::Triple::armeb:
1402 case llvm::Triple::thumb:
1403 case llvm::Triple::thumbeb:
1404 return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
1405 case llvm::Triple::aarch64:
1406 case llvm::Triple::aarch64_32:
1407 case llvm::Triple::aarch64_be:
1408 return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
1409 case llvm::Triple::bpfeb:
1410 case llvm::Triple::bpfel:
1411 return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
1412 case llvm::Triple::hexagon:
1413 return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
1414 case llvm::Triple::mips:
1415 case llvm::Triple::mipsel:
1416 case llvm::Triple::mips64:
1417 case llvm::Triple::mips64el:
1418 return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
1419 case llvm::Triple::systemz:
1420 return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
1421 case llvm::Triple::x86:
1422 case llvm::Triple::x86_64:
1423 return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall);
1424 case llvm::Triple::ppc:
1425 case llvm::Triple::ppc64:
1426 case llvm::Triple::ppc64le:
1427 return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
1428 case llvm::Triple::amdgcn:
1429 return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall);
1430 }
1431 }
1432
1433 ExprResult
CheckBuiltinFunctionCall(FunctionDecl * FDecl,unsigned BuiltinID,CallExpr * TheCall)1434 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
1435 CallExpr *TheCall) {
1436 ExprResult TheCallResult(TheCall);
1437
1438 // Find out if any arguments are required to be integer constant expressions.
1439 unsigned ICEArguments = 0;
1440 ASTContext::GetBuiltinTypeError Error;
1441 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
1442 if (Error != ASTContext::GE_None)
1443 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
1444
1445 // If any arguments are required to be ICE's, check and diagnose.
1446 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
1447 // Skip arguments not required to be ICE's.
1448 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
1449
1450 llvm::APSInt Result;
1451 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
1452 return true;
1453 ICEArguments &= ~(1 << ArgNo);
1454 }
1455
1456 switch (BuiltinID) {
1457 case Builtin::BI__builtin___CFStringMakeConstantString:
1458 assert(TheCall->getNumArgs() == 1 &&
1459 "Wrong # arguments to builtin CFStringMakeConstantString");
1460 if (CheckObjCString(TheCall->getArg(0)))
1461 return ExprError();
1462 break;
1463 case Builtin::BI__builtin_ms_va_start:
1464 case Builtin::BI__builtin_stdarg_start:
1465 case Builtin::BI__builtin_va_start:
1466 if (SemaBuiltinVAStart(BuiltinID, TheCall))
1467 return ExprError();
1468 break;
1469 case Builtin::BI__va_start: {
1470 switch (Context.getTargetInfo().getTriple().getArch()) {
1471 case llvm::Triple::aarch64:
1472 case llvm::Triple::arm:
1473 case llvm::Triple::thumb:
1474 if (SemaBuiltinVAStartARMMicrosoft(TheCall))
1475 return ExprError();
1476 break;
1477 default:
1478 if (SemaBuiltinVAStart(BuiltinID, TheCall))
1479 return ExprError();
1480 break;
1481 }
1482 break;
1483 }
1484
1485 // The acquire, release, and no fence variants are ARM and AArch64 only.
1486 case Builtin::BI_interlockedbittestandset_acq:
1487 case Builtin::BI_interlockedbittestandset_rel:
1488 case Builtin::BI_interlockedbittestandset_nf:
1489 case Builtin::BI_interlockedbittestandreset_acq:
1490 case Builtin::BI_interlockedbittestandreset_rel:
1491 case Builtin::BI_interlockedbittestandreset_nf:
1492 if (CheckBuiltinTargetSupport(
1493 *this, BuiltinID, TheCall,
1494 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
1495 return ExprError();
1496 break;
1497
1498 // The 64-bit bittest variants are x64, ARM, and AArch64 only.
1499 case Builtin::BI_bittest64:
1500 case Builtin::BI_bittestandcomplement64:
1501 case Builtin::BI_bittestandreset64:
1502 case Builtin::BI_bittestandset64:
1503 case Builtin::BI_interlockedbittestandreset64:
1504 case Builtin::BI_interlockedbittestandset64:
1505 if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
1506 {llvm::Triple::x86_64, llvm::Triple::arm,
1507 llvm::Triple::thumb, llvm::Triple::aarch64}))
1508 return ExprError();
1509 break;
1510
1511 case Builtin::BI__builtin_isgreater:
1512 case Builtin::BI__builtin_isgreaterequal:
1513 case Builtin::BI__builtin_isless:
1514 case Builtin::BI__builtin_islessequal:
1515 case Builtin::BI__builtin_islessgreater:
1516 case Builtin::BI__builtin_isunordered:
1517 if (SemaBuiltinUnorderedCompare(TheCall))
1518 return ExprError();
1519 break;
1520 case Builtin::BI__builtin_fpclassify:
1521 if (SemaBuiltinFPClassification(TheCall, 6))
1522 return ExprError();
1523 break;
1524 case Builtin::BI__builtin_isfinite:
1525 case Builtin::BI__builtin_isinf:
1526 case Builtin::BI__builtin_isinf_sign:
1527 case Builtin::BI__builtin_isnan:
1528 case Builtin::BI__builtin_isnormal:
1529 case Builtin::BI__builtin_signbit:
1530 case Builtin::BI__builtin_signbitf:
1531 case Builtin::BI__builtin_signbitl:
1532 if (SemaBuiltinFPClassification(TheCall, 1))
1533 return ExprError();
1534 break;
1535 case Builtin::BI__builtin_shufflevector:
1536 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 case Builtin::BI__builtin_prefetch:
1540 if (SemaBuiltinPrefetch(TheCall))
1541 return ExprError();
1542 break;
1543 case Builtin::BI__builtin_alloca_with_align:
1544 if (SemaBuiltinAllocaWithAlign(TheCall))
1545 return ExprError();
1546 LLVM_FALLTHROUGH;
1547 case Builtin::BI__builtin_alloca:
1548 Diag(TheCall->getBeginLoc(), diag::warn_alloca)
1549 << TheCall->getDirectCallee();
1550 break;
1551 case Builtin::BI__assume:
1552 case Builtin::BI__builtin_assume:
1553 if (SemaBuiltinAssume(TheCall))
1554 return ExprError();
1555 break;
1556 case Builtin::BI__builtin_assume_aligned:
1557 if (SemaBuiltinAssumeAligned(TheCall))
1558 return ExprError();
1559 break;
1560 case Builtin::BI__builtin_dynamic_object_size:
1561 case Builtin::BI__builtin_object_size:
1562 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1563 return ExprError();
1564 break;
1565 case Builtin::BI__builtin_longjmp:
1566 if (SemaBuiltinLongjmp(TheCall))
1567 return ExprError();
1568 break;
1569 case Builtin::BI__builtin_setjmp:
1570 if (SemaBuiltinSetjmp(TheCall))
1571 return ExprError();
1572 break;
1573 case Builtin::BI__builtin_classify_type:
1574 if (checkArgCount(*this, TheCall, 1)) return true;
1575 TheCall->setType(Context.IntTy);
1576 break;
1577 case Builtin::BI__builtin_complex:
1578 if (SemaBuiltinComplex(TheCall))
1579 return ExprError();
1580 break;
1581 case Builtin::BI__builtin_constant_p: {
1582 if (checkArgCount(*this, TheCall, 1)) return true;
1583 ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
1584 if (Arg.isInvalid()) return true;
1585 TheCall->setArg(0, Arg.get());
1586 TheCall->setType(Context.IntTy);
1587 break;
1588 }
1589 case Builtin::BI__builtin_launder:
1590 return SemaBuiltinLaunder(*this, TheCall);
1591 case Builtin::BI__sync_fetch_and_add:
1592 case Builtin::BI__sync_fetch_and_add_1:
1593 case Builtin::BI__sync_fetch_and_add_2:
1594 case Builtin::BI__sync_fetch_and_add_4:
1595 case Builtin::BI__sync_fetch_and_add_8:
1596 case Builtin::BI__sync_fetch_and_add_16:
1597 case Builtin::BI__sync_fetch_and_sub:
1598 case Builtin::BI__sync_fetch_and_sub_1:
1599 case Builtin::BI__sync_fetch_and_sub_2:
1600 case Builtin::BI__sync_fetch_and_sub_4:
1601 case Builtin::BI__sync_fetch_and_sub_8:
1602 case Builtin::BI__sync_fetch_and_sub_16:
1603 case Builtin::BI__sync_fetch_and_or:
1604 case Builtin::BI__sync_fetch_and_or_1:
1605 case Builtin::BI__sync_fetch_and_or_2:
1606 case Builtin::BI__sync_fetch_and_or_4:
1607 case Builtin::BI__sync_fetch_and_or_8:
1608 case Builtin::BI__sync_fetch_and_or_16:
1609 case Builtin::BI__sync_fetch_and_and:
1610 case Builtin::BI__sync_fetch_and_and_1:
1611 case Builtin::BI__sync_fetch_and_and_2:
1612 case Builtin::BI__sync_fetch_and_and_4:
1613 case Builtin::BI__sync_fetch_and_and_8:
1614 case Builtin::BI__sync_fetch_and_and_16:
1615 case Builtin::BI__sync_fetch_and_xor:
1616 case Builtin::BI__sync_fetch_and_xor_1:
1617 case Builtin::BI__sync_fetch_and_xor_2:
1618 case Builtin::BI__sync_fetch_and_xor_4:
1619 case Builtin::BI__sync_fetch_and_xor_8:
1620 case Builtin::BI__sync_fetch_and_xor_16:
1621 case Builtin::BI__sync_fetch_and_nand:
1622 case Builtin::BI__sync_fetch_and_nand_1:
1623 case Builtin::BI__sync_fetch_and_nand_2:
1624 case Builtin::BI__sync_fetch_and_nand_4:
1625 case Builtin::BI__sync_fetch_and_nand_8:
1626 case Builtin::BI__sync_fetch_and_nand_16:
1627 case Builtin::BI__sync_add_and_fetch:
1628 case Builtin::BI__sync_add_and_fetch_1:
1629 case Builtin::BI__sync_add_and_fetch_2:
1630 case Builtin::BI__sync_add_and_fetch_4:
1631 case Builtin::BI__sync_add_and_fetch_8:
1632 case Builtin::BI__sync_add_and_fetch_16:
1633 case Builtin::BI__sync_sub_and_fetch:
1634 case Builtin::BI__sync_sub_and_fetch_1:
1635 case Builtin::BI__sync_sub_and_fetch_2:
1636 case Builtin::BI__sync_sub_and_fetch_4:
1637 case Builtin::BI__sync_sub_and_fetch_8:
1638 case Builtin::BI__sync_sub_and_fetch_16:
1639 case Builtin::BI__sync_and_and_fetch:
1640 case Builtin::BI__sync_and_and_fetch_1:
1641 case Builtin::BI__sync_and_and_fetch_2:
1642 case Builtin::BI__sync_and_and_fetch_4:
1643 case Builtin::BI__sync_and_and_fetch_8:
1644 case Builtin::BI__sync_and_and_fetch_16:
1645 case Builtin::BI__sync_or_and_fetch:
1646 case Builtin::BI__sync_or_and_fetch_1:
1647 case Builtin::BI__sync_or_and_fetch_2:
1648 case Builtin::BI__sync_or_and_fetch_4:
1649 case Builtin::BI__sync_or_and_fetch_8:
1650 case Builtin::BI__sync_or_and_fetch_16:
1651 case Builtin::BI__sync_xor_and_fetch:
1652 case Builtin::BI__sync_xor_and_fetch_1:
1653 case Builtin::BI__sync_xor_and_fetch_2:
1654 case Builtin::BI__sync_xor_and_fetch_4:
1655 case Builtin::BI__sync_xor_and_fetch_8:
1656 case Builtin::BI__sync_xor_and_fetch_16:
1657 case Builtin::BI__sync_nand_and_fetch:
1658 case Builtin::BI__sync_nand_and_fetch_1:
1659 case Builtin::BI__sync_nand_and_fetch_2:
1660 case Builtin::BI__sync_nand_and_fetch_4:
1661 case Builtin::BI__sync_nand_and_fetch_8:
1662 case Builtin::BI__sync_nand_and_fetch_16:
1663 case Builtin::BI__sync_val_compare_and_swap:
1664 case Builtin::BI__sync_val_compare_and_swap_1:
1665 case Builtin::BI__sync_val_compare_and_swap_2:
1666 case Builtin::BI__sync_val_compare_and_swap_4:
1667 case Builtin::BI__sync_val_compare_and_swap_8:
1668 case Builtin::BI__sync_val_compare_and_swap_16:
1669 case Builtin::BI__sync_bool_compare_and_swap:
1670 case Builtin::BI__sync_bool_compare_and_swap_1:
1671 case Builtin::BI__sync_bool_compare_and_swap_2:
1672 case Builtin::BI__sync_bool_compare_and_swap_4:
1673 case Builtin::BI__sync_bool_compare_and_swap_8:
1674 case Builtin::BI__sync_bool_compare_and_swap_16:
1675 case Builtin::BI__sync_lock_test_and_set:
1676 case Builtin::BI__sync_lock_test_and_set_1:
1677 case Builtin::BI__sync_lock_test_and_set_2:
1678 case Builtin::BI__sync_lock_test_and_set_4:
1679 case Builtin::BI__sync_lock_test_and_set_8:
1680 case Builtin::BI__sync_lock_test_and_set_16:
1681 case Builtin::BI__sync_lock_release:
1682 case Builtin::BI__sync_lock_release_1:
1683 case Builtin::BI__sync_lock_release_2:
1684 case Builtin::BI__sync_lock_release_4:
1685 case Builtin::BI__sync_lock_release_8:
1686 case Builtin::BI__sync_lock_release_16:
1687 case Builtin::BI__sync_swap:
1688 case Builtin::BI__sync_swap_1:
1689 case Builtin::BI__sync_swap_2:
1690 case Builtin::BI__sync_swap_4:
1691 case Builtin::BI__sync_swap_8:
1692 case Builtin::BI__sync_swap_16:
1693 return SemaBuiltinAtomicOverloaded(TheCallResult);
1694 case Builtin::BI__sync_synchronize:
1695 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
1696 << TheCall->getCallee()->getSourceRange();
1697 break;
1698 case Builtin::BI__builtin_nontemporal_load:
1699 case Builtin::BI__builtin_nontemporal_store:
1700 return SemaBuiltinNontemporalOverloaded(TheCallResult);
1701 case Builtin::BI__builtin_memcpy_inline: {
1702 clang::Expr *SizeOp = TheCall->getArg(2);
1703 // We warn about copying to or from `nullptr` pointers when `size` is
1704 // greater than 0. When `size` is value dependent we cannot evaluate its
1705 // value so we bail out.
1706 if (SizeOp->isValueDependent())
1707 break;
1708 if (!SizeOp->EvaluateKnownConstInt(Context).isNullValue()) {
1709 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
1710 CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
1711 }
1712 break;
1713 }
1714 #define BUILTIN(ID, TYPE, ATTRS)
1715 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1716 case Builtin::BI##ID: \
1717 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1718 #include "clang/Basic/Builtins.def"
1719 case Builtin::BI__annotation:
1720 if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1721 return ExprError();
1722 break;
1723 case Builtin::BI__builtin_annotation:
1724 if (SemaBuiltinAnnotation(*this, TheCall))
1725 return ExprError();
1726 break;
1727 case Builtin::BI__builtin_addressof:
1728 if (SemaBuiltinAddressof(*this, TheCall))
1729 return ExprError();
1730 break;
1731 case Builtin::BI__builtin_is_aligned:
1732 case Builtin::BI__builtin_align_up:
1733 case Builtin::BI__builtin_align_down:
1734 if (SemaBuiltinAlignment(*this, TheCall, BuiltinID))
1735 return ExprError();
1736 break;
1737 case Builtin::BI__builtin_add_overflow:
1738 case Builtin::BI__builtin_sub_overflow:
1739 case Builtin::BI__builtin_mul_overflow:
1740 if (SemaBuiltinOverflow(*this, TheCall, BuiltinID))
1741 return ExprError();
1742 break;
1743 case Builtin::BI__builtin_operator_new:
1744 case Builtin::BI__builtin_operator_delete: {
1745 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1746 ExprResult Res =
1747 SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1748 if (Res.isInvalid())
1749 CorrectDelayedTyposInExpr(TheCallResult.get());
1750 return Res;
1751 }
1752 case Builtin::BI__builtin_dump_struct: {
1753 // We first want to ensure we are called with 2 arguments
1754 if (checkArgCount(*this, TheCall, 2))
1755 return ExprError();
1756 // Ensure that the first argument is of type 'struct XX *'
1757 const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1758 const QualType PtrArgType = PtrArg->getType();
1759 if (!PtrArgType->isPointerType() ||
1760 !PtrArgType->getPointeeType()->isRecordType()) {
1761 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1762 << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1763 << "structure pointer";
1764 return ExprError();
1765 }
1766
1767 // Ensure that the second argument is of type 'FunctionType'
1768 const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1769 const QualType FnPtrArgType = FnPtrArg->getType();
1770 if (!FnPtrArgType->isPointerType()) {
1771 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1772 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1773 << FnPtrArgType << "'int (*)(const char *, ...)'";
1774 return ExprError();
1775 }
1776
1777 const auto *FuncType =
1778 FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1779
1780 if (!FuncType) {
1781 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1782 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1783 << FnPtrArgType << "'int (*)(const char *, ...)'";
1784 return ExprError();
1785 }
1786
1787 if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1788 if (!FT->getNumParams()) {
1789 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1790 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1791 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1792 return ExprError();
1793 }
1794 QualType PT = FT->getParamType(0);
1795 if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1796 !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1797 !PT->getPointeeType().isConstQualified()) {
1798 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1799 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1800 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1801 return ExprError();
1802 }
1803 }
1804
1805 TheCall->setType(Context.IntTy);
1806 break;
1807 }
1808 case Builtin::BI__builtin_expect_with_probability: {
1809 // We first want to ensure we are called with 3 arguments
1810 if (checkArgCount(*this, TheCall, 3))
1811 return ExprError();
1812 // then check probability is constant float in range [0.0, 1.0]
1813 const Expr *ProbArg = TheCall->getArg(2);
1814 SmallVector<PartialDiagnosticAt, 8> Notes;
1815 Expr::EvalResult Eval;
1816 Eval.Diag = &Notes;
1817 if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) ||
1818 !Eval.Val.isFloat()) {
1819 Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
1820 << ProbArg->getSourceRange();
1821 for (const PartialDiagnosticAt &PDiag : Notes)
1822 Diag(PDiag.first, PDiag.second);
1823 return ExprError();
1824 }
1825 llvm::APFloat Probability = Eval.Val.getFloat();
1826 bool LoseInfo = false;
1827 Probability.convert(llvm::APFloat::IEEEdouble(),
1828 llvm::RoundingMode::Dynamic, &LoseInfo);
1829 if (!(Probability >= llvm::APFloat(0.0) &&
1830 Probability <= llvm::APFloat(1.0))) {
1831 Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
1832 << ProbArg->getSourceRange();
1833 return ExprError();
1834 }
1835 break;
1836 }
1837 case Builtin::BI__builtin_preserve_access_index:
1838 if (SemaBuiltinPreserveAI(*this, TheCall))
1839 return ExprError();
1840 break;
1841 case Builtin::BI__builtin_call_with_static_chain:
1842 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1843 return ExprError();
1844 break;
1845 case Builtin::BI__exception_code:
1846 case Builtin::BI_exception_code:
1847 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1848 diag::err_seh___except_block))
1849 return ExprError();
1850 break;
1851 case Builtin::BI__exception_info:
1852 case Builtin::BI_exception_info:
1853 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1854 diag::err_seh___except_filter))
1855 return ExprError();
1856 break;
1857 case Builtin::BI__GetExceptionInfo:
1858 if (checkArgCount(*this, TheCall, 1))
1859 return ExprError();
1860
1861 if (CheckCXXThrowOperand(
1862 TheCall->getBeginLoc(),
1863 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1864 TheCall))
1865 return ExprError();
1866
1867 TheCall->setType(Context.VoidPtrTy);
1868 break;
1869 // OpenCL v2.0, s6.13.16 - Pipe functions
1870 case Builtin::BIread_pipe:
1871 case Builtin::BIwrite_pipe:
1872 // Since those two functions are declared with var args, we need a semantic
1873 // check for the argument.
1874 if (SemaBuiltinRWPipe(*this, TheCall))
1875 return ExprError();
1876 break;
1877 case Builtin::BIreserve_read_pipe:
1878 case Builtin::BIreserve_write_pipe:
1879 case Builtin::BIwork_group_reserve_read_pipe:
1880 case Builtin::BIwork_group_reserve_write_pipe:
1881 if (SemaBuiltinReserveRWPipe(*this, TheCall))
1882 return ExprError();
1883 break;
1884 case Builtin::BIsub_group_reserve_read_pipe:
1885 case Builtin::BIsub_group_reserve_write_pipe:
1886 if (checkOpenCLSubgroupExt(*this, TheCall) ||
1887 SemaBuiltinReserveRWPipe(*this, TheCall))
1888 return ExprError();
1889 break;
1890 case Builtin::BIcommit_read_pipe:
1891 case Builtin::BIcommit_write_pipe:
1892 case Builtin::BIwork_group_commit_read_pipe:
1893 case Builtin::BIwork_group_commit_write_pipe:
1894 if (SemaBuiltinCommitRWPipe(*this, TheCall))
1895 return ExprError();
1896 break;
1897 case Builtin::BIsub_group_commit_read_pipe:
1898 case Builtin::BIsub_group_commit_write_pipe:
1899 if (checkOpenCLSubgroupExt(*this, TheCall) ||
1900 SemaBuiltinCommitRWPipe(*this, TheCall))
1901 return ExprError();
1902 break;
1903 case Builtin::BIget_pipe_num_packets:
1904 case Builtin::BIget_pipe_max_packets:
1905 if (SemaBuiltinPipePackets(*this, TheCall))
1906 return ExprError();
1907 break;
1908 case Builtin::BIto_global:
1909 case Builtin::BIto_local:
1910 case Builtin::BIto_private:
1911 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1912 return ExprError();
1913 break;
1914 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1915 case Builtin::BIenqueue_kernel:
1916 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1917 return ExprError();
1918 break;
1919 case Builtin::BIget_kernel_work_group_size:
1920 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1921 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1922 return ExprError();
1923 break;
1924 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1925 case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1926 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1927 return ExprError();
1928 break;
1929 case Builtin::BI__builtin_os_log_format:
1930 Cleanup.setExprNeedsCleanups(true);
1931 LLVM_FALLTHROUGH;
1932 case Builtin::BI__builtin_os_log_format_buffer_size:
1933 if (SemaBuiltinOSLogFormat(TheCall))
1934 return ExprError();
1935 break;
1936 case Builtin::BI__builtin_frame_address:
1937 case Builtin::BI__builtin_return_address: {
1938 if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
1939 return ExprError();
1940
1941 // -Wframe-address warning if non-zero passed to builtin
1942 // return/frame address.
1943 Expr::EvalResult Result;
1944 if (TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
1945 Result.Val.getInt() != 0)
1946 Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
1947 << ((BuiltinID == Builtin::BI__builtin_return_address)
1948 ? "__builtin_return_address"
1949 : "__builtin_frame_address")
1950 << TheCall->getSourceRange();
1951 break;
1952 }
1953
1954 case Builtin::BI__builtin_matrix_transpose:
1955 return SemaBuiltinMatrixTranspose(TheCall, TheCallResult);
1956
1957 case Builtin::BI__builtin_matrix_column_major_load:
1958 return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
1959
1960 case Builtin::BI__builtin_matrix_column_major_store:
1961 return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
1962 }
1963
1964 // Since the target specific builtins for each arch overlap, only check those
1965 // of the arch we are compiling for.
1966 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1967 if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
1968 assert(Context.getAuxTargetInfo() &&
1969 "Aux Target Builtin, but not an aux target?");
1970
1971 if (CheckTSBuiltinFunctionCall(
1972 *Context.getAuxTargetInfo(),
1973 Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
1974 return ExprError();
1975 } else {
1976 if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
1977 TheCall))
1978 return ExprError();
1979 }
1980 }
1981
1982 return TheCallResult;
1983 }
1984
1985 // Get the valid immediate range for the specified NEON type code.
RFT(unsigned t,bool shift=false,bool ForceQuad=false)1986 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
1987 NeonTypeFlags Type(t);
1988 int IsQuad = ForceQuad ? true : Type.isQuad();
1989 switch (Type.getEltType()) {
1990 case NeonTypeFlags::Int8:
1991 case NeonTypeFlags::Poly8:
1992 return shift ? 7 : (8 << IsQuad) - 1;
1993 case NeonTypeFlags::Int16:
1994 case NeonTypeFlags::Poly16:
1995 return shift ? 15 : (4 << IsQuad) - 1;
1996 case NeonTypeFlags::Int32:
1997 return shift ? 31 : (2 << IsQuad) - 1;
1998 case NeonTypeFlags::Int64:
1999 case NeonTypeFlags::Poly64:
2000 return shift ? 63 : (1 << IsQuad) - 1;
2001 case NeonTypeFlags::Poly128:
2002 return shift ? 127 : (1 << IsQuad) - 1;
2003 case NeonTypeFlags::Float16:
2004 assert(!shift && "cannot shift float types!");
2005 return (4 << IsQuad) - 1;
2006 case NeonTypeFlags::Float32:
2007 assert(!shift && "cannot shift float types!");
2008 return (2 << IsQuad) - 1;
2009 case NeonTypeFlags::Float64:
2010 assert(!shift && "cannot shift float types!");
2011 return (1 << IsQuad) - 1;
2012 case NeonTypeFlags::BFloat16:
2013 assert(!shift && "cannot shift float types!");
2014 return (4 << IsQuad) - 1;
2015 }
2016 llvm_unreachable("Invalid NeonTypeFlag!");
2017 }
2018
2019 /// getNeonEltType - Return the QualType corresponding to the elements of
2020 /// the vector type specified by the NeonTypeFlags. This is used to check
2021 /// the pointer arguments for Neon load/store intrinsics.
getNeonEltType(NeonTypeFlags Flags,ASTContext & Context,bool IsPolyUnsigned,bool IsInt64Long)2022 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
2023 bool IsPolyUnsigned, bool IsInt64Long) {
2024 switch (Flags.getEltType()) {
2025 case NeonTypeFlags::Int8:
2026 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
2027 case NeonTypeFlags::Int16:
2028 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
2029 case NeonTypeFlags::Int32:
2030 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
2031 case NeonTypeFlags::Int64:
2032 if (IsInt64Long)
2033 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
2034 else
2035 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
2036 : Context.LongLongTy;
2037 case NeonTypeFlags::Poly8:
2038 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
2039 case NeonTypeFlags::Poly16:
2040 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
2041 case NeonTypeFlags::Poly64:
2042 if (IsInt64Long)
2043 return Context.UnsignedLongTy;
2044 else
2045 return Context.UnsignedLongLongTy;
2046 case NeonTypeFlags::Poly128:
2047 break;
2048 case NeonTypeFlags::Float16:
2049 return Context.HalfTy;
2050 case NeonTypeFlags::Float32:
2051 return Context.FloatTy;
2052 case NeonTypeFlags::Float64:
2053 return Context.DoubleTy;
2054 case NeonTypeFlags::BFloat16:
2055 return Context.BFloat16Ty;
2056 }
2057 llvm_unreachable("Invalid NeonTypeFlag!");
2058 }
2059
CheckSVEBuiltinFunctionCall(unsigned BuiltinID,CallExpr * TheCall)2060 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2061 // Range check SVE intrinsics that take immediate values.
2062 SmallVector<std::tuple<int,int,int>, 3> ImmChecks;
2063
2064 switch (BuiltinID) {
2065 default:
2066 return false;
2067 #define GET_SVE_IMMEDIATE_CHECK
2068 #include "clang/Basic/arm_sve_sema_rangechecks.inc"
2069 #undef GET_SVE_IMMEDIATE_CHECK
2070 }
2071
2072 // Perform all the immediate checks for this builtin call.
2073 bool HasError = false;
2074 for (auto &I : ImmChecks) {
2075 int ArgNum, CheckTy, ElementSizeInBits;
2076 std::tie(ArgNum, CheckTy, ElementSizeInBits) = I;
2077
2078 typedef bool(*OptionSetCheckFnTy)(int64_t Value);
2079
2080 // Function that checks whether the operand (ArgNum) is an immediate
2081 // that is one of the predefined values.
2082 auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm,
2083 int ErrDiag) -> bool {
2084 // We can't check the value of a dependent argument.
2085 Expr *Arg = TheCall->getArg(ArgNum);
2086 if (Arg->isTypeDependent() || Arg->isValueDependent())
2087 return false;
2088
2089 // Check constant-ness first.
2090 llvm::APSInt Imm;
2091 if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm))
2092 return true;
2093
2094 if (!CheckImm(Imm.getSExtValue()))
2095 return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange();
2096 return false;
2097 };
2098
2099 switch ((SVETypeFlags::ImmCheckType)CheckTy) {
2100 case SVETypeFlags::ImmCheck0_31:
2101 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31))
2102 HasError = true;
2103 break;
2104 case SVETypeFlags::ImmCheck0_13:
2105 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13))
2106 HasError = true;
2107 break;
2108 case SVETypeFlags::ImmCheck1_16:
2109 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16))
2110 HasError = true;
2111 break;
2112 case SVETypeFlags::ImmCheck0_7:
2113 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7))
2114 HasError = true;
2115 break;
2116 case SVETypeFlags::ImmCheckExtract:
2117 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2118 (2048 / ElementSizeInBits) - 1))
2119 HasError = true;
2120 break;
2121 case SVETypeFlags::ImmCheckShiftRight:
2122 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits))
2123 HasError = true;
2124 break;
2125 case SVETypeFlags::ImmCheckShiftRightNarrow:
2126 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1,
2127 ElementSizeInBits / 2))
2128 HasError = true;
2129 break;
2130 case SVETypeFlags::ImmCheckShiftLeft:
2131 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2132 ElementSizeInBits - 1))
2133 HasError = true;
2134 break;
2135 case SVETypeFlags::ImmCheckLaneIndex:
2136 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2137 (128 / (1 * ElementSizeInBits)) - 1))
2138 HasError = true;
2139 break;
2140 case SVETypeFlags::ImmCheckLaneIndexCompRotate:
2141 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2142 (128 / (2 * ElementSizeInBits)) - 1))
2143 HasError = true;
2144 break;
2145 case SVETypeFlags::ImmCheckLaneIndexDot:
2146 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2147 (128 / (4 * ElementSizeInBits)) - 1))
2148 HasError = true;
2149 break;
2150 case SVETypeFlags::ImmCheckComplexRot90_270:
2151 if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; },
2152 diag::err_rotation_argument_to_cadd))
2153 HasError = true;
2154 break;
2155 case SVETypeFlags::ImmCheckComplexRotAll90:
2156 if (CheckImmediateInSet(
2157 [](int64_t V) {
2158 return V == 0 || V == 90 || V == 180 || V == 270;
2159 },
2160 diag::err_rotation_argument_to_cmla))
2161 HasError = true;
2162 break;
2163 case SVETypeFlags::ImmCheck0_1:
2164 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1))
2165 HasError = true;
2166 break;
2167 case SVETypeFlags::ImmCheck0_2:
2168 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2))
2169 HasError = true;
2170 break;
2171 case SVETypeFlags::ImmCheck0_3:
2172 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3))
2173 HasError = true;
2174 break;
2175 }
2176 }
2177
2178 return HasError;
2179 }
2180
CheckNeonBuiltinFunctionCall(const TargetInfo & TI,unsigned BuiltinID,CallExpr * TheCall)2181 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI,
2182 unsigned BuiltinID, CallExpr *TheCall) {
2183 llvm::APSInt Result;
2184 uint64_t mask = 0;
2185 unsigned TV = 0;
2186 int PtrArgNum = -1;
2187 bool HasConstPtr = false;
2188 switch (BuiltinID) {
2189 #define GET_NEON_OVERLOAD_CHECK
2190 #include "clang/Basic/arm_neon.inc"
2191 #include "clang/Basic/arm_fp16.inc"
2192 #undef GET_NEON_OVERLOAD_CHECK
2193 }
2194
2195 // For NEON intrinsics which are overloaded on vector element type, validate
2196 // the immediate which specifies which variant to emit.
2197 unsigned ImmArg = TheCall->getNumArgs()-1;
2198 if (mask) {
2199 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
2200 return true;
2201
2202 TV = Result.getLimitedValue(64);
2203 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
2204 return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
2205 << TheCall->getArg(ImmArg)->getSourceRange();
2206 }
2207
2208 if (PtrArgNum >= 0) {
2209 // Check that pointer arguments have the specified type.
2210 Expr *Arg = TheCall->getArg(PtrArgNum);
2211 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
2212 Arg = ICE->getSubExpr();
2213 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
2214 QualType RHSTy = RHS.get()->getType();
2215
2216 llvm::Triple::ArchType Arch = TI.getTriple().getArch();
2217 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
2218 Arch == llvm::Triple::aarch64_32 ||
2219 Arch == llvm::Triple::aarch64_be;
2220 bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong;
2221 QualType EltTy =
2222 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
2223 if (HasConstPtr)
2224 EltTy = EltTy.withConst();
2225 QualType LHSTy = Context.getPointerType(EltTy);
2226 AssignConvertType ConvTy;
2227 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
2228 if (RHS.isInvalid())
2229 return true;
2230 if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
2231 RHS.get(), AA_Assigning))
2232 return true;
2233 }
2234
2235 // For NEON intrinsics which take an immediate value as part of the
2236 // instruction, range check them here.
2237 unsigned i = 0, l = 0, u = 0;
2238 switch (BuiltinID) {
2239 default:
2240 return false;
2241 #define GET_NEON_IMMEDIATE_CHECK
2242 #include "clang/Basic/arm_neon.inc"
2243 #include "clang/Basic/arm_fp16.inc"
2244 #undef GET_NEON_IMMEDIATE_CHECK
2245 }
2246
2247 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2248 }
2249
CheckMVEBuiltinFunctionCall(unsigned BuiltinID,CallExpr * TheCall)2250 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2251 switch (BuiltinID) {
2252 default:
2253 return false;
2254 #include "clang/Basic/arm_mve_builtin_sema.inc"
2255 }
2256 }
2257
CheckCDEBuiltinFunctionCall(const TargetInfo & TI,unsigned BuiltinID,CallExpr * TheCall)2258 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2259 CallExpr *TheCall) {
2260 bool Err = false;
2261 switch (BuiltinID) {
2262 default:
2263 return false;
2264 #include "clang/Basic/arm_cde_builtin_sema.inc"
2265 }
2266
2267 if (Err)
2268 return true;
2269
2270 return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true);
2271 }
2272
CheckARMCoprocessorImmediate(const TargetInfo & TI,const Expr * CoprocArg,bool WantCDE)2273 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI,
2274 const Expr *CoprocArg, bool WantCDE) {
2275 if (isConstantEvaluated())
2276 return false;
2277
2278 // We can't check the value of a dependent argument.
2279 if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent())
2280 return false;
2281
2282 llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context);
2283 int64_t CoprocNo = CoprocNoAP.getExtValue();
2284 assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative");
2285
2286 uint32_t CDECoprocMask = TI.getARMCDECoprocMask();
2287 bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo));
2288
2289 if (IsCDECoproc != WantCDE)
2290 return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc)
2291 << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange();
2292
2293 return false;
2294 }
2295
CheckARMBuiltinExclusiveCall(unsigned BuiltinID,CallExpr * TheCall,unsigned MaxWidth)2296 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
2297 unsigned MaxWidth) {
2298 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
2299 BuiltinID == ARM::BI__builtin_arm_ldaex ||
2300 BuiltinID == ARM::BI__builtin_arm_strex ||
2301 BuiltinID == ARM::BI__builtin_arm_stlex ||
2302 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2303 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2304 BuiltinID == AArch64::BI__builtin_arm_strex ||
2305 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
2306 "unexpected ARM builtin");
2307 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
2308 BuiltinID == ARM::BI__builtin_arm_ldaex ||
2309 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2310 BuiltinID == AArch64::BI__builtin_arm_ldaex;
2311
2312 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2313
2314 // Ensure that we have the proper number of arguments.
2315 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
2316 return true;
2317
2318 // Inspect the pointer argument of the atomic builtin. This should always be
2319 // a pointer type, whose element is an integral scalar or pointer type.
2320 // Because it is a pointer type, we don't have to worry about any implicit
2321 // casts here.
2322 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
2323 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
2324 if (PointerArgRes.isInvalid())
2325 return true;
2326 PointerArg = PointerArgRes.get();
2327
2328 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2329 if (!pointerType) {
2330 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
2331 << PointerArg->getType() << PointerArg->getSourceRange();
2332 return true;
2333 }
2334
2335 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
2336 // task is to insert the appropriate casts into the AST. First work out just
2337 // what the appropriate type is.
2338 QualType ValType = pointerType->getPointeeType();
2339 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
2340 if (IsLdrex)
2341 AddrType.addConst();
2342
2343 // Issue a warning if the cast is dodgy.
2344 CastKind CastNeeded = CK_NoOp;
2345 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
2346 CastNeeded = CK_BitCast;
2347 Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
2348 << PointerArg->getType() << Context.getPointerType(AddrType)
2349 << AA_Passing << PointerArg->getSourceRange();
2350 }
2351
2352 // Finally, do the cast and replace the argument with the corrected version.
2353 AddrType = Context.getPointerType(AddrType);
2354 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
2355 if (PointerArgRes.isInvalid())
2356 return true;
2357 PointerArg = PointerArgRes.get();
2358
2359 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
2360
2361 // In general, we allow ints, floats and pointers to be loaded and stored.
2362 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2363 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
2364 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
2365 << PointerArg->getType() << PointerArg->getSourceRange();
2366 return true;
2367 }
2368
2369 // But ARM doesn't have instructions to deal with 128-bit versions.
2370 if (Context.getTypeSize(ValType) > MaxWidth) {
2371 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
2372 Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
2373 << PointerArg->getType() << PointerArg->getSourceRange();
2374 return true;
2375 }
2376
2377 switch (ValType.getObjCLifetime()) {
2378 case Qualifiers::OCL_None:
2379 case Qualifiers::OCL_ExplicitNone:
2380 // okay
2381 break;
2382
2383 case Qualifiers::OCL_Weak:
2384 case Qualifiers::OCL_Strong:
2385 case Qualifiers::OCL_Autoreleasing:
2386 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
2387 << ValType << PointerArg->getSourceRange();
2388 return true;
2389 }
2390
2391 if (IsLdrex) {
2392 TheCall->setType(ValType);
2393 return false;
2394 }
2395
2396 // Initialize the argument to be stored.
2397 ExprResult ValArg = TheCall->getArg(0);
2398 InitializedEntity Entity = InitializedEntity::InitializeParameter(
2399 Context, ValType, /*consume*/ false);
2400 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2401 if (ValArg.isInvalid())
2402 return true;
2403 TheCall->setArg(0, ValArg.get());
2404
2405 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
2406 // but the custom checker bypasses all default analysis.
2407 TheCall->setType(Context.IntTy);
2408 return false;
2409 }
2410
CheckARMBuiltinFunctionCall(const TargetInfo & TI,unsigned BuiltinID,CallExpr * TheCall)2411 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2412 CallExpr *TheCall) {
2413 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
2414 BuiltinID == ARM::BI__builtin_arm_ldaex ||
2415 BuiltinID == ARM::BI__builtin_arm_strex ||
2416 BuiltinID == ARM::BI__builtin_arm_stlex) {
2417 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
2418 }
2419
2420 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
2421 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2422 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
2423 }
2424
2425 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
2426 BuiltinID == ARM::BI__builtin_arm_wsr64)
2427 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
2428
2429 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
2430 BuiltinID == ARM::BI__builtin_arm_rsrp ||
2431 BuiltinID == ARM::BI__builtin_arm_wsr ||
2432 BuiltinID == ARM::BI__builtin_arm_wsrp)
2433 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2434
2435 if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2436 return true;
2437 if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall))
2438 return true;
2439 if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall))
2440 return true;
2441
2442 // For intrinsics which take an immediate value as part of the instruction,
2443 // range check them here.
2444 // FIXME: VFP Intrinsics should error if VFP not present.
2445 switch (BuiltinID) {
2446 default: return false;
2447 case ARM::BI__builtin_arm_ssat:
2448 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
2449 case ARM::BI__builtin_arm_usat:
2450 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
2451 case ARM::BI__builtin_arm_ssat16:
2452 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
2453 case ARM::BI__builtin_arm_usat16:
2454 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
2455 case ARM::BI__builtin_arm_vcvtr_f:
2456 case ARM::BI__builtin_arm_vcvtr_d:
2457 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
2458 case ARM::BI__builtin_arm_dmb:
2459 case ARM::BI__builtin_arm_dsb:
2460 case ARM::BI__builtin_arm_isb:
2461 case ARM::BI__builtin_arm_dbg:
2462 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
2463 case ARM::BI__builtin_arm_cdp:
2464 case ARM::BI__builtin_arm_cdp2:
2465 case ARM::BI__builtin_arm_mcr:
2466 case ARM::BI__builtin_arm_mcr2:
2467 case ARM::BI__builtin_arm_mrc:
2468 case ARM::BI__builtin_arm_mrc2:
2469 case ARM::BI__builtin_arm_mcrr:
2470 case ARM::BI__builtin_arm_mcrr2:
2471 case ARM::BI__builtin_arm_mrrc:
2472 case ARM::BI__builtin_arm_mrrc2:
2473 case ARM::BI__builtin_arm_ldc:
2474 case ARM::BI__builtin_arm_ldcl:
2475 case ARM::BI__builtin_arm_ldc2:
2476 case ARM::BI__builtin_arm_ldc2l:
2477 case ARM::BI__builtin_arm_stc:
2478 case ARM::BI__builtin_arm_stcl:
2479 case ARM::BI__builtin_arm_stc2:
2480 case ARM::BI__builtin_arm_stc2l:
2481 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) ||
2482 CheckARMCoprocessorImmediate(TI, TheCall->getArg(0),
2483 /*WantCDE*/ false);
2484 }
2485 }
2486
CheckAArch64BuiltinFunctionCall(const TargetInfo & TI,unsigned BuiltinID,CallExpr * TheCall)2487 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI,
2488 unsigned BuiltinID,
2489 CallExpr *TheCall) {
2490 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2491 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2492 BuiltinID == AArch64::BI__builtin_arm_strex ||
2493 BuiltinID == AArch64::BI__builtin_arm_stlex) {
2494 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
2495 }
2496
2497 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
2498 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2499 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
2500 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
2501 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
2502 }
2503
2504 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
2505 BuiltinID == AArch64::BI__builtin_arm_wsr64)
2506 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2507
2508 // Memory Tagging Extensions (MTE) Intrinsics
2509 if (BuiltinID == AArch64::BI__builtin_arm_irg ||
2510 BuiltinID == AArch64::BI__builtin_arm_addg ||
2511 BuiltinID == AArch64::BI__builtin_arm_gmi ||
2512 BuiltinID == AArch64::BI__builtin_arm_ldg ||
2513 BuiltinID == AArch64::BI__builtin_arm_stg ||
2514 BuiltinID == AArch64::BI__builtin_arm_subp) {
2515 return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
2516 }
2517
2518 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
2519 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
2520 BuiltinID == AArch64::BI__builtin_arm_wsr ||
2521 BuiltinID == AArch64::BI__builtin_arm_wsrp)
2522 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2523
2524 // Only check the valid encoding range. Any constant in this range would be
2525 // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
2526 // an exception for incorrect registers. This matches MSVC behavior.
2527 if (BuiltinID == AArch64::BI_ReadStatusReg ||
2528 BuiltinID == AArch64::BI_WriteStatusReg)
2529 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
2530
2531 if (BuiltinID == AArch64::BI__getReg)
2532 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
2533
2534 if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2535 return true;
2536
2537 if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall))
2538 return true;
2539
2540 // For intrinsics which take an immediate value as part of the instruction,
2541 // range check them here.
2542 unsigned i = 0, l = 0, u = 0;
2543 switch (BuiltinID) {
2544 default: return false;
2545 case AArch64::BI__builtin_arm_dmb:
2546 case AArch64::BI__builtin_arm_dsb:
2547 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
2548 case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
2549 }
2550
2551 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2552 }
2553
isValidBPFPreserveFieldInfoArg(Expr * Arg)2554 static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) {
2555 if (Arg->getType()->getAsPlaceholderType())
2556 return false;
2557
2558 // The first argument needs to be a record field access.
2559 // If it is an array element access, we delay decision
2560 // to BPF backend to check whether the access is a
2561 // field access or not.
2562 return (Arg->IgnoreParens()->getObjectKind() == OK_BitField ||
2563 dyn_cast<MemberExpr>(Arg->IgnoreParens()) ||
2564 dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens()));
2565 }
2566
isEltOfVectorTy(ASTContext & Context,CallExpr * Call,Sema & S,QualType VectorTy,QualType EltTy)2567 static bool isEltOfVectorTy(ASTContext &Context, CallExpr *Call, Sema &S,
2568 QualType VectorTy, QualType EltTy) {
2569 QualType VectorEltTy = VectorTy->castAs<VectorType>()->getElementType();
2570 if (!Context.hasSameType(VectorEltTy, EltTy)) {
2571 S.Diag(Call->getBeginLoc(), diag::err_typecheck_call_different_arg_types)
2572 << Call->getSourceRange() << VectorEltTy << EltTy;
2573 return false;
2574 }
2575 return true;
2576 }
2577
isValidBPFPreserveTypeInfoArg(Expr * Arg)2578 static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) {
2579 QualType ArgType = Arg->getType();
2580 if (ArgType->getAsPlaceholderType())
2581 return false;
2582
2583 // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type
2584 // format:
2585 // 1. __builtin_preserve_type_info(*(<type> *)0, flag);
2586 // 2. <type> var;
2587 // __builtin_preserve_type_info(var, flag);
2588 if (!dyn_cast<DeclRefExpr>(Arg->IgnoreParens()) &&
2589 !dyn_cast<UnaryOperator>(Arg->IgnoreParens()))
2590 return false;
2591
2592 // Typedef type.
2593 if (ArgType->getAs<TypedefType>())
2594 return true;
2595
2596 // Record type or Enum type.
2597 const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2598 if (const auto *RT = Ty->getAs<RecordType>()) {
2599 if (!RT->getDecl()->getDeclName().isEmpty())
2600 return true;
2601 } else if (const auto *ET = Ty->getAs<EnumType>()) {
2602 if (!ET->getDecl()->getDeclName().isEmpty())
2603 return true;
2604 }
2605
2606 return false;
2607 }
2608
isValidBPFPreserveEnumValueArg(Expr * Arg)2609 static bool isValidBPFPreserveEnumValueArg(Expr *Arg) {
2610 QualType ArgType = Arg->getType();
2611 if (ArgType->getAsPlaceholderType())
2612 return false;
2613
2614 // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type
2615 // format:
2616 // __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>,
2617 // flag);
2618 const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens());
2619 if (!UO)
2620 return false;
2621
2622 const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr());
2623 if (!CE || CE->getCastKind() != CK_IntegralToPointer)
2624 return false;
2625
2626 // The integer must be from an EnumConstantDecl.
2627 const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr());
2628 if (!DR)
2629 return false;
2630
2631 const EnumConstantDecl *Enumerator =
2632 dyn_cast<EnumConstantDecl>(DR->getDecl());
2633 if (!Enumerator)
2634 return false;
2635
2636 // The type must be EnumType.
2637 const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2638 const auto *ET = Ty->getAs<EnumType>();
2639 if (!ET)
2640 return false;
2641
2642 // The enum value must be supported.
2643 for (auto *EDI : ET->getDecl()->enumerators()) {
2644 if (EDI == Enumerator)
2645 return true;
2646 }
2647
2648 return false;
2649 }
2650
CheckBPFBuiltinFunctionCall(unsigned BuiltinID,CallExpr * TheCall)2651 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
2652 CallExpr *TheCall) {
2653 assert((BuiltinID == BPF::BI__builtin_preserve_field_info ||
2654 BuiltinID == BPF::BI__builtin_btf_type_id ||
2655 BuiltinID == BPF::BI__builtin_preserve_type_info ||
2656 BuiltinID == BPF::BI__builtin_preserve_enum_value) &&
2657 "unexpected BPF builtin");
2658
2659 if (checkArgCount(*this, TheCall, 2))
2660 return true;
2661
2662 // The second argument needs to be a constant int
2663 Expr *Arg = TheCall->getArg(1);
2664 Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context);
2665 diag::kind kind;
2666 if (!Value) {
2667 if (BuiltinID == BPF::BI__builtin_preserve_field_info)
2668 kind = diag::err_preserve_field_info_not_const;
2669 else if (BuiltinID == BPF::BI__builtin_btf_type_id)
2670 kind = diag::err_btf_type_id_not_const;
2671 else if (BuiltinID == BPF::BI__builtin_preserve_type_info)
2672 kind = diag::err_preserve_type_info_not_const;
2673 else
2674 kind = diag::err_preserve_enum_value_not_const;
2675 Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange();
2676 return true;
2677 }
2678
2679 // The first argument
2680 Arg = TheCall->getArg(0);
2681 bool InvalidArg = false;
2682 bool ReturnUnsignedInt = true;
2683 if (BuiltinID == BPF::BI__builtin_preserve_field_info) {
2684 if (!isValidBPFPreserveFieldInfoArg(Arg)) {
2685 InvalidArg = true;
2686 kind = diag::err_preserve_field_info_not_field;
2687 }
2688 } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) {
2689 if (!isValidBPFPreserveTypeInfoArg(Arg)) {
2690 InvalidArg = true;
2691 kind = diag::err_preserve_type_info_invalid;
2692 }
2693 } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) {
2694 if (!isValidBPFPreserveEnumValueArg(Arg)) {
2695 InvalidArg = true;
2696 kind = diag::err_preserve_enum_value_invalid;
2697 }
2698 ReturnUnsignedInt = false;
2699 } else if (BuiltinID == BPF::BI__builtin_btf_type_id) {
2700 ReturnUnsignedInt = false;
2701 }
2702
2703 if (InvalidArg) {
2704 Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange();
2705 return true;
2706 }
2707
2708 if (ReturnUnsignedInt)
2709 TheCall->setType(Context.UnsignedIntTy);
2710 else
2711 TheCall->setType(Context.UnsignedLongTy);
2712 return false;
2713 }
2714
CheckHexagonBuiltinArgument(unsigned BuiltinID,CallExpr * TheCall)2715 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2716 struct ArgInfo {
2717 uint8_t OpNum;
2718 bool IsSigned;
2719 uint8_t BitWidth;
2720 uint8_t Align;
2721 };
2722 struct BuiltinInfo {
2723 unsigned BuiltinID;
2724 ArgInfo Infos[2];
2725 };
2726
2727 static BuiltinInfo Infos[] = {
2728 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} },
2729 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} },
2730 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} },
2731 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 1 }} },
2732 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} },
2733 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} },
2734 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} },
2735 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} },
2736 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} },
2737 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} },
2738 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} },
2739
2740 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} },
2741 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} },
2742 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} },
2743 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} },
2744 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} },
2745 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} },
2746 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} },
2747 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} },
2748 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} },
2749 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} },
2750 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} },
2751
2752 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} },
2753 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} },
2754 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} },
2755 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} },
2756 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} },
2757 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} },
2758 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} },
2759 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} },
2760 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} },
2761 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} },
2762 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} },
2763 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} },
2764 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} },
2765 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} },
2766 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} },
2767 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} },
2768 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} },
2769 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} },
2770 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} },
2771 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} },
2772 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} },
2773 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} },
2774 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} },
2775 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} },
2776 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} },
2777 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} },
2778 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} },
2779 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} },
2780 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} },
2781 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} },
2782 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} },
2783 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} },
2784 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} },
2785 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} },
2786 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} },
2787 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} },
2788 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} },
2789 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} },
2790 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} },
2791 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} },
2792 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} },
2793 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} },
2794 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} },
2795 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} },
2796 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} },
2797 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} },
2798 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} },
2799 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} },
2800 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} },
2801 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} },
2802 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} },
2803 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
2804 {{ 1, false, 6, 0 }} },
2805 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} },
2806 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} },
2807 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} },
2808 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} },
2809 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} },
2810 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} },
2811 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
2812 {{ 1, false, 5, 0 }} },
2813 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} },
2814 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} },
2815 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} },
2816 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} },
2817 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} },
2818 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 },
2819 { 2, false, 5, 0 }} },
2820 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 },
2821 { 2, false, 6, 0 }} },
2822 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 },
2823 { 3, false, 5, 0 }} },
2824 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 },
2825 { 3, false, 6, 0 }} },
2826 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} },
2827 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} },
2828 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} },
2829 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} },
2830 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} },
2831 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} },
2832 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} },
2833 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} },
2834 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} },
2835 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} },
2836 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} },
2837 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} },
2838 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} },
2839 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} },
2840 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} },
2841 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
2842 {{ 2, false, 4, 0 },
2843 { 3, false, 5, 0 }} },
2844 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
2845 {{ 2, false, 4, 0 },
2846 { 3, false, 5, 0 }} },
2847 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
2848 {{ 2, false, 4, 0 },
2849 { 3, false, 5, 0 }} },
2850 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
2851 {{ 2, false, 4, 0 },
2852 { 3, false, 5, 0 }} },
2853 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} },
2854 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} },
2855 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} },
2856 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} },
2857 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} },
2858 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} },
2859 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} },
2860 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} },
2861 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} },
2862 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} },
2863 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 },
2864 { 2, false, 5, 0 }} },
2865 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 },
2866 { 2, false, 6, 0 }} },
2867 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} },
2868 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} },
2869 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} },
2870 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} },
2871 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} },
2872 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} },
2873 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} },
2874 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} },
2875 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
2876 {{ 1, false, 4, 0 }} },
2877 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} },
2878 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
2879 {{ 1, false, 4, 0 }} },
2880 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} },
2881 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} },
2882 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} },
2883 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} },
2884 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} },
2885 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} },
2886 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} },
2887 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} },
2888 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} },
2889 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} },
2890 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} },
2891 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} },
2892 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} },
2893 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} },
2894 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} },
2895 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} },
2896 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} },
2897 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} },
2898 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} },
2899 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
2900 {{ 3, false, 1, 0 }} },
2901 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} },
2902 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} },
2903 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} },
2904 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
2905 {{ 3, false, 1, 0 }} },
2906 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} },
2907 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} },
2908 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} },
2909 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
2910 {{ 3, false, 1, 0 }} },
2911 };
2912
2913 // Use a dynamically initialized static to sort the table exactly once on
2914 // first run.
2915 static const bool SortOnce =
2916 (llvm::sort(Infos,
2917 [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
2918 return LHS.BuiltinID < RHS.BuiltinID;
2919 }),
2920 true);
2921 (void)SortOnce;
2922
2923 const BuiltinInfo *F = llvm::partition_point(
2924 Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
2925 if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
2926 return false;
2927
2928 bool Error = false;
2929
2930 for (const ArgInfo &A : F->Infos) {
2931 // Ignore empty ArgInfo elements.
2932 if (A.BitWidth == 0)
2933 continue;
2934
2935 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
2936 int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
2937 if (!A.Align) {
2938 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
2939 } else {
2940 unsigned M = 1 << A.Align;
2941 Min *= M;
2942 Max *= M;
2943 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
2944 SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
2945 }
2946 }
2947 return Error;
2948 }
2949
CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,CallExpr * TheCall)2950 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
2951 CallExpr *TheCall) {
2952 return CheckHexagonBuiltinArgument(BuiltinID, TheCall);
2953 }
2954
CheckMipsBuiltinFunctionCall(const TargetInfo & TI,unsigned BuiltinID,CallExpr * TheCall)2955 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI,
2956 unsigned BuiltinID, CallExpr *TheCall) {
2957 return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) ||
2958 CheckMipsBuiltinArgument(BuiltinID, TheCall);
2959 }
2960
CheckMipsBuiltinCpu(const TargetInfo & TI,unsigned BuiltinID,CallExpr * TheCall)2961 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID,
2962 CallExpr *TheCall) {
2963
2964 if (Mips::BI__builtin_mips_addu_qb <= BuiltinID &&
2965 BuiltinID <= Mips::BI__builtin_mips_lwx) {
2966 if (!TI.hasFeature("dsp"))
2967 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp);
2968 }
2969
2970 if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID &&
2971 BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) {
2972 if (!TI.hasFeature("dspr2"))
2973 return Diag(TheCall->getBeginLoc(),
2974 diag::err_mips_builtin_requires_dspr2);
2975 }
2976
2977 if (Mips::BI__builtin_msa_add_a_b <= BuiltinID &&
2978 BuiltinID <= Mips::BI__builtin_msa_xori_b) {
2979 if (!TI.hasFeature("msa"))
2980 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa);
2981 }
2982
2983 return false;
2984 }
2985
2986 // CheckMipsBuiltinArgument - Checks the constant value passed to the
2987 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
2988 // ordering for DSP is unspecified. MSA is ordered by the data format used
2989 // by the underlying instruction i.e., df/m, df/n and then by size.
2990 //
2991 // FIXME: The size tests here should instead be tablegen'd along with the
2992 // definitions from include/clang/Basic/BuiltinsMips.def.
2993 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
2994 // be too.
CheckMipsBuiltinArgument(unsigned BuiltinID,CallExpr * TheCall)2995 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2996 unsigned i = 0, l = 0, u = 0, m = 0;
2997 switch (BuiltinID) {
2998 default: return false;
2999 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
3000 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
3001 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
3002 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
3003 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
3004 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
3005 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
3006 // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
3007 // df/m field.
3008 // These intrinsics take an unsigned 3 bit immediate.
3009 case Mips::BI__builtin_msa_bclri_b:
3010 case Mips::BI__builtin_msa_bnegi_b:
3011 case Mips::BI__builtin_msa_bseti_b:
3012 case Mips::BI__builtin_msa_sat_s_b:
3013 case Mips::BI__builtin_msa_sat_u_b:
3014 case Mips::BI__builtin_msa_slli_b:
3015 case Mips::BI__builtin_msa_srai_b:
3016 case Mips::BI__builtin_msa_srari_b:
3017 case Mips::BI__builtin_msa_srli_b:
3018 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
3019 case Mips::BI__builtin_msa_binsli_b:
3020 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
3021 // These intrinsics take an unsigned 4 bit immediate.
3022 case Mips::BI__builtin_msa_bclri_h:
3023 case Mips::BI__builtin_msa_bnegi_h:
3024 case Mips::BI__builtin_msa_bseti_h:
3025 case Mips::BI__builtin_msa_sat_s_h:
3026 case Mips::BI__builtin_msa_sat_u_h:
3027 case Mips::BI__builtin_msa_slli_h:
3028 case Mips::BI__builtin_msa_srai_h:
3029 case Mips::BI__builtin_msa_srari_h:
3030 case Mips::BI__builtin_msa_srli_h:
3031 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
3032 case Mips::BI__builtin_msa_binsli_h:
3033 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
3034 // These intrinsics take an unsigned 5 bit immediate.
3035 // The first block of intrinsics actually have an unsigned 5 bit field,
3036 // not a df/n field.
3037 case Mips::BI__builtin_msa_cfcmsa:
3038 case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
3039 case Mips::BI__builtin_msa_clei_u_b:
3040 case Mips::BI__builtin_msa_clei_u_h:
3041 case Mips::BI__builtin_msa_clei_u_w:
3042 case Mips::BI__builtin_msa_clei_u_d:
3043 case Mips::BI__builtin_msa_clti_u_b:
3044 case Mips::BI__builtin_msa_clti_u_h:
3045 case Mips::BI__builtin_msa_clti_u_w:
3046 case Mips::BI__builtin_msa_clti_u_d:
3047 case Mips::BI__builtin_msa_maxi_u_b:
3048 case Mips::BI__builtin_msa_maxi_u_h:
3049 case Mips::BI__builtin_msa_maxi_u_w:
3050 case Mips::BI__builtin_msa_maxi_u_d:
3051 case Mips::BI__builtin_msa_mini_u_b:
3052 case Mips::BI__builtin_msa_mini_u_h:
3053 case Mips::BI__builtin_msa_mini_u_w:
3054 case Mips::BI__builtin_msa_mini_u_d:
3055 case Mips::BI__builtin_msa_addvi_b:
3056 case Mips::BI__builtin_msa_addvi_h:
3057 case Mips::BI__builtin_msa_addvi_w:
3058 case Mips::BI__builtin_msa_addvi_d:
3059 case Mips::BI__builtin_msa_bclri_w:
3060 case Mips::BI__builtin_msa_bnegi_w:
3061 case Mips::BI__builtin_msa_bseti_w:
3062 case Mips::BI__builtin_msa_sat_s_w:
3063 case Mips::BI__builtin_msa_sat_u_w:
3064 case Mips::BI__builtin_msa_slli_w:
3065 case Mips::BI__builtin_msa_srai_w:
3066 case Mips::BI__builtin_msa_srari_w:
3067 case Mips::BI__builtin_msa_srli_w:
3068 case Mips::BI__builtin_msa_srlri_w:
3069 case Mips::BI__builtin_msa_subvi_b:
3070 case Mips::BI__builtin_msa_subvi_h:
3071 case Mips::BI__builtin_msa_subvi_w:
3072 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
3073 case Mips::BI__builtin_msa_binsli_w:
3074 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
3075 // These intrinsics take an unsigned 6 bit immediate.
3076 case Mips::BI__builtin_msa_bclri_d:
3077 case Mips::BI__builtin_msa_bnegi_d:
3078 case Mips::BI__builtin_msa_bseti_d:
3079 case Mips::BI__builtin_msa_sat_s_d:
3080 case Mips::BI__builtin_msa_sat_u_d:
3081 case Mips::BI__builtin_msa_slli_d:
3082 case Mips::BI__builtin_msa_srai_d:
3083 case Mips::BI__builtin_msa_srari_d:
3084 case Mips::BI__builtin_msa_srli_d:
3085 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
3086 case Mips::BI__builtin_msa_binsli_d:
3087 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
3088 // These intrinsics take a signed 5 bit immediate.
3089 case Mips::BI__builtin_msa_ceqi_b:
3090 case Mips::BI__builtin_msa_ceqi_h:
3091 case Mips::BI__builtin_msa_ceqi_w:
3092 case Mips::BI__builtin_msa_ceqi_d:
3093 case Mips::BI__builtin_msa_clti_s_b:
3094 case Mips::BI__builtin_msa_clti_s_h:
3095 case Mips::BI__builtin_msa_clti_s_w:
3096 case Mips::BI__builtin_msa_clti_s_d:
3097 case Mips::BI__builtin_msa_clei_s_b:
3098 case Mips::BI__builtin_msa_clei_s_h:
3099 case Mips::BI__builtin_msa_clei_s_w:
3100 case Mips::BI__builtin_msa_clei_s_d:
3101 case Mips::BI__builtin_msa_maxi_s_b:
3102 case Mips::BI__builtin_msa_maxi_s_h:
3103 case Mips::BI__builtin_msa_maxi_s_w:
3104 case Mips::BI__builtin_msa_maxi_s_d:
3105 case Mips::BI__builtin_msa_mini_s_b:
3106 case Mips::BI__builtin_msa_mini_s_h:
3107 case Mips::BI__builtin_msa_mini_s_w:
3108 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
3109 // These intrinsics take an unsigned 8 bit immediate.
3110 case Mips::BI__builtin_msa_andi_b:
3111 case Mips::BI__builtin_msa_nori_b:
3112 case Mips::BI__builtin_msa_ori_b:
3113 case Mips::BI__builtin_msa_shf_b:
3114 case Mips::BI__builtin_msa_shf_h:
3115 case Mips::BI__builtin_msa_shf_w:
3116 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
3117 case Mips::BI__builtin_msa_bseli_b:
3118 case Mips::BI__builtin_msa_bmnzi_b:
3119 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
3120 // df/n format
3121 // These intrinsics take an unsigned 4 bit immediate.
3122 case Mips::BI__builtin_msa_copy_s_b:
3123 case Mips::BI__builtin_msa_copy_u_b:
3124 case Mips::BI__builtin_msa_insve_b:
3125 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
3126 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
3127 // These intrinsics take an unsigned 3 bit immediate.
3128 case Mips::BI__builtin_msa_copy_s_h:
3129 case Mips::BI__builtin_msa_copy_u_h:
3130 case Mips::BI__builtin_msa_insve_h:
3131 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
3132 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
3133 // These intrinsics take an unsigned 2 bit immediate.
3134 case Mips::BI__builtin_msa_copy_s_w:
3135 case Mips::BI__builtin_msa_copy_u_w:
3136 case Mips::BI__builtin_msa_insve_w:
3137 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
3138 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
3139 // These intrinsics take an unsigned 1 bit immediate.
3140 case Mips::BI__builtin_msa_copy_s_d:
3141 case Mips::BI__builtin_msa_copy_u_d:
3142 case Mips::BI__builtin_msa_insve_d:
3143 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
3144 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
3145 // Memory offsets and immediate loads.
3146 // These intrinsics take a signed 10 bit immediate.
3147 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
3148 case Mips::BI__builtin_msa_ldi_h:
3149 case Mips::BI__builtin_msa_ldi_w:
3150 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
3151 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
3152 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
3153 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
3154 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
3155 case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break;
3156 case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break;
3157 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
3158 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
3159 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
3160 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
3161 case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break;
3162 case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break;
3163 }
3164
3165 if (!m)
3166 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3167
3168 return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
3169 SemaBuiltinConstantArgMultiple(TheCall, i, m);
3170 }
3171
3172 /// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str,
3173 /// advancing the pointer over the consumed characters. The decoded type is
3174 /// returned. If the decoded type represents a constant integer with a
3175 /// constraint on its value then Mask is set to that value. The type descriptors
3176 /// used in Str are specific to PPC MMA builtins and are documented in the file
3177 /// defining the PPC builtins.
DecodePPCMMATypeFromStr(ASTContext & Context,const char * & Str,unsigned & Mask)3178 static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str,
3179 unsigned &Mask) {
3180 bool RequireICE = false;
3181 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
3182 switch (*Str++) {
3183 case 'V':
3184 return Context.getVectorType(Context.UnsignedCharTy, 16,
3185 VectorType::VectorKind::AltiVecVector);
3186 case 'i': {
3187 char *End;
3188 unsigned size = strtoul(Str, &End, 10);
3189 assert(End != Str && "Missing constant parameter constraint");
3190 Str = End;
3191 Mask = size;
3192 return Context.IntTy;
3193 }
3194 case 'W': {
3195 char *End;
3196 unsigned size = strtoul(Str, &End, 10);
3197 assert(End != Str && "Missing PowerPC MMA type size");
3198 Str = End;
3199 QualType Type;
3200 switch (size) {
3201 #define PPC_MMA_VECTOR_TYPE(typeName, Id, size) \
3202 case size: Type = Context.Id##Ty; break;
3203 #include "clang/Basic/PPCTypes.def"
3204 default: llvm_unreachable("Invalid PowerPC MMA vector type");
3205 }
3206 bool CheckVectorArgs = false;
3207 while (!CheckVectorArgs) {
3208 switch (*Str++) {
3209 case '*':
3210 Type = Context.getPointerType(Type);
3211 break;
3212 case 'C':
3213 Type = Type.withConst();
3214 break;
3215 default:
3216 CheckVectorArgs = true;
3217 --Str;
3218 break;
3219 }
3220 }
3221 return Type;
3222 }
3223 default:
3224 return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true);
3225 }
3226 }
3227
CheckPPCBuiltinFunctionCall(const TargetInfo & TI,unsigned BuiltinID,CallExpr * TheCall)3228 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3229 CallExpr *TheCall) {
3230 unsigned i = 0, l = 0, u = 0;
3231 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
3232 BuiltinID == PPC::BI__builtin_divdeu ||
3233 BuiltinID == PPC::BI__builtin_bpermd;
3234 bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64;
3235 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
3236 BuiltinID == PPC::BI__builtin_divweu ||
3237 BuiltinID == PPC::BI__builtin_divde ||
3238 BuiltinID == PPC::BI__builtin_divdeu;
3239
3240 if (Is64BitBltin && !IsTarget64Bit)
3241 return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3242 << TheCall->getSourceRange();
3243
3244 if ((IsBltinExtDiv && !TI.hasFeature("extdiv")) ||
3245 (BuiltinID == PPC::BI__builtin_bpermd && !TI.hasFeature("bpermd")))
3246 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3247 << TheCall->getSourceRange();
3248
3249 auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool {
3250 if (!TI.hasFeature("vsx"))
3251 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3252 << TheCall->getSourceRange();
3253 return false;
3254 };
3255
3256 switch (BuiltinID) {
3257 default: return false;
3258 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3259 case PPC::BI__builtin_altivec_crypto_vshasigmad:
3260 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3261 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3262 case PPC::BI__builtin_altivec_dss:
3263 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
3264 case PPC::BI__builtin_tbegin:
3265 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
3266 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
3267 case PPC::BI__builtin_tabortwc:
3268 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
3269 case PPC::BI__builtin_tabortwci:
3270 case PPC::BI__builtin_tabortdci:
3271 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3272 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
3273 case PPC::BI__builtin_altivec_dst:
3274 case PPC::BI__builtin_altivec_dstt:
3275 case PPC::BI__builtin_altivec_dstst:
3276 case PPC::BI__builtin_altivec_dststt:
3277 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
3278 case PPC::BI__builtin_vsx_xxpermdi:
3279 case PPC::BI__builtin_vsx_xxsldwi:
3280 return SemaBuiltinVSX(TheCall);
3281 case PPC::BI__builtin_unpack_vector_int128:
3282 return SemaVSXCheck(TheCall) ||
3283 SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3284 case PPC::BI__builtin_pack_vector_int128:
3285 return SemaVSXCheck(TheCall);
3286 case PPC::BI__builtin_altivec_vgnb:
3287 return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7);
3288 case PPC::BI__builtin_altivec_vec_replace_elt:
3289 case PPC::BI__builtin_altivec_vec_replace_unaligned: {
3290 QualType VecTy = TheCall->getArg(0)->getType();
3291 QualType EltTy = TheCall->getArg(1)->getType();
3292 unsigned Width = Context.getIntWidth(EltTy);
3293 return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) ||
3294 !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy);
3295 }
3296 case PPC::BI__builtin_vsx_xxeval:
3297 return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255);
3298 case PPC::BI__builtin_altivec_vsldbi:
3299 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3300 case PPC::BI__builtin_altivec_vsrdbi:
3301 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3302 case PPC::BI__builtin_vsx_xxpermx:
3303 return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7);
3304 #define MMA_BUILTIN(Name, Types, Acc) \
3305 case PPC::BI__builtin_mma_##Name: \
3306 return SemaBuiltinPPCMMACall(TheCall, Types);
3307 #include "clang/Basic/BuiltinsPPC.def"
3308 }
3309 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3310 }
3311
3312 // Check if the given type is a non-pointer PPC MMA type. This function is used
3313 // in Sema to prevent invalid uses of restricted PPC MMA types.
CheckPPCMMAType(QualType Type,SourceLocation TypeLoc)3314 bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) {
3315 if (Type->isPointerType() || Type->isArrayType())
3316 return false;
3317
3318 QualType CoreType = Type.getCanonicalType().getUnqualifiedType();
3319 #define PPC_MMA_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty
3320 if (false
3321 #include "clang/Basic/PPCTypes.def"
3322 ) {
3323 Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type);
3324 return true;
3325 }
3326 return false;
3327 }
3328
CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID,CallExpr * TheCall)3329 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID,
3330 CallExpr *TheCall) {
3331 // position of memory order and scope arguments in the builtin
3332 unsigned OrderIndex, ScopeIndex;
3333 switch (BuiltinID) {
3334 case AMDGPU::BI__builtin_amdgcn_atomic_inc32:
3335 case AMDGPU::BI__builtin_amdgcn_atomic_inc64:
3336 case AMDGPU::BI__builtin_amdgcn_atomic_dec32:
3337 case AMDGPU::BI__builtin_amdgcn_atomic_dec64:
3338 OrderIndex = 2;
3339 ScopeIndex = 3;
3340 break;
3341 case AMDGPU::BI__builtin_amdgcn_fence:
3342 OrderIndex = 0;
3343 ScopeIndex = 1;
3344 break;
3345 default:
3346 return false;
3347 }
3348
3349 ExprResult Arg = TheCall->getArg(OrderIndex);
3350 auto ArgExpr = Arg.get();
3351 Expr::EvalResult ArgResult;
3352
3353 if (!ArgExpr->EvaluateAsInt(ArgResult, Context))
3354 return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int)
3355 << ArgExpr->getType();
3356 int ord = ArgResult.Val.getInt().getZExtValue();
3357
3358 // Check valididty of memory ordering as per C11 / C++11's memody model.
3359 switch (static_cast<llvm::AtomicOrderingCABI>(ord)) {
3360 case llvm::AtomicOrderingCABI::acquire:
3361 case llvm::AtomicOrderingCABI::release:
3362 case llvm::AtomicOrderingCABI::acq_rel:
3363 case llvm::AtomicOrderingCABI::seq_cst:
3364 break;
3365 default: {
3366 return Diag(ArgExpr->getBeginLoc(),
3367 diag::warn_atomic_op_has_invalid_memory_order)
3368 << ArgExpr->getSourceRange();
3369 }
3370 }
3371
3372 Arg = TheCall->getArg(ScopeIndex);
3373 ArgExpr = Arg.get();
3374 Expr::EvalResult ArgResult1;
3375 // Check that sync scope is a constant literal
3376 if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context))
3377 return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal)
3378 << ArgExpr->getType();
3379
3380 return false;
3381 }
3382
CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,CallExpr * TheCall)3383 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
3384 CallExpr *TheCall) {
3385 if (BuiltinID == SystemZ::BI__builtin_tabort) {
3386 Expr *Arg = TheCall->getArg(0);
3387 if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context))
3388 if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256)
3389 return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
3390 << Arg->getSourceRange();
3391 }
3392
3393 // For intrinsics which take an immediate value as part of the instruction,
3394 // range check them here.
3395 unsigned i = 0, l = 0, u = 0;
3396 switch (BuiltinID) {
3397 default: return false;
3398 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
3399 case SystemZ::BI__builtin_s390_verimb:
3400 case SystemZ::BI__builtin_s390_verimh:
3401 case SystemZ::BI__builtin_s390_verimf:
3402 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
3403 case SystemZ::BI__builtin_s390_vfaeb:
3404 case SystemZ::BI__builtin_s390_vfaeh:
3405 case SystemZ::BI__builtin_s390_vfaef:
3406 case SystemZ::BI__builtin_s390_vfaebs:
3407 case SystemZ::BI__builtin_s390_vfaehs:
3408 case SystemZ::BI__builtin_s390_vfaefs:
3409 case SystemZ::BI__builtin_s390_vfaezb:
3410 case SystemZ::BI__builtin_s390_vfaezh:
3411 case SystemZ::BI__builtin_s390_vfaezf:
3412 case SystemZ::BI__builtin_s390_vfaezbs:
3413 case SystemZ::BI__builtin_s390_vfaezhs:
3414 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
3415 case SystemZ::BI__builtin_s390_vfisb:
3416 case SystemZ::BI__builtin_s390_vfidb:
3417 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
3418 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3419 case SystemZ::BI__builtin_s390_vftcisb:
3420 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
3421 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
3422 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
3423 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
3424 case SystemZ::BI__builtin_s390_vstrcb:
3425 case SystemZ::BI__builtin_s390_vstrch:
3426 case SystemZ::BI__builtin_s390_vstrcf:
3427 case SystemZ::BI__builtin_s390_vstrczb:
3428 case SystemZ::BI__builtin_s390_vstrczh:
3429 case SystemZ::BI__builtin_s390_vstrczf:
3430 case SystemZ::BI__builtin_s390_vstrcbs:
3431 case SystemZ::BI__builtin_s390_vstrchs:
3432 case SystemZ::BI__builtin_s390_vstrcfs:
3433 case SystemZ::BI__builtin_s390_vstrczbs:
3434 case SystemZ::BI__builtin_s390_vstrczhs:
3435 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
3436 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
3437 case SystemZ::BI__builtin_s390_vfminsb:
3438 case SystemZ::BI__builtin_s390_vfmaxsb:
3439 case SystemZ::BI__builtin_s390_vfmindb:
3440 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
3441 case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
3442 case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
3443 }
3444 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3445 }
3446
3447 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
3448 /// This checks that the target supports __builtin_cpu_supports and
3449 /// that the string argument is constant and valid.
SemaBuiltinCpuSupports(Sema & S,const TargetInfo & TI,CallExpr * TheCall)3450 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI,
3451 CallExpr *TheCall) {
3452 Expr *Arg = TheCall->getArg(0);
3453
3454 // Check if the argument is a string literal.
3455 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3456 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3457 << Arg->getSourceRange();
3458
3459 // Check the contents of the string.
3460 StringRef Feature =
3461 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3462 if (!TI.validateCpuSupports(Feature))
3463 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
3464 << Arg->getSourceRange();
3465 return false;
3466 }
3467
3468 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
3469 /// This checks that the target supports __builtin_cpu_is and
3470 /// that the string argument is constant and valid.
SemaBuiltinCpuIs(Sema & S,const TargetInfo & TI,CallExpr * TheCall)3471 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) {
3472 Expr *Arg = TheCall->getArg(0);
3473
3474 // Check if the argument is a string literal.
3475 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3476 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3477 << Arg->getSourceRange();
3478
3479 // Check the contents of the string.
3480 StringRef Feature =
3481 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3482 if (!TI.validateCpuIs(Feature))
3483 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
3484 << Arg->getSourceRange();
3485 return false;
3486 }
3487
3488 // Check if the rounding mode is legal.
CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID,CallExpr * TheCall)3489 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
3490 // Indicates if this instruction has rounding control or just SAE.
3491 bool HasRC = false;
3492
3493 unsigned ArgNum = 0;
3494 switch (BuiltinID) {
3495 default:
3496 return false;
3497 case X86::BI__builtin_ia32_vcvttsd2si32:
3498 case X86::BI__builtin_ia32_vcvttsd2si64:
3499 case X86::BI__builtin_ia32_vcvttsd2usi32:
3500 case X86::BI__builtin_ia32_vcvttsd2usi64:
3501 case X86::BI__builtin_ia32_vcvttss2si32:
3502 case X86::BI__builtin_ia32_vcvttss2si64:
3503 case X86::BI__builtin_ia32_vcvttss2usi32:
3504 case X86::BI__builtin_ia32_vcvttss2usi64:
3505 ArgNum = 1;
3506 break;
3507 case X86::BI__builtin_ia32_maxpd512:
3508 case X86::BI__builtin_ia32_maxps512:
3509 case X86::BI__builtin_ia32_minpd512:
3510 case X86::BI__builtin_ia32_minps512:
3511 ArgNum = 2;
3512 break;
3513 case X86::BI__builtin_ia32_cvtps2pd512_mask:
3514 case X86::BI__builtin_ia32_cvttpd2dq512_mask:
3515 case X86::BI__builtin_ia32_cvttpd2qq512_mask:
3516 case X86::BI__builtin_ia32_cvttpd2udq512_mask:
3517 case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
3518 case X86::BI__builtin_ia32_cvttps2dq512_mask:
3519 case X86::BI__builtin_ia32_cvttps2qq512_mask:
3520 case X86::BI__builtin_ia32_cvttps2udq512_mask:
3521 case X86::BI__builtin_ia32_cvttps2uqq512_mask:
3522 case X86::BI__builtin_ia32_exp2pd_mask:
3523 case X86::BI__builtin_ia32_exp2ps_mask:
3524 case X86::BI__builtin_ia32_getexppd512_mask:
3525 case X86::BI__builtin_ia32_getexpps512_mask:
3526 case X86::BI__builtin_ia32_rcp28pd_mask:
3527 case X86::BI__builtin_ia32_rcp28ps_mask:
3528 case X86::BI__builtin_ia32_rsqrt28pd_mask:
3529 case X86::BI__builtin_ia32_rsqrt28ps_mask:
3530 case X86::BI__builtin_ia32_vcomisd:
3531 case X86::BI__builtin_ia32_vcomiss:
3532 case X86::BI__builtin_ia32_vcvtph2ps512_mask:
3533 ArgNum = 3;
3534 break;
3535 case X86::BI__builtin_ia32_cmppd512_mask:
3536 case X86::BI__builtin_ia32_cmpps512_mask:
3537 case X86::BI__builtin_ia32_cmpsd_mask:
3538 case X86::BI__builtin_ia32_cmpss_mask:
3539 case X86::BI__builtin_ia32_cvtss2sd_round_mask:
3540 case X86::BI__builtin_ia32_getexpsd128_round_mask:
3541 case X86::BI__builtin_ia32_getexpss128_round_mask:
3542 case X86::BI__builtin_ia32_getmantpd512_mask:
3543 case X86::BI__builtin_ia32_getmantps512_mask:
3544 case X86::BI__builtin_ia32_maxsd_round_mask:
3545 case X86::BI__builtin_ia32_maxss_round_mask:
3546 case X86::BI__builtin_ia32_minsd_round_mask:
3547 case X86::BI__builtin_ia32_minss_round_mask:
3548 case X86::BI__builtin_ia32_rcp28sd_round_mask:
3549 case X86::BI__builtin_ia32_rcp28ss_round_mask:
3550 case X86::BI__builtin_ia32_reducepd512_mask:
3551 case X86::BI__builtin_ia32_reduceps512_mask:
3552 case X86::BI__builtin_ia32_rndscalepd_mask:
3553 case X86::BI__builtin_ia32_rndscaleps_mask:
3554 case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
3555 case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
3556 ArgNum = 4;
3557 break;
3558 case X86::BI__builtin_ia32_fixupimmpd512_mask:
3559 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3560 case X86::BI__builtin_ia32_fixupimmps512_mask:
3561 case X86::BI__builtin_ia32_fixupimmps512_maskz:
3562 case X86::BI__builtin_ia32_fixupimmsd_mask:
3563 case X86::BI__builtin_ia32_fixupimmsd_maskz:
3564 case X86::BI__builtin_ia32_fixupimmss_mask:
3565 case X86::BI__builtin_ia32_fixupimmss_maskz:
3566 case X86::BI__builtin_ia32_getmantsd_round_mask:
3567 case X86::BI__builtin_ia32_getmantss_round_mask:
3568 case X86::BI__builtin_ia32_rangepd512_mask:
3569 case X86::BI__builtin_ia32_rangeps512_mask:
3570 case X86::BI__builtin_ia32_rangesd128_round_mask:
3571 case X86::BI__builtin_ia32_rangess128_round_mask:
3572 case X86::BI__builtin_ia32_reducesd_mask:
3573 case X86::BI__builtin_ia32_reducess_mask:
3574 case X86::BI__builtin_ia32_rndscalesd_round_mask:
3575 case X86::BI__builtin_ia32_rndscaless_round_mask:
3576 ArgNum = 5;
3577 break;
3578 case X86::BI__builtin_ia32_vcvtsd2si64:
3579 case X86::BI__builtin_ia32_vcvtsd2si32:
3580 case X86::BI__builtin_ia32_vcvtsd2usi32:
3581 case X86::BI__builtin_ia32_vcvtsd2usi64:
3582 case X86::BI__builtin_ia32_vcvtss2si32:
3583 case X86::BI__builtin_ia32_vcvtss2si64:
3584 case X86::BI__builtin_ia32_vcvtss2usi32:
3585 case X86::BI__builtin_ia32_vcvtss2usi64:
3586 case X86::BI__builtin_ia32_sqrtpd512:
3587 case X86::BI__builtin_ia32_sqrtps512:
3588 ArgNum = 1;
3589 HasRC = true;
3590 break;
3591 case X86::BI__builtin_ia32_addpd512:
3592 case X86::BI__builtin_ia32_addps512:
3593 case X86::BI__builtin_ia32_divpd512:
3594 case X86::BI__builtin_ia32_divps512:
3595 case X86::BI__builtin_ia32_mulpd512:
3596 case X86::BI__builtin_ia32_mulps512:
3597 case X86::BI__builtin_ia32_subpd512:
3598 case X86::BI__builtin_ia32_subps512:
3599 case X86::BI__builtin_ia32_cvtsi2sd64:
3600 case X86::BI__builtin_ia32_cvtsi2ss32:
3601 case X86::BI__builtin_ia32_cvtsi2ss64:
3602 case X86::BI__builtin_ia32_cvtusi2sd64:
3603 case X86::BI__builtin_ia32_cvtusi2ss32:
3604 case X86::BI__builtin_ia32_cvtusi2ss64:
3605 ArgNum = 2;
3606 HasRC = true;
3607 break;
3608 case X86::BI__builtin_ia32_cvtdq2ps512_mask:
3609 case X86::BI__builtin_ia32_cvtudq2ps512_mask:
3610 case X86::BI__builtin_ia32_cvtpd2ps512_mask:
3611 case X86::BI__builtin_ia32_cvtpd2dq512_mask:
3612 case X86::BI__builtin_ia32_cvtpd2qq512_mask:
3613 case X86::BI__builtin_ia32_cvtpd2udq512_mask:
3614 case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
3615 case X86::BI__builtin_ia32_cvtps2dq512_mask:
3616 case X86::BI__builtin_ia32_cvtps2qq512_mask:
3617 case X86::BI__builtin_ia32_cvtps2udq512_mask:
3618 case X86::BI__builtin_ia32_cvtps2uqq512_mask:
3619 case X86::BI__builtin_ia32_cvtqq2pd512_mask:
3620 case X86::BI__builtin_ia32_cvtqq2ps512_mask:
3621 case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
3622 case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
3623 ArgNum = 3;
3624 HasRC = true;
3625 break;
3626 case X86::BI__builtin_ia32_addss_round_mask:
3627 case X86::BI__builtin_ia32_addsd_round_mask:
3628 case X86::BI__builtin_ia32_divss_round_mask:
3629 case X86::BI__builtin_ia32_divsd_round_mask:
3630 case X86::BI__builtin_ia32_mulss_round_mask:
3631 case X86::BI__builtin_ia32_mulsd_round_mask:
3632 case X86::BI__builtin_ia32_subss_round_mask:
3633 case X86::BI__builtin_ia32_subsd_round_mask:
3634 case X86::BI__builtin_ia32_scalefpd512_mask:
3635 case X86::BI__builtin_ia32_scalefps512_mask:
3636 case X86::BI__builtin_ia32_scalefsd_round_mask:
3637 case X86::BI__builtin_ia32_scalefss_round_mask:
3638 case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
3639 case X86::BI__builtin_ia32_sqrtsd_round_mask:
3640 case X86::BI__builtin_ia32_sqrtss_round_mask:
3641 case X86::BI__builtin_ia32_vfmaddsd3_mask:
3642 case X86::BI__builtin_ia32_vfmaddsd3_maskz:
3643 case X86::BI__builtin_ia32_vfmaddsd3_mask3:
3644 case X86::BI__builtin_ia32_vfmaddss3_mask:
3645 case X86::BI__builtin_ia32_vfmaddss3_maskz:
3646 case X86::BI__builtin_ia32_vfmaddss3_mask3:
3647 case X86::BI__builtin_ia32_vfmaddpd512_mask:
3648 case X86::BI__builtin_ia32_vfmaddpd512_maskz:
3649 case X86::BI__builtin_ia32_vfmaddpd512_mask3:
3650 case X86::BI__builtin_ia32_vfmsubpd512_mask3:
3651 case X86::BI__builtin_ia32_vfmaddps512_mask:
3652 case X86::BI__builtin_ia32_vfmaddps512_maskz:
3653 case X86::BI__builtin_ia32_vfmaddps512_mask3:
3654 case X86::BI__builtin_ia32_vfmsubps512_mask3:
3655 case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
3656 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
3657 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
3658 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
3659 case X86::BI__builtin_ia32_vfmaddsubps512_mask:
3660 case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
3661 case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
3662 case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
3663 ArgNum = 4;
3664 HasRC = true;
3665 break;
3666 }
3667
3668 llvm::APSInt Result;
3669
3670 // We can't check the value of a dependent argument.
3671 Expr *Arg = TheCall->getArg(ArgNum);
3672 if (Arg->isTypeDependent() || Arg->isValueDependent())
3673 return false;
3674
3675 // Check constant-ness first.
3676 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3677 return true;
3678
3679 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
3680 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
3681 // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
3682 // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
3683 if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
3684 Result == 8/*ROUND_NO_EXC*/ ||
3685 (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
3686 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
3687 return false;
3688
3689 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
3690 << Arg->getSourceRange();
3691 }
3692
3693 // Check if the gather/scatter scale is legal.
CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,CallExpr * TheCall)3694 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
3695 CallExpr *TheCall) {
3696 unsigned ArgNum = 0;
3697 switch (BuiltinID) {
3698 default:
3699 return false;
3700 case X86::BI__builtin_ia32_gatherpfdpd:
3701 case X86::BI__builtin_ia32_gatherpfdps:
3702 case X86::BI__builtin_ia32_gatherpfqpd:
3703 case X86::BI__builtin_ia32_gatherpfqps:
3704 case X86::BI__builtin_ia32_scatterpfdpd:
3705 case X86::BI__builtin_ia32_scatterpfdps:
3706 case X86::BI__builtin_ia32_scatterpfqpd:
3707 case X86::BI__builtin_ia32_scatterpfqps:
3708 ArgNum = 3;
3709 break;
3710 case X86::BI__builtin_ia32_gatherd_pd:
3711 case X86::BI__builtin_ia32_gatherd_pd256:
3712 case X86::BI__builtin_ia32_gatherq_pd:
3713 case X86::BI__builtin_ia32_gatherq_pd256:
3714 case X86::BI__builtin_ia32_gatherd_ps:
3715 case X86::BI__builtin_ia32_gatherd_ps256:
3716 case X86::BI__builtin_ia32_gatherq_ps:
3717 case X86::BI__builtin_ia32_gatherq_ps256:
3718 case X86::BI__builtin_ia32_gatherd_q:
3719 case X86::BI__builtin_ia32_gatherd_q256:
3720 case X86::BI__builtin_ia32_gatherq_q:
3721 case X86::BI__builtin_ia32_gatherq_q256:
3722 case X86::BI__builtin_ia32_gatherd_d:
3723 case X86::BI__builtin_ia32_gatherd_d256:
3724 case X86::BI__builtin_ia32_gatherq_d:
3725 case X86::BI__builtin_ia32_gatherq_d256:
3726 case X86::BI__builtin_ia32_gather3div2df:
3727 case X86::BI__builtin_ia32_gather3div2di:
3728 case X86::BI__builtin_ia32_gather3div4df:
3729 case X86::BI__builtin_ia32_gather3div4di:
3730 case X86::BI__builtin_ia32_gather3div4sf:
3731 case X86::BI__builtin_ia32_gather3div4si:
3732 case X86::BI__builtin_ia32_gather3div8sf:
3733 case X86::BI__builtin_ia32_gather3div8si:
3734 case X86::BI__builtin_ia32_gather3siv2df:
3735 case X86::BI__builtin_ia32_gather3siv2di:
3736 case X86::BI__builtin_ia32_gather3siv4df:
3737 case X86::BI__builtin_ia32_gather3siv4di:
3738 case X86::BI__builtin_ia32_gather3siv4sf:
3739 case X86::BI__builtin_ia32_gather3siv4si:
3740 case X86::BI__builtin_ia32_gather3siv8sf:
3741 case X86::BI__builtin_ia32_gather3siv8si:
3742 case X86::BI__builtin_ia32_gathersiv8df:
3743 case X86::BI__builtin_ia32_gathersiv16sf:
3744 case X86::BI__builtin_ia32_gatherdiv8df:
3745 case X86::BI__builtin_ia32_gatherdiv16sf:
3746 case X86::BI__builtin_ia32_gathersiv8di:
3747 case X86::BI__builtin_ia32_gathersiv16si:
3748 case X86::BI__builtin_ia32_gatherdiv8di:
3749 case X86::BI__builtin_ia32_gatherdiv16si:
3750 case X86::BI__builtin_ia32_scatterdiv2df:
3751 case X86::BI__builtin_ia32_scatterdiv2di:
3752 case X86::BI__builtin_ia32_scatterdiv4df:
3753 case X86::BI__builtin_ia32_scatterdiv4di:
3754 case X86::BI__builtin_ia32_scatterdiv4sf:
3755 case X86::BI__builtin_ia32_scatterdiv4si:
3756 case X86::BI__builtin_ia32_scatterdiv8sf:
3757 case X86::BI__builtin_ia32_scatterdiv8si:
3758 case X86::BI__builtin_ia32_scattersiv2df:
3759 case X86::BI__builtin_ia32_scattersiv2di:
3760 case X86::BI__builtin_ia32_scattersiv4df:
3761 case X86::BI__builtin_ia32_scattersiv4di:
3762 case X86::BI__builtin_ia32_scattersiv4sf:
3763 case X86::BI__builtin_ia32_scattersiv4si:
3764 case X86::BI__builtin_ia32_scattersiv8sf:
3765 case X86::BI__builtin_ia32_scattersiv8si:
3766 case X86::BI__builtin_ia32_scattersiv8df:
3767 case X86::BI__builtin_ia32_scattersiv16sf:
3768 case X86::BI__builtin_ia32_scatterdiv8df:
3769 case X86::BI__builtin_ia32_scatterdiv16sf:
3770 case X86::BI__builtin_ia32_scattersiv8di:
3771 case X86::BI__builtin_ia32_scattersiv16si:
3772 case X86::BI__builtin_ia32_scatterdiv8di:
3773 case X86::BI__builtin_ia32_scatterdiv16si:
3774 ArgNum = 4;
3775 break;
3776 }
3777
3778 llvm::APSInt Result;
3779
3780 // We can't check the value of a dependent argument.
3781 Expr *Arg = TheCall->getArg(ArgNum);
3782 if (Arg->isTypeDependent() || Arg->isValueDependent())
3783 return false;
3784
3785 // Check constant-ness first.
3786 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3787 return true;
3788
3789 if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
3790 return false;
3791
3792 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
3793 << Arg->getSourceRange();
3794 }
3795
3796 enum { TileRegLow = 0, TileRegHigh = 7 };
3797
CheckX86BuiltinTileArgumentsRange(CallExpr * TheCall,ArrayRef<int> ArgNums)3798 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall,
3799 ArrayRef<int> ArgNums) {
3800 for (int ArgNum : ArgNums) {
3801 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh))
3802 return true;
3803 }
3804 return false;
3805 }
3806
CheckX86BuiltinTileDuplicate(CallExpr * TheCall,ArrayRef<int> ArgNums)3807 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall,
3808 ArrayRef<int> ArgNums) {
3809 // Because the max number of tile register is TileRegHigh + 1, so here we use
3810 // each bit to represent the usage of them in bitset.
3811 std::bitset<TileRegHigh + 1> ArgValues;
3812 for (int ArgNum : ArgNums) {
3813 Expr *Arg = TheCall->getArg(ArgNum);
3814 if (Arg->isTypeDependent() || Arg->isValueDependent())
3815 continue;
3816
3817 llvm::APSInt Result;
3818 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3819 return true;
3820 int ArgExtValue = Result.getExtValue();
3821 assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) &&
3822 "Incorrect tile register num.");
3823 if (ArgValues.test(ArgExtValue))
3824 return Diag(TheCall->getBeginLoc(),
3825 diag::err_x86_builtin_tile_arg_duplicate)
3826 << TheCall->getArg(ArgNum)->getSourceRange();
3827 ArgValues.set(ArgExtValue);
3828 }
3829 return false;
3830 }
3831
CheckX86BuiltinTileRangeAndDuplicate(CallExpr * TheCall,ArrayRef<int> ArgNums)3832 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall,
3833 ArrayRef<int> ArgNums) {
3834 return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) ||
3835 CheckX86BuiltinTileDuplicate(TheCall, ArgNums);
3836 }
3837
CheckX86BuiltinTileArguments(unsigned BuiltinID,CallExpr * TheCall)3838 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) {
3839 switch (BuiltinID) {
3840 default:
3841 return false;
3842 case X86::BI__builtin_ia32_tileloadd64:
3843 case X86::BI__builtin_ia32_tileloaddt164:
3844 case X86::BI__builtin_ia32_tilestored64:
3845 case X86::BI__builtin_ia32_tilezero:
3846 return CheckX86BuiltinTileArgumentsRange(TheCall, 0);
3847 case X86::BI__builtin_ia32_tdpbssd:
3848 case X86::BI__builtin_ia32_tdpbsud:
3849 case X86::BI__builtin_ia32_tdpbusd:
3850 case X86::BI__builtin_ia32_tdpbuud:
3851 case X86::BI__builtin_ia32_tdpbf16ps:
3852 return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2});
3853 }
3854 }
isX86_32Builtin(unsigned BuiltinID)3855 static bool isX86_32Builtin(unsigned BuiltinID) {
3856 // These builtins only work on x86-32 targets.
3857 switch (BuiltinID) {
3858 case X86::BI__builtin_ia32_readeflags_u32:
3859 case X86::BI__builtin_ia32_writeeflags_u32:
3860 return true;
3861 }
3862
3863 return false;
3864 }
3865
CheckX86BuiltinFunctionCall(const TargetInfo & TI,unsigned BuiltinID,CallExpr * TheCall)3866 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3867 CallExpr *TheCall) {
3868 if (BuiltinID == X86::BI__builtin_cpu_supports)
3869 return SemaBuiltinCpuSupports(*this, TI, TheCall);
3870
3871 if (BuiltinID == X86::BI__builtin_cpu_is)
3872 return SemaBuiltinCpuIs(*this, TI, TheCall);
3873
3874 // Check for 32-bit only builtins on a 64-bit target.
3875 const llvm::Triple &TT = TI.getTriple();
3876 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
3877 return Diag(TheCall->getCallee()->getBeginLoc(),
3878 diag::err_32_bit_builtin_64_bit_tgt);
3879
3880 // If the intrinsic has rounding or SAE make sure its valid.
3881 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
3882 return true;
3883
3884 // If the intrinsic has a gather/scatter scale immediate make sure its valid.
3885 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
3886 return true;
3887
3888 // If the intrinsic has a tile arguments, make sure they are valid.
3889 if (CheckX86BuiltinTileArguments(BuiltinID, TheCall))
3890 return true;
3891
3892 // For intrinsics which take an immediate value as part of the instruction,
3893 // range check them here.
3894 int i = 0, l = 0, u = 0;
3895 switch (BuiltinID) {
3896 default:
3897 return false;
3898 case X86::BI__builtin_ia32_vec_ext_v2si:
3899 case X86::BI__builtin_ia32_vec_ext_v2di:
3900 case X86::BI__builtin_ia32_vextractf128_pd256:
3901 case X86::BI__builtin_ia32_vextractf128_ps256:
3902 case X86::BI__builtin_ia32_vextractf128_si256:
3903 case X86::BI__builtin_ia32_extract128i256:
3904 case X86::BI__builtin_ia32_extractf64x4_mask:
3905 case X86::BI__builtin_ia32_extracti64x4_mask:
3906 case X86::BI__builtin_ia32_extractf32x8_mask:
3907 case X86::BI__builtin_ia32_extracti32x8_mask:
3908 case X86::BI__builtin_ia32_extractf64x2_256_mask:
3909 case X86::BI__builtin_ia32_extracti64x2_256_mask:
3910 case X86::BI__builtin_ia32_extractf32x4_256_mask:
3911 case X86::BI__builtin_ia32_extracti32x4_256_mask:
3912 i = 1; l = 0; u = 1;
3913 break;
3914 case X86::BI__builtin_ia32_vec_set_v2di:
3915 case X86::BI__builtin_ia32_vinsertf128_pd256:
3916 case X86::BI__builtin_ia32_vinsertf128_ps256:
3917 case X86::BI__builtin_ia32_vinsertf128_si256:
3918 case X86::BI__builtin_ia32_insert128i256:
3919 case X86::BI__builtin_ia32_insertf32x8:
3920 case X86::BI__builtin_ia32_inserti32x8:
3921 case X86::BI__builtin_ia32_insertf64x4:
3922 case X86::BI__builtin_ia32_inserti64x4:
3923 case X86::BI__builtin_ia32_insertf64x2_256:
3924 case X86::BI__builtin_ia32_inserti64x2_256:
3925 case X86::BI__builtin_ia32_insertf32x4_256:
3926 case X86::BI__builtin_ia32_inserti32x4_256:
3927 i = 2; l = 0; u = 1;
3928 break;
3929 case X86::BI__builtin_ia32_vpermilpd:
3930 case X86::BI__builtin_ia32_vec_ext_v4hi:
3931 case X86::BI__builtin_ia32_vec_ext_v4si:
3932 case X86::BI__builtin_ia32_vec_ext_v4sf:
3933 case X86::BI__builtin_ia32_vec_ext_v4di:
3934 case X86::BI__builtin_ia32_extractf32x4_mask:
3935 case X86::BI__builtin_ia32_extracti32x4_mask:
3936 case X86::BI__builtin_ia32_extractf64x2_512_mask:
3937 case X86::BI__builtin_ia32_extracti64x2_512_mask:
3938 i = 1; l = 0; u = 3;
3939 break;
3940 case X86::BI_mm_prefetch:
3941 case X86::BI__builtin_ia32_vec_ext_v8hi:
3942 case X86::BI__builtin_ia32_vec_ext_v8si:
3943 i = 1; l = 0; u = 7;
3944 break;
3945 case X86::BI__builtin_ia32_sha1rnds4:
3946 case X86::BI__builtin_ia32_blendpd:
3947 case X86::BI__builtin_ia32_shufpd:
3948 case X86::BI__builtin_ia32_vec_set_v4hi:
3949 case X86::BI__builtin_ia32_vec_set_v4si:
3950 case X86::BI__builtin_ia32_vec_set_v4di:
3951 case X86::BI__builtin_ia32_shuf_f32x4_256:
3952 case X86::BI__builtin_ia32_shuf_f64x2_256:
3953 case X86::BI__builtin_ia32_shuf_i32x4_256:
3954 case X86::BI__builtin_ia32_shuf_i64x2_256:
3955 case X86::BI__builtin_ia32_insertf64x2_512:
3956 case X86::BI__builtin_ia32_inserti64x2_512:
3957 case X86::BI__builtin_ia32_insertf32x4:
3958 case X86::BI__builtin_ia32_inserti32x4:
3959 i = 2; l = 0; u = 3;
3960 break;
3961 case X86::BI__builtin_ia32_vpermil2pd:
3962 case X86::BI__builtin_ia32_vpermil2pd256:
3963 case X86::BI__builtin_ia32_vpermil2ps:
3964 case X86::BI__builtin_ia32_vpermil2ps256:
3965 i = 3; l = 0; u = 3;
3966 break;
3967 case X86::BI__builtin_ia32_cmpb128_mask:
3968 case X86::BI__builtin_ia32_cmpw128_mask:
3969 case X86::BI__builtin_ia32_cmpd128_mask:
3970 case X86::BI__builtin_ia32_cmpq128_mask:
3971 case X86::BI__builtin_ia32_cmpb256_mask:
3972 case X86::BI__builtin_ia32_cmpw256_mask:
3973 case X86::BI__builtin_ia32_cmpd256_mask:
3974 case X86::BI__builtin_ia32_cmpq256_mask:
3975 case X86::BI__builtin_ia32_cmpb512_mask:
3976 case X86::BI__builtin_ia32_cmpw512_mask:
3977 case X86::BI__builtin_ia32_cmpd512_mask:
3978 case X86::BI__builtin_ia32_cmpq512_mask:
3979 case X86::BI__builtin_ia32_ucmpb128_mask:
3980 case X86::BI__builtin_ia32_ucmpw128_mask:
3981 case X86::BI__builtin_ia32_ucmpd128_mask:
3982 case X86::BI__builtin_ia32_ucmpq128_mask:
3983 case X86::BI__builtin_ia32_ucmpb256_mask:
3984 case X86::BI__builtin_ia32_ucmpw256_mask:
3985 case X86::BI__builtin_ia32_ucmpd256_mask:
3986 case X86::BI__builtin_ia32_ucmpq256_mask:
3987 case X86::BI__builtin_ia32_ucmpb512_mask:
3988 case X86::BI__builtin_ia32_ucmpw512_mask:
3989 case X86::BI__builtin_ia32_ucmpd512_mask:
3990 case X86::BI__builtin_ia32_ucmpq512_mask:
3991 case X86::BI__builtin_ia32_vpcomub:
3992 case X86::BI__builtin_ia32_vpcomuw:
3993 case X86::BI__builtin_ia32_vpcomud:
3994 case X86::BI__builtin_ia32_vpcomuq:
3995 case X86::BI__builtin_ia32_vpcomb:
3996 case X86::BI__builtin_ia32_vpcomw:
3997 case X86::BI__builtin_ia32_vpcomd:
3998 case X86::BI__builtin_ia32_vpcomq:
3999 case X86::BI__builtin_ia32_vec_set_v8hi:
4000 case X86::BI__builtin_ia32_vec_set_v8si:
4001 i = 2; l = 0; u = 7;
4002 break;
4003 case X86::BI__builtin_ia32_vpermilpd256:
4004 case X86::BI__builtin_ia32_roundps:
4005 case X86::BI__builtin_ia32_roundpd:
4006 case X86::BI__builtin_ia32_roundps256:
4007 case X86::BI__builtin_ia32_roundpd256:
4008 case X86::BI__builtin_ia32_getmantpd128_mask:
4009 case X86::BI__builtin_ia32_getmantpd256_mask:
4010 case X86::BI__builtin_ia32_getmantps128_mask:
4011 case X86::BI__builtin_ia32_getmantps256_mask:
4012 case X86::BI__builtin_ia32_getmantpd512_mask:
4013 case X86::BI__builtin_ia32_getmantps512_mask:
4014 case X86::BI__builtin_ia32_vec_ext_v16qi:
4015 case X86::BI__builtin_ia32_vec_ext_v16hi:
4016 i = 1; l = 0; u = 15;
4017 break;
4018 case X86::BI__builtin_ia32_pblendd128:
4019 case X86::BI__builtin_ia32_blendps:
4020 case X86::BI__builtin_ia32_blendpd256:
4021 case X86::BI__builtin_ia32_shufpd256:
4022 case X86::BI__builtin_ia32_roundss:
4023 case X86::BI__builtin_ia32_roundsd:
4024 case X86::BI__builtin_ia32_rangepd128_mask:
4025 case X86::BI__builtin_ia32_rangepd256_mask:
4026 case X86::BI__builtin_ia32_rangepd512_mask:
4027 case X86::BI__builtin_ia32_rangeps128_mask:
4028 case X86::BI__builtin_ia32_rangeps256_mask:
4029 case X86::BI__builtin_ia32_rangeps512_mask:
4030 case X86::BI__builtin_ia32_getmantsd_round_mask:
4031 case X86::BI__builtin_ia32_getmantss_round_mask:
4032 case X86::BI__builtin_ia32_vec_set_v16qi:
4033 case X86::BI__builtin_ia32_vec_set_v16hi:
4034 i = 2; l = 0; u = 15;
4035 break;
4036 case X86::BI__builtin_ia32_vec_ext_v32qi:
4037 i = 1; l = 0; u = 31;
4038 break;
4039 case X86::BI__builtin_ia32_cmpps:
4040 case X86::BI__builtin_ia32_cmpss:
4041 case X86::BI__builtin_ia32_cmppd:
4042 case X86::BI__builtin_ia32_cmpsd:
4043 case X86::BI__builtin_ia32_cmpps256:
4044 case X86::BI__builtin_ia32_cmppd256:
4045 case X86::BI__builtin_ia32_cmpps128_mask:
4046 case X86::BI__builtin_ia32_cmppd128_mask:
4047 case X86::BI__builtin_ia32_cmpps256_mask:
4048 case X86::BI__builtin_ia32_cmppd256_mask:
4049 case X86::BI__builtin_ia32_cmpps512_mask:
4050 case X86::BI__builtin_ia32_cmppd512_mask:
4051 case X86::BI__builtin_ia32_cmpsd_mask:
4052 case X86::BI__builtin_ia32_cmpss_mask:
4053 case X86::BI__builtin_ia32_vec_set_v32qi:
4054 i = 2; l = 0; u = 31;
4055 break;
4056 case X86::BI__builtin_ia32_permdf256:
4057 case X86::BI__builtin_ia32_permdi256:
4058 case X86::BI__builtin_ia32_permdf512:
4059 case X86::BI__builtin_ia32_permdi512:
4060 case X86::BI__builtin_ia32_vpermilps:
4061 case X86::BI__builtin_ia32_vpermilps256:
4062 case X86::BI__builtin_ia32_vpermilpd512:
4063 case X86::BI__builtin_ia32_vpermilps512:
4064 case X86::BI__builtin_ia32_pshufd:
4065 case X86::BI__builtin_ia32_pshufd256:
4066 case X86::BI__builtin_ia32_pshufd512:
4067 case X86::BI__builtin_ia32_pshufhw:
4068 case X86::BI__builtin_ia32_pshufhw256:
4069 case X86::BI__builtin_ia32_pshufhw512:
4070 case X86::BI__builtin_ia32_pshuflw:
4071 case X86::BI__builtin_ia32_pshuflw256:
4072 case X86::BI__builtin_ia32_pshuflw512:
4073 case X86::BI__builtin_ia32_vcvtps2ph:
4074 case X86::BI__builtin_ia32_vcvtps2ph_mask:
4075 case X86::BI__builtin_ia32_vcvtps2ph256:
4076 case X86::BI__builtin_ia32_vcvtps2ph256_mask:
4077 case X86::BI__builtin_ia32_vcvtps2ph512_mask:
4078 case X86::BI__builtin_ia32_rndscaleps_128_mask:
4079 case X86::BI__builtin_ia32_rndscalepd_128_mask:
4080 case X86::BI__builtin_ia32_rndscaleps_256_mask:
4081 case X86::BI__builtin_ia32_rndscalepd_256_mask:
4082 case X86::BI__builtin_ia32_rndscaleps_mask:
4083 case X86::BI__builtin_ia32_rndscalepd_mask:
4084 case X86::BI__builtin_ia32_reducepd128_mask:
4085 case X86::BI__builtin_ia32_reducepd256_mask:
4086 case X86::BI__builtin_ia32_reducepd512_mask:
4087 case X86::BI__builtin_ia32_reduceps128_mask:
4088 case X86::BI__builtin_ia32_reduceps256_mask:
4089 case X86::BI__builtin_ia32_reduceps512_mask:
4090 case X86::BI__builtin_ia32_prold512:
4091 case X86::BI__builtin_ia32_prolq512:
4092 case X86::BI__builtin_ia32_prold128:
4093 case X86::BI__builtin_ia32_prold256:
4094 case X86::BI__builtin_ia32_prolq128:
4095 case X86::BI__builtin_ia32_prolq256:
4096 case X86::BI__builtin_ia32_prord512:
4097 case X86::BI__builtin_ia32_prorq512:
4098 case X86::BI__builtin_ia32_prord128:
4099 case X86::BI__builtin_ia32_prord256:
4100 case X86::BI__builtin_ia32_prorq128:
4101 case X86::BI__builtin_ia32_prorq256:
4102 case X86::BI__builtin_ia32_fpclasspd128_mask:
4103 case X86::BI__builtin_ia32_fpclasspd256_mask:
4104 case X86::BI__builtin_ia32_fpclassps128_mask:
4105 case X86::BI__builtin_ia32_fpclassps256_mask:
4106 case X86::BI__builtin_ia32_fpclassps512_mask:
4107 case X86::BI__builtin_ia32_fpclasspd512_mask:
4108 case X86::BI__builtin_ia32_fpclasssd_mask:
4109 case X86::BI__builtin_ia32_fpclassss_mask:
4110 case X86::BI__builtin_ia32_pslldqi128_byteshift:
4111 case X86::BI__builtin_ia32_pslldqi256_byteshift:
4112 case X86::BI__builtin_ia32_pslldqi512_byteshift:
4113 case X86::BI__builtin_ia32_psrldqi128_byteshift:
4114 case X86::BI__builtin_ia32_psrldqi256_byteshift:
4115 case X86::BI__builtin_ia32_psrldqi512_byteshift:
4116 case X86::BI__builtin_ia32_kshiftliqi:
4117 case X86::BI__builtin_ia32_kshiftlihi:
4118 case X86::BI__builtin_ia32_kshiftlisi:
4119 case X86::BI__builtin_ia32_kshiftlidi:
4120 case X86::BI__builtin_ia32_kshiftriqi:
4121 case X86::BI__builtin_ia32_kshiftrihi:
4122 case X86::BI__builtin_ia32_kshiftrisi:
4123 case X86::BI__builtin_ia32_kshiftridi:
4124 i = 1; l = 0; u = 255;
4125 break;
4126 case X86::BI__builtin_ia32_vperm2f128_pd256:
4127 case X86::BI__builtin_ia32_vperm2f128_ps256:
4128 case X86::BI__builtin_ia32_vperm2f128_si256:
4129 case X86::BI__builtin_ia32_permti256:
4130 case X86::BI__builtin_ia32_pblendw128:
4131 case X86::BI__builtin_ia32_pblendw256:
4132 case X86::BI__builtin_ia32_blendps256:
4133 case X86::BI__builtin_ia32_pblendd256:
4134 case X86::BI__builtin_ia32_palignr128:
4135 case X86::BI__builtin_ia32_palignr256:
4136 case X86::BI__builtin_ia32_palignr512:
4137 case X86::BI__builtin_ia32_alignq512:
4138 case X86::BI__builtin_ia32_alignd512:
4139 case X86::BI__builtin_ia32_alignd128:
4140 case X86::BI__builtin_ia32_alignd256:
4141 case X86::BI__builtin_ia32_alignq128:
4142 case X86::BI__builtin_ia32_alignq256:
4143 case X86::BI__builtin_ia32_vcomisd:
4144 case X86::BI__builtin_ia32_vcomiss:
4145 case X86::BI__builtin_ia32_shuf_f32x4:
4146 case X86::BI__builtin_ia32_shuf_f64x2:
4147 case X86::BI__builtin_ia32_shuf_i32x4:
4148 case X86::BI__builtin_ia32_shuf_i64x2:
4149 case X86::BI__builtin_ia32_shufpd512:
4150 case X86::BI__builtin_ia32_shufps:
4151 case X86::BI__builtin_ia32_shufps256:
4152 case X86::BI__builtin_ia32_shufps512:
4153 case X86::BI__builtin_ia32_dbpsadbw128:
4154 case X86::BI__builtin_ia32_dbpsadbw256:
4155 case X86::BI__builtin_ia32_dbpsadbw512:
4156 case X86::BI__builtin_ia32_vpshldd128:
4157 case X86::BI__builtin_ia32_vpshldd256:
4158 case X86::BI__builtin_ia32_vpshldd512:
4159 case X86::BI__builtin_ia32_vpshldq128:
4160 case X86::BI__builtin_ia32_vpshldq256:
4161 case X86::BI__builtin_ia32_vpshldq512:
4162 case X86::BI__builtin_ia32_vpshldw128:
4163 case X86::BI__builtin_ia32_vpshldw256:
4164 case X86::BI__builtin_ia32_vpshldw512:
4165 case X86::BI__builtin_ia32_vpshrdd128:
4166 case X86::BI__builtin_ia32_vpshrdd256:
4167 case X86::BI__builtin_ia32_vpshrdd512:
4168 case X86::BI__builtin_ia32_vpshrdq128:
4169 case X86::BI__builtin_ia32_vpshrdq256:
4170 case X86::BI__builtin_ia32_vpshrdq512:
4171 case X86::BI__builtin_ia32_vpshrdw128:
4172 case X86::BI__builtin_ia32_vpshrdw256:
4173 case X86::BI__builtin_ia32_vpshrdw512:
4174 i = 2; l = 0; u = 255;
4175 break;
4176 case X86::BI__builtin_ia32_fixupimmpd512_mask:
4177 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
4178 case X86::BI__builtin_ia32_fixupimmps512_mask:
4179 case X86::BI__builtin_ia32_fixupimmps512_maskz:
4180 case X86::BI__builtin_ia32_fixupimmsd_mask:
4181 case X86::BI__builtin_ia32_fixupimmsd_maskz:
4182 case X86::BI__builtin_ia32_fixupimmss_mask:
4183 case X86::BI__builtin_ia32_fixupimmss_maskz:
4184 case X86::BI__builtin_ia32_fixupimmpd128_mask:
4185 case X86::BI__builtin_ia32_fixupimmpd128_maskz:
4186 case X86::BI__builtin_ia32_fixupimmpd256_mask:
4187 case X86::BI__builtin_ia32_fixupimmpd256_maskz:
4188 case X86::BI__builtin_ia32_fixupimmps128_mask:
4189 case X86::BI__builtin_ia32_fixupimmps128_maskz:
4190 case X86::BI__builtin_ia32_fixupimmps256_mask:
4191 case X86::BI__builtin_ia32_fixupimmps256_maskz:
4192 case X86::BI__builtin_ia32_pternlogd512_mask:
4193 case X86::BI__builtin_ia32_pternlogd512_maskz:
4194 case X86::BI__builtin_ia32_pternlogq512_mask:
4195 case X86::BI__builtin_ia32_pternlogq512_maskz:
4196 case X86::BI__builtin_ia32_pternlogd128_mask:
4197 case X86::BI__builtin_ia32_pternlogd128_maskz:
4198 case X86::BI__builtin_ia32_pternlogd256_mask:
4199 case X86::BI__builtin_ia32_pternlogd256_maskz:
4200 case X86::BI__builtin_ia32_pternlogq128_mask:
4201 case X86::BI__builtin_ia32_pternlogq128_maskz:
4202 case X86::BI__builtin_ia32_pternlogq256_mask:
4203 case X86::BI__builtin_ia32_pternlogq256_maskz:
4204 i = 3; l = 0; u = 255;
4205 break;
4206 case X86::BI__builtin_ia32_gatherpfdpd:
4207 case X86::BI__builtin_ia32_gatherpfdps:
4208 case X86::BI__builtin_ia32_gatherpfqpd:
4209 case X86::BI__builtin_ia32_gatherpfqps:
4210 case X86::BI__builtin_ia32_scatterpfdpd:
4211 case X86::BI__builtin_ia32_scatterpfdps:
4212 case X86::BI__builtin_ia32_scatterpfqpd:
4213 case X86::BI__builtin_ia32_scatterpfqps:
4214 i = 4; l = 2; u = 3;
4215 break;
4216 case X86::BI__builtin_ia32_reducesd_mask:
4217 case X86::BI__builtin_ia32_reducess_mask:
4218 case X86::BI__builtin_ia32_rndscalesd_round_mask:
4219 case X86::BI__builtin_ia32_rndscaless_round_mask:
4220 i = 4; l = 0; u = 255;
4221 break;
4222 }
4223
4224 // Note that we don't force a hard error on the range check here, allowing
4225 // template-generated or macro-generated dead code to potentially have out-of-
4226 // range values. These need to code generate, but don't need to necessarily
4227 // make any sense. We use a warning that defaults to an error.
4228 return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
4229 }
4230
4231 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
4232 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
4233 /// Returns true when the format fits the function and the FormatStringInfo has
4234 /// been populated.
getFormatStringInfo(const FormatAttr * Format,bool IsCXXMember,FormatStringInfo * FSI)4235 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
4236 FormatStringInfo *FSI) {
4237 FSI->HasVAListArg = Format->getFirstArg() == 0;
4238 FSI->FormatIdx = Format->getFormatIdx() - 1;
4239 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
4240
4241 // The way the format attribute works in GCC, the implicit this argument
4242 // of member functions is counted. However, it doesn't appear in our own
4243 // lists, so decrement format_idx in that case.
4244 if (IsCXXMember) {
4245 if(FSI->FormatIdx == 0)
4246 return false;
4247 --FSI->FormatIdx;
4248 if (FSI->FirstDataArg != 0)
4249 --FSI->FirstDataArg;
4250 }
4251 return true;
4252 }
4253
4254 /// Checks if a the given expression evaluates to null.
4255 ///
4256 /// Returns true if the value evaluates to null.
CheckNonNullExpr(Sema & S,const Expr * Expr)4257 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
4258 // If the expression has non-null type, it doesn't evaluate to null.
4259 if (auto nullability
4260 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
4261 if (*nullability == NullabilityKind::NonNull)
4262 return false;
4263 }
4264
4265 // As a special case, transparent unions initialized with zero are
4266 // considered null for the purposes of the nonnull attribute.
4267 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
4268 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
4269 if (const CompoundLiteralExpr *CLE =
4270 dyn_cast<CompoundLiteralExpr>(Expr))
4271 if (const InitListExpr *ILE =
4272 dyn_cast<InitListExpr>(CLE->getInitializer()))
4273 Expr = ILE->getInit(0);
4274 }
4275
4276 bool Result;
4277 return (!Expr->isValueDependent() &&
4278 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
4279 !Result);
4280 }
4281
CheckNonNullArgument(Sema & S,const Expr * ArgExpr,SourceLocation CallSiteLoc)4282 static void CheckNonNullArgument(Sema &S,
4283 const Expr *ArgExpr,
4284 SourceLocation CallSiteLoc) {
4285 if (CheckNonNullExpr(S, ArgExpr))
4286 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
4287 S.PDiag(diag::warn_null_arg)
4288 << ArgExpr->getSourceRange());
4289 }
4290
GetFormatNSStringIdx(const FormatAttr * Format,unsigned & Idx)4291 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
4292 FormatStringInfo FSI;
4293 if ((GetFormatStringType(Format) == FST_NSString) &&
4294 getFormatStringInfo(Format, false, &FSI)) {
4295 Idx = FSI.FormatIdx;
4296 return true;
4297 }
4298 return false;
4299 }
4300
4301 /// Diagnose use of %s directive in an NSString which is being passed
4302 /// as formatting string to formatting method.
4303 static void
DiagnoseCStringFormatDirectiveInCFAPI(Sema & S,const NamedDecl * FDecl,Expr ** Args,unsigned NumArgs)4304 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
4305 const NamedDecl *FDecl,
4306 Expr **Args,
4307 unsigned NumArgs) {
4308 unsigned Idx = 0;
4309 bool Format = false;
4310 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
4311 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
4312 Idx = 2;
4313 Format = true;
4314 }
4315 else
4316 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4317 if (S.GetFormatNSStringIdx(I, Idx)) {
4318 Format = true;
4319 break;
4320 }
4321 }
4322 if (!Format || NumArgs <= Idx)
4323 return;
4324 const Expr *FormatExpr = Args[Idx];
4325 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
4326 FormatExpr = CSCE->getSubExpr();
4327 const StringLiteral *FormatString;
4328 if (const ObjCStringLiteral *OSL =
4329 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
4330 FormatString = OSL->getString();
4331 else
4332 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
4333 if (!FormatString)
4334 return;
4335 if (S.FormatStringHasSArg(FormatString)) {
4336 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
4337 << "%s" << 1 << 1;
4338 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
4339 << FDecl->getDeclName();
4340 }
4341 }
4342
4343 /// Determine whether the given type has a non-null nullability annotation.
isNonNullType(ASTContext & ctx,QualType type)4344 static bool isNonNullType(ASTContext &ctx, QualType type) {
4345 if (auto nullability = type->getNullability(ctx))
4346 return *nullability == NullabilityKind::NonNull;
4347
4348 return false;
4349 }
4350
CheckNonNullArguments(Sema & S,const NamedDecl * FDecl,const FunctionProtoType * Proto,ArrayRef<const Expr * > Args,SourceLocation CallSiteLoc)4351 static void CheckNonNullArguments(Sema &S,
4352 const NamedDecl *FDecl,
4353 const FunctionProtoType *Proto,
4354 ArrayRef<const Expr *> Args,
4355 SourceLocation CallSiteLoc) {
4356 assert((FDecl || Proto) && "Need a function declaration or prototype");
4357
4358 // Already checked by by constant evaluator.
4359 if (S.isConstantEvaluated())
4360 return;
4361 // Check the attributes attached to the method/function itself.
4362 llvm::SmallBitVector NonNullArgs;
4363 if (FDecl) {
4364 // Handle the nonnull attribute on the function/method declaration itself.
4365 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4366 if (!NonNull->args_size()) {
4367 // Easy case: all pointer arguments are nonnull.
4368 for (const auto *Arg : Args)
4369 if (S.isValidPointerAttrType(Arg->getType()))
4370 CheckNonNullArgument(S, Arg, CallSiteLoc);
4371 return;
4372 }
4373
4374 for (const ParamIdx &Idx : NonNull->args()) {
4375 unsigned IdxAST = Idx.getASTIndex();
4376 if (IdxAST >= Args.size())
4377 continue;
4378 if (NonNullArgs.empty())
4379 NonNullArgs.resize(Args.size());
4380 NonNullArgs.set(IdxAST);
4381 }
4382 }
4383 }
4384
4385 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4386 // Handle the nonnull attribute on the parameters of the
4387 // function/method.
4388 ArrayRef<ParmVarDecl*> parms;
4389 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4390 parms = FD->parameters();
4391 else
4392 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
4393
4394 unsigned ParamIndex = 0;
4395 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4396 I != E; ++I, ++ParamIndex) {
4397 const ParmVarDecl *PVD = *I;
4398 if (PVD->hasAttr<NonNullAttr>() ||
4399 isNonNullType(S.Context, PVD->getType())) {
4400 if (NonNullArgs.empty())
4401 NonNullArgs.resize(Args.size());
4402
4403 NonNullArgs.set(ParamIndex);
4404 }
4405 }
4406 } else {
4407 // If we have a non-function, non-method declaration but no
4408 // function prototype, try to dig out the function prototype.
4409 if (!Proto) {
4410 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4411 QualType type = VD->getType().getNonReferenceType();
4412 if (auto pointerType = type->getAs<PointerType>())
4413 type = pointerType->getPointeeType();
4414 else if (auto blockType = type->getAs<BlockPointerType>())
4415 type = blockType->getPointeeType();
4416 // FIXME: data member pointers?
4417
4418 // Dig out the function prototype, if there is one.
4419 Proto = type->getAs<FunctionProtoType>();
4420 }
4421 }
4422
4423 // Fill in non-null argument information from the nullability
4424 // information on the parameter types (if we have them).
4425 if (Proto) {
4426 unsigned Index = 0;
4427 for (auto paramType : Proto->getParamTypes()) {
4428 if (isNonNullType(S.Context, paramType)) {
4429 if (NonNullArgs.empty())
4430 NonNullArgs.resize(Args.size());
4431
4432 NonNullArgs.set(Index);
4433 }
4434
4435 ++Index;
4436 }
4437 }
4438 }
4439
4440 // Check for non-null arguments.
4441 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4442 ArgIndex != ArgIndexEnd; ++ArgIndex) {
4443 if (NonNullArgs[ArgIndex])
4444 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
4445 }
4446 }
4447
4448 /// Handles the checks for format strings, non-POD arguments to vararg
4449 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
4450 /// attributes.
checkCall(NamedDecl * FDecl,const FunctionProtoType * Proto,const Expr * ThisArg,ArrayRef<const Expr * > Args,bool IsMemberFunction,SourceLocation Loc,SourceRange Range,VariadicCallType CallType)4451 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
4452 const Expr *ThisArg, ArrayRef<const Expr *> Args,
4453 bool IsMemberFunction, SourceLocation Loc,
4454 SourceRange Range, VariadicCallType CallType) {
4455 // FIXME: We should check as much as we can in the template definition.
4456 if (CurContext->isDependentContext())
4457 return;
4458
4459 // Printf and scanf checking.
4460 llvm::SmallBitVector CheckedVarArgs;
4461 if (FDecl) {
4462 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4463 // Only create vector if there are format attributes.
4464 CheckedVarArgs.resize(Args.size());
4465
4466 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
4467 CheckedVarArgs);
4468 }
4469 }
4470
4471 // Refuse POD arguments that weren't caught by the format string
4472 // checks above.
4473 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4474 if (CallType != VariadicDoesNotApply &&
4475 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4476 unsigned NumParams = Proto ? Proto->getNumParams()
4477 : FDecl && isa<FunctionDecl>(FDecl)
4478 ? cast<FunctionDecl>(FDecl)->getNumParams()
4479 : FDecl && isa<ObjCMethodDecl>(FDecl)
4480 ? cast<ObjCMethodDecl>(FDecl)->param_size()
4481 : 0;
4482
4483 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4484 // Args[ArgIdx] can be null in malformed code.
4485 if (const Expr *Arg = Args[ArgIdx]) {
4486 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4487 checkVariadicArgument(Arg, CallType);
4488 }
4489 }
4490 }
4491
4492 if (FDecl || Proto) {
4493 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
4494
4495 // Type safety checking.
4496 if (FDecl) {
4497 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4498 CheckArgumentWithTypeTag(I, Args, Loc);
4499 }
4500 }
4501
4502 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
4503 auto *AA = FDecl->getAttr<AllocAlignAttr>();
4504 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
4505 if (!Arg->isValueDependent()) {
4506 Expr::EvalResult Align;
4507 if (Arg->EvaluateAsInt(Align, Context)) {
4508 const llvm::APSInt &I = Align.Val.getInt();
4509 if (!I.isPowerOf2())
4510 Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
4511 << Arg->getSourceRange();
4512
4513 if (I > Sema::MaximumAlignment)
4514 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
4515 << Arg->getSourceRange() << Sema::MaximumAlignment;
4516 }
4517 }
4518 }
4519
4520 if (FD)
4521 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
4522 }
4523
4524 /// CheckConstructorCall - Check a constructor call for correctness and safety
4525 /// properties not enforced by the C type system.
CheckConstructorCall(FunctionDecl * FDecl,ArrayRef<const Expr * > Args,const FunctionProtoType * Proto,SourceLocation Loc)4526 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
4527 ArrayRef<const Expr *> Args,
4528 const FunctionProtoType *Proto,
4529 SourceLocation Loc) {
4530 VariadicCallType CallType =
4531 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4532 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4533 Loc, SourceRange(), CallType);
4534 }
4535
4536 /// CheckFunctionCall - Check a direct function call for various correctness
4537 /// and safety properties not strictly enforced by the C type system.
CheckFunctionCall(FunctionDecl * FDecl,CallExpr * TheCall,const FunctionProtoType * Proto)4538 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
4539 const FunctionProtoType *Proto) {
4540 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4541 isa<CXXMethodDecl>(FDecl);
4542 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4543 IsMemberOperatorCall;
4544 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4545 TheCall->getCallee());
4546 Expr** Args = TheCall->getArgs();
4547 unsigned NumArgs = TheCall->getNumArgs();
4548
4549 Expr *ImplicitThis = nullptr;
4550 if (IsMemberOperatorCall) {
4551 // If this is a call to a member operator, hide the first argument
4552 // from checkCall.
4553 // FIXME: Our choice of AST representation here is less than ideal.
4554 ImplicitThis = Args[0];
4555 ++Args;
4556 --NumArgs;
4557 } else if (IsMemberFunction)
4558 ImplicitThis =
4559 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4560
4561 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
4562 IsMemberFunction, TheCall->getRParenLoc(),
4563 TheCall->getCallee()->getSourceRange(), CallType);
4564
4565 IdentifierInfo *FnInfo = FDecl->getIdentifier();
4566 // None of the checks below are needed for functions that don't have
4567 // simple names (e.g., C++ conversion functions).
4568 if (!FnInfo)
4569 return false;
4570
4571 CheckAbsoluteValueFunction(TheCall, FDecl);
4572 CheckMaxUnsignedZero(TheCall, FDecl);
4573
4574 if (getLangOpts().ObjC)
4575 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
4576
4577 unsigned CMId = FDecl->getMemoryFunctionKind();
4578
4579 // Handle memory setting and copying functions.
4580 switch (CMId) {
4581 case 0:
4582 return false;
4583 case Builtin::BIstrlcpy: // fallthrough
4584 case Builtin::BIstrlcat:
4585 CheckStrlcpycatArguments(TheCall, FnInfo);
4586 break;
4587 case Builtin::BIstrncat:
4588 CheckStrncatArguments(TheCall, FnInfo);
4589 break;
4590 case Builtin::BIfree:
4591 CheckFreeArguments(TheCall);
4592 break;
4593 default:
4594 CheckMemaccessArguments(TheCall, CMId, FnInfo);
4595 }
4596
4597 return false;
4598 }
4599
CheckObjCMethodCall(ObjCMethodDecl * Method,SourceLocation lbrac,ArrayRef<const Expr * > Args)4600 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
4601 ArrayRef<const Expr *> Args) {
4602 VariadicCallType CallType =
4603 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
4604
4605 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
4606 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
4607 CallType);
4608
4609 return false;
4610 }
4611
CheckPointerCall(NamedDecl * NDecl,CallExpr * TheCall,const FunctionProtoType * Proto)4612 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4613 const FunctionProtoType *Proto) {
4614 QualType Ty;
4615 if (const auto *V = dyn_cast<VarDecl>(NDecl))
4616 Ty = V->getType().getNonReferenceType();
4617 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
4618 Ty = F->getType().getNonReferenceType();
4619 else
4620 return false;
4621
4622 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4623 !Ty->isFunctionProtoType())
4624 return false;
4625
4626 VariadicCallType CallType;
4627 if (!Proto || !Proto->isVariadic()) {
4628 CallType = VariadicDoesNotApply;
4629 } else if (Ty->isBlockPointerType()) {
4630 CallType = VariadicBlock;
4631 } else { // Ty->isFunctionPointerType()
4632 CallType = VariadicFunction;
4633 }
4634
4635 checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
4636 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4637 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4638 TheCall->getCallee()->getSourceRange(), CallType);
4639
4640 return false;
4641 }
4642
4643 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
4644 /// such as function pointers returned from functions.
CheckOtherCall(CallExpr * TheCall,const FunctionProtoType * Proto)4645 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4646 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4647 TheCall->getCallee());
4648 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4649 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4650 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4651 TheCall->getCallee()->getSourceRange(), CallType);
4652
4653 return false;
4654 }
4655
isValidOrderingForOp(int64_t Ordering,AtomicExpr::AtomicOp Op)4656 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4657 if (!llvm::isValidAtomicOrderingCABI(Ordering))
4658 return false;
4659
4660 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4661 switch (Op) {
4662 case AtomicExpr::AO__c11_atomic_init:
4663 case AtomicExpr::AO__opencl_atomic_init:
4664 llvm_unreachable("There is no ordering argument for an init");
4665
4666 case AtomicExpr::AO__c11_atomic_load:
4667 case AtomicExpr::AO__opencl_atomic_load:
4668 case AtomicExpr::AO__atomic_load_n:
4669 case AtomicExpr::AO__atomic_load:
4670 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4671 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4672
4673 case AtomicExpr::AO__c11_atomic_store:
4674 case AtomicExpr::AO__opencl_atomic_store:
4675 case AtomicExpr::AO__atomic_store:
4676 case AtomicExpr::AO__atomic_store_n:
4677 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4678 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4679 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4680
4681 default:
4682 return true;
4683 }
4684 }
4685
SemaAtomicOpsOverloaded(ExprResult TheCallResult,AtomicExpr::AtomicOp Op)4686 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
4687 AtomicExpr::AtomicOp Op) {
4688 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
4689 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4690 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
4691 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
4692 DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
4693 Op);
4694 }
4695
BuildAtomicExpr(SourceRange CallRange,SourceRange ExprRange,SourceLocation RParenLoc,MultiExprArg Args,AtomicExpr::AtomicOp Op,AtomicArgumentOrder ArgOrder)4696 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
4697 SourceLocation RParenLoc, MultiExprArg Args,
4698 AtomicExpr::AtomicOp Op,
4699 AtomicArgumentOrder ArgOrder) {
4700 // All the non-OpenCL operations take one of the following forms.
4701 // The OpenCL operations take the __c11 forms with one extra argument for
4702 // synchronization scope.
4703 enum {
4704 // C __c11_atomic_init(A *, C)
4705 Init,
4706
4707 // C __c11_atomic_load(A *, int)
4708 Load,
4709
4710 // void __atomic_load(A *, CP, int)
4711 LoadCopy,
4712
4713 // void __atomic_store(A *, CP, int)
4714 Copy,
4715
4716 // C __c11_atomic_add(A *, M, int)
4717 Arithmetic,
4718
4719 // C __atomic_exchange_n(A *, CP, int)
4720 Xchg,
4721
4722 // void __atomic_exchange(A *, C *, CP, int)
4723 GNUXchg,
4724
4725 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
4726 C11CmpXchg,
4727
4728 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
4729 GNUCmpXchg
4730 } Form = Init;
4731
4732 const unsigned NumForm = GNUCmpXchg + 1;
4733 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
4734 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
4735 // where:
4736 // C is an appropriate type,
4737 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
4738 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
4739 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
4740 // the int parameters are for orderings.
4741
4742 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
4743 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
4744 "need to update code for modified forms");
4745 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
4746 AtomicExpr::AO__c11_atomic_fetch_min + 1 ==
4747 AtomicExpr::AO__atomic_load,
4748 "need to update code for modified C11 atomics");
4749 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
4750 Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
4751 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
4752 Op <= AtomicExpr::AO__c11_atomic_fetch_min) ||
4753 IsOpenCL;
4754 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
4755 Op == AtomicExpr::AO__atomic_store_n ||
4756 Op == AtomicExpr::AO__atomic_exchange_n ||
4757 Op == AtomicExpr::AO__atomic_compare_exchange_n;
4758 bool IsAddSub = false;
4759
4760 switch (Op) {
4761 case AtomicExpr::AO__c11_atomic_init:
4762 case AtomicExpr::AO__opencl_atomic_init:
4763 Form = Init;
4764 break;
4765
4766 case AtomicExpr::AO__c11_atomic_load:
4767 case AtomicExpr::AO__opencl_atomic_load:
4768 case AtomicExpr::AO__atomic_load_n:
4769 Form = Load;
4770 break;
4771
4772 case AtomicExpr::AO__atomic_load:
4773 Form = LoadCopy;
4774 break;
4775
4776 case AtomicExpr::AO__c11_atomic_store:
4777 case AtomicExpr::AO__opencl_atomic_store:
4778 case AtomicExpr::AO__atomic_store:
4779 case AtomicExpr::AO__atomic_store_n:
4780 Form = Copy;
4781 break;
4782
4783 case AtomicExpr::AO__c11_atomic_fetch_add:
4784 case AtomicExpr::AO__c11_atomic_fetch_sub:
4785 case AtomicExpr::AO__opencl_atomic_fetch_add:
4786 case AtomicExpr::AO__opencl_atomic_fetch_sub:
4787 case AtomicExpr::AO__atomic_fetch_add:
4788 case AtomicExpr::AO__atomic_fetch_sub:
4789 case AtomicExpr::AO__atomic_add_fetch:
4790 case AtomicExpr::AO__atomic_sub_fetch:
4791 IsAddSub = true;
4792 LLVM_FALLTHROUGH;
4793 case AtomicExpr::AO__c11_atomic_fetch_and:
4794 case AtomicExpr::AO__c11_atomic_fetch_or:
4795 case AtomicExpr::AO__c11_atomic_fetch_xor:
4796 case AtomicExpr::AO__opencl_atomic_fetch_and:
4797 case AtomicExpr::AO__opencl_atomic_fetch_or:
4798 case AtomicExpr::AO__opencl_atomic_fetch_xor:
4799 case AtomicExpr::AO__atomic_fetch_and:
4800 case AtomicExpr::AO__atomic_fetch_or:
4801 case AtomicExpr::AO__atomic_fetch_xor:
4802 case AtomicExpr::AO__atomic_fetch_nand:
4803 case AtomicExpr::AO__atomic_and_fetch:
4804 case AtomicExpr::AO__atomic_or_fetch:
4805 case AtomicExpr::AO__atomic_xor_fetch:
4806 case AtomicExpr::AO__atomic_nand_fetch:
4807 case AtomicExpr::AO__c11_atomic_fetch_min:
4808 case AtomicExpr::AO__c11_atomic_fetch_max:
4809 case AtomicExpr::AO__opencl_atomic_fetch_min:
4810 case AtomicExpr::AO__opencl_atomic_fetch_max:
4811 case AtomicExpr::AO__atomic_min_fetch:
4812 case AtomicExpr::AO__atomic_max_fetch:
4813 case AtomicExpr::AO__atomic_fetch_min:
4814 case AtomicExpr::AO__atomic_fetch_max:
4815 Form = Arithmetic;
4816 break;
4817
4818 case AtomicExpr::AO__c11_atomic_exchange:
4819 case AtomicExpr::AO__opencl_atomic_exchange:
4820 case AtomicExpr::AO__atomic_exchange_n:
4821 Form = Xchg;
4822 break;
4823
4824 case AtomicExpr::AO__atomic_exchange:
4825 Form = GNUXchg;
4826 break;
4827
4828 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
4829 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
4830 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
4831 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
4832 Form = C11CmpXchg;
4833 break;
4834
4835 case AtomicExpr::AO__atomic_compare_exchange:
4836 case AtomicExpr::AO__atomic_compare_exchange_n:
4837 Form = GNUCmpXchg;
4838 break;
4839 }
4840
4841 unsigned AdjustedNumArgs = NumArgs[Form];
4842 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
4843 ++AdjustedNumArgs;
4844 // Check we have the right number of arguments.
4845 if (Args.size() < AdjustedNumArgs) {
4846 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
4847 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4848 << ExprRange;
4849 return ExprError();
4850 } else if (Args.size() > AdjustedNumArgs) {
4851 Diag(Args[AdjustedNumArgs]->getBeginLoc(),
4852 diag::err_typecheck_call_too_many_args)
4853 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4854 << ExprRange;
4855 return ExprError();
4856 }
4857
4858 // Inspect the first argument of the atomic operation.
4859 Expr *Ptr = Args[0];
4860 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
4861 if (ConvertedPtr.isInvalid())
4862 return ExprError();
4863
4864 Ptr = ConvertedPtr.get();
4865 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
4866 if (!pointerType) {
4867 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
4868 << Ptr->getType() << Ptr->getSourceRange();
4869 return ExprError();
4870 }
4871
4872 // For a __c11 builtin, this should be a pointer to an _Atomic type.
4873 QualType AtomTy = pointerType->getPointeeType(); // 'A'
4874 QualType ValType = AtomTy; // 'C'
4875 if (IsC11) {
4876 if (!AtomTy->isAtomicType()) {
4877 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
4878 << Ptr->getType() << Ptr->getSourceRange();
4879 return ExprError();
4880 }
4881 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
4882 AtomTy.getAddressSpace() == LangAS::opencl_constant) {
4883 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
4884 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
4885 << Ptr->getSourceRange();
4886 return ExprError();
4887 }
4888 ValType = AtomTy->castAs<AtomicType>()->getValueType();
4889 } else if (Form != Load && Form != LoadCopy) {
4890 if (ValType.isConstQualified()) {
4891 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
4892 << Ptr->getType() << Ptr->getSourceRange();
4893 return ExprError();
4894 }
4895 }
4896
4897 // For an arithmetic operation, the implied arithmetic must be well-formed.
4898 if (Form == Arithmetic) {
4899 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
4900 if (IsAddSub && !ValType->isIntegerType()
4901 && !ValType->isPointerType()) {
4902 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4903 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4904 return ExprError();
4905 }
4906 if (!IsAddSub && !ValType->isIntegerType()) {
4907 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int)
4908 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4909 return ExprError();
4910 }
4911 if (IsC11 && ValType->isPointerType() &&
4912 RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
4913 diag::err_incomplete_type)) {
4914 return ExprError();
4915 }
4916 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
4917 // For __atomic_*_n operations, the value type must be a scalar integral or
4918 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
4919 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4920 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4921 return ExprError();
4922 }
4923
4924 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
4925 !AtomTy->isScalarType()) {
4926 // For GNU atomics, require a trivially-copyable type. This is not part of
4927 // the GNU atomics specification, but we enforce it for sanity.
4928 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
4929 << Ptr->getType() << Ptr->getSourceRange();
4930 return ExprError();
4931 }
4932
4933 switch (ValType.getObjCLifetime()) {
4934 case Qualifiers::OCL_None:
4935 case Qualifiers::OCL_ExplicitNone:
4936 // okay
4937 break;
4938
4939 case Qualifiers::OCL_Weak:
4940 case Qualifiers::OCL_Strong:
4941 case Qualifiers::OCL_Autoreleasing:
4942 // FIXME: Can this happen? By this point, ValType should be known
4943 // to be trivially copyable.
4944 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
4945 << ValType << Ptr->getSourceRange();
4946 return ExprError();
4947 }
4948
4949 // All atomic operations have an overload which takes a pointer to a volatile
4950 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself
4951 // into the result or the other operands. Similarly atomic_load takes a
4952 // pointer to a const 'A'.
4953 ValType.removeLocalVolatile();
4954 ValType.removeLocalConst();
4955 QualType ResultType = ValType;
4956 if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
4957 Form == Init)
4958 ResultType = Context.VoidTy;
4959 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
4960 ResultType = Context.BoolTy;
4961
4962 // The type of a parameter passed 'by value'. In the GNU atomics, such
4963 // arguments are actually passed as pointers.
4964 QualType ByValType = ValType; // 'CP'
4965 bool IsPassedByAddress = false;
4966 if (!IsC11 && !IsN) {
4967 ByValType = Ptr->getType();
4968 IsPassedByAddress = true;
4969 }
4970
4971 SmallVector<Expr *, 5> APIOrderedArgs;
4972 if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
4973 APIOrderedArgs.push_back(Args[0]);
4974 switch (Form) {
4975 case Init:
4976 case Load:
4977 APIOrderedArgs.push_back(Args[1]); // Val1/Order
4978 break;
4979 case LoadCopy:
4980 case Copy:
4981 case Arithmetic:
4982 case Xchg:
4983 APIOrderedArgs.push_back(Args[2]); // Val1
4984 APIOrderedArgs.push_back(Args[1]); // Order
4985 break;
4986 case GNUXchg:
4987 APIOrderedArgs.push_back(Args[2]); // Val1
4988 APIOrderedArgs.push_back(Args[3]); // Val2
4989 APIOrderedArgs.push_back(Args[1]); // Order
4990 break;
4991 case C11CmpXchg:
4992 APIOrderedArgs.push_back(Args[2]); // Val1
4993 APIOrderedArgs.push_back(Args[4]); // Val2
4994 APIOrderedArgs.push_back(Args[1]); // Order
4995 APIOrderedArgs.push_back(Args[3]); // OrderFail
4996 break;
4997 case GNUCmpXchg:
4998 APIOrderedArgs.push_back(Args[2]); // Val1
4999 APIOrderedArgs.push_back(Args[4]); // Val2
5000 APIOrderedArgs.push_back(Args[5]); // Weak
5001 APIOrderedArgs.push_back(Args[1]); // Order
5002 APIOrderedArgs.push_back(Args[3]); // OrderFail
5003 break;
5004 }
5005 } else
5006 APIOrderedArgs.append(Args.begin(), Args.end());
5007
5008 // The first argument's non-CV pointer type is used to deduce the type of
5009 // subsequent arguments, except for:
5010 // - weak flag (always converted to bool)
5011 // - memory order (always converted to int)
5012 // - scope (always converted to int)
5013 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
5014 QualType Ty;
5015 if (i < NumVals[Form] + 1) {
5016 switch (i) {
5017 case 0:
5018 // The first argument is always a pointer. It has a fixed type.
5019 // It is always dereferenced, a nullptr is undefined.
5020 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5021 // Nothing else to do: we already know all we want about this pointer.
5022 continue;
5023 case 1:
5024 // The second argument is the non-atomic operand. For arithmetic, this
5025 // is always passed by value, and for a compare_exchange it is always
5026 // passed by address. For the rest, GNU uses by-address and C11 uses
5027 // by-value.
5028 assert(Form != Load);
5029 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
5030 Ty = ValType;
5031 else if (Form == Copy || Form == Xchg) {
5032 if (IsPassedByAddress) {
5033 // The value pointer is always dereferenced, a nullptr is undefined.
5034 CheckNonNullArgument(*this, APIOrderedArgs[i],
5035 ExprRange.getBegin());
5036 }
5037 Ty = ByValType;
5038 } else if (Form == Arithmetic)
5039 Ty = Context.getPointerDiffType();
5040 else {
5041 Expr *ValArg = APIOrderedArgs[i];
5042 // The value pointer is always dereferenced, a nullptr is undefined.
5043 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
5044 LangAS AS = LangAS::Default;
5045 // Keep address space of non-atomic pointer type.
5046 if (const PointerType *PtrTy =
5047 ValArg->getType()->getAs<PointerType>()) {
5048 AS = PtrTy->getPointeeType().getAddressSpace();
5049 }
5050 Ty = Context.getPointerType(
5051 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
5052 }
5053 break;
5054 case 2:
5055 // The third argument to compare_exchange / GNU exchange is the desired
5056 // value, either by-value (for the C11 and *_n variant) or as a pointer.
5057 if (IsPassedByAddress)
5058 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5059 Ty = ByValType;
5060 break;
5061 case 3:
5062 // The fourth argument to GNU compare_exchange is a 'weak' flag.
5063 Ty = Context.BoolTy;
5064 break;
5065 }
5066 } else {
5067 // The order(s) and scope are always converted to int.
5068 Ty = Context.IntTy;
5069 }
5070
5071 InitializedEntity Entity =
5072 InitializedEntity::InitializeParameter(Context, Ty, false);
5073 ExprResult Arg = APIOrderedArgs[i];
5074 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5075 if (Arg.isInvalid())
5076 return true;
5077 APIOrderedArgs[i] = Arg.get();
5078 }
5079
5080 // Permute the arguments into a 'consistent' order.
5081 SmallVector<Expr*, 5> SubExprs;
5082 SubExprs.push_back(Ptr);
5083 switch (Form) {
5084 case Init:
5085 // Note, AtomicExpr::getVal1() has a special case for this atomic.
5086 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5087 break;
5088 case Load:
5089 SubExprs.push_back(APIOrderedArgs[1]); // Order
5090 break;
5091 case LoadCopy:
5092 case Copy:
5093 case Arithmetic:
5094 case Xchg:
5095 SubExprs.push_back(APIOrderedArgs[2]); // Order
5096 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5097 break;
5098 case GNUXchg:
5099 // Note, AtomicExpr::getVal2() has a special case for this atomic.
5100 SubExprs.push_back(APIOrderedArgs[3]); // Order
5101 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5102 SubExprs.push_back(APIOrderedArgs[2]); // Val2
5103 break;
5104 case C11CmpXchg:
5105 SubExprs.push_back(APIOrderedArgs[3]); // Order
5106 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5107 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
5108 SubExprs.push_back(APIOrderedArgs[2]); // Val2
5109 break;
5110 case GNUCmpXchg:
5111 SubExprs.push_back(APIOrderedArgs[4]); // Order
5112 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5113 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
5114 SubExprs.push_back(APIOrderedArgs[2]); // Val2
5115 SubExprs.push_back(APIOrderedArgs[3]); // Weak
5116 break;
5117 }
5118
5119 if (SubExprs.size() >= 2 && Form != Init) {
5120 if (Optional<llvm::APSInt> Result =
5121 SubExprs[1]->getIntegerConstantExpr(Context))
5122 if (!isValidOrderingForOp(Result->getSExtValue(), Op))
5123 Diag(SubExprs[1]->getBeginLoc(),
5124 diag::warn_atomic_op_has_invalid_memory_order)
5125 << SubExprs[1]->getSourceRange();
5126 }
5127
5128 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
5129 auto *Scope = Args[Args.size() - 1];
5130 if (Optional<llvm::APSInt> Result =
5131 Scope->getIntegerConstantExpr(Context)) {
5132 if (!ScopeModel->isValid(Result->getZExtValue()))
5133 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
5134 << Scope->getSourceRange();
5135 }
5136 SubExprs.push_back(Scope);
5137 }
5138
5139 AtomicExpr *AE = new (Context)
5140 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
5141
5142 if ((Op == AtomicExpr::AO__c11_atomic_load ||
5143 Op == AtomicExpr::AO__c11_atomic_store ||
5144 Op == AtomicExpr::AO__opencl_atomic_load ||
5145 Op == AtomicExpr::AO__opencl_atomic_store ) &&
5146 Context.AtomicUsesUnsupportedLibcall(AE))
5147 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
5148 << ((Op == AtomicExpr::AO__c11_atomic_load ||
5149 Op == AtomicExpr::AO__opencl_atomic_load)
5150 ? 0
5151 : 1);
5152
5153 if (ValType->isExtIntType()) {
5154 Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_ext_int_prohibit);
5155 return ExprError();
5156 }
5157
5158 return AE;
5159 }
5160
5161 /// checkBuiltinArgument - Given a call to a builtin function, perform
5162 /// normal type-checking on the given argument, updating the call in
5163 /// place. This is useful when a builtin function requires custom
5164 /// type-checking for some of its arguments but not necessarily all of
5165 /// them.
5166 ///
5167 /// Returns true on error.
checkBuiltinArgument(Sema & S,CallExpr * E,unsigned ArgIndex)5168 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
5169 FunctionDecl *Fn = E->getDirectCallee();
5170 assert(Fn && "builtin call without direct callee!");
5171
5172 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
5173 InitializedEntity Entity =
5174 InitializedEntity::InitializeParameter(S.Context, Param);
5175
5176 ExprResult Arg = E->getArg(0);
5177 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
5178 if (Arg.isInvalid())
5179 return true;
5180
5181 E->setArg(ArgIndex, Arg.get());
5182 return false;
5183 }
5184
5185 /// We have a call to a function like __sync_fetch_and_add, which is an
5186 /// overloaded function based on the pointer type of its first argument.
5187 /// The main BuildCallExpr routines have already promoted the types of
5188 /// arguments because all of these calls are prototyped as void(...).
5189 ///
5190 /// This function goes through and does final semantic checking for these
5191 /// builtins, as well as generating any warnings.
5192 ExprResult
SemaBuiltinAtomicOverloaded(ExprResult TheCallResult)5193 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
5194 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
5195 Expr *Callee = TheCall->getCallee();
5196 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
5197 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5198
5199 // Ensure that we have at least one argument to do type inference from.
5200 if (TheCall->getNumArgs() < 1) {
5201 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5202 << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
5203 return ExprError();
5204 }
5205
5206 // Inspect the first argument of the atomic builtin. This should always be
5207 // a pointer type, whose element is an integral scalar or pointer type.
5208 // Because it is a pointer type, we don't have to worry about any implicit
5209 // casts here.
5210 // FIXME: We don't allow floating point scalars as input.
5211 Expr *FirstArg = TheCall->getArg(0);
5212 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
5213 if (FirstArgResult.isInvalid())
5214 return ExprError();
5215 FirstArg = FirstArgResult.get();
5216 TheCall->setArg(0, FirstArg);
5217
5218 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
5219 if (!pointerType) {
5220 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
5221 << FirstArg->getType() << FirstArg->getSourceRange();
5222 return ExprError();
5223 }
5224
5225 QualType ValType = pointerType->getPointeeType();
5226 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5227 !ValType->isBlockPointerType()) {
5228 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
5229 << FirstArg->getType() << FirstArg->getSourceRange();
5230 return ExprError();
5231 }
5232
5233 if (ValType.isConstQualified()) {
5234 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
5235 << FirstArg->getType() << FirstArg->getSourceRange();
5236 return ExprError();
5237 }
5238
5239 switch (ValType.getObjCLifetime()) {
5240 case Qualifiers::OCL_None:
5241 case Qualifiers::OCL_ExplicitNone:
5242 // okay
5243 break;
5244
5245 case Qualifiers::OCL_Weak:
5246 case Qualifiers::OCL_Strong:
5247 case Qualifiers::OCL_Autoreleasing:
5248 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
5249 << ValType << FirstArg->getSourceRange();
5250 return ExprError();
5251 }
5252
5253 // Strip any qualifiers off ValType.
5254 ValType = ValType.getUnqualifiedType();
5255
5256 // The majority of builtins return a value, but a few have special return
5257 // types, so allow them to override appropriately below.
5258 QualType ResultType = ValType;
5259
5260 // We need to figure out which concrete builtin this maps onto. For example,
5261 // __sync_fetch_and_add with a 2 byte object turns into
5262 // __sync_fetch_and_add_2.
5263 #define BUILTIN_ROW(x) \
5264 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
5265 Builtin::BI##x##_8, Builtin::BI##x##_16 }
5266
5267 static const unsigned BuiltinIndices[][5] = {
5268 BUILTIN_ROW(__sync_fetch_and_add),
5269 BUILTIN_ROW(__sync_fetch_and_sub),
5270 BUILTIN_ROW(__sync_fetch_and_or),
5271 BUILTIN_ROW(__sync_fetch_and_and),
5272 BUILTIN_ROW(__sync_fetch_and_xor),
5273 BUILTIN_ROW(__sync_fetch_and_nand),
5274
5275 BUILTIN_ROW(__sync_add_and_fetch),
5276 BUILTIN_ROW(__sync_sub_and_fetch),
5277 BUILTIN_ROW(__sync_and_and_fetch),
5278 BUILTIN_ROW(__sync_or_and_fetch),
5279 BUILTIN_ROW(__sync_xor_and_fetch),
5280 BUILTIN_ROW(__sync_nand_and_fetch),
5281
5282 BUILTIN_ROW(__sync_val_compare_and_swap),
5283 BUILTIN_ROW(__sync_bool_compare_and_swap),
5284 BUILTIN_ROW(__sync_lock_test_and_set),
5285 BUILTIN_ROW(__sync_lock_release),
5286 BUILTIN_ROW(__sync_swap)
5287 };
5288 #undef BUILTIN_ROW
5289
5290 // Determine the index of the size.
5291 unsigned SizeIndex;
5292 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
5293 case 1: SizeIndex = 0; break;
5294 case 2: SizeIndex = 1; break;
5295 case 4: SizeIndex = 2; break;
5296 case 8: SizeIndex = 3; break;
5297 case 16: SizeIndex = 4; break;
5298 default:
5299 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
5300 << FirstArg->getType() << FirstArg->getSourceRange();
5301 return ExprError();
5302 }
5303
5304 // Each of these builtins has one pointer argument, followed by some number of
5305 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5306 // that we ignore. Find out which row of BuiltinIndices to read from as well
5307 // as the number of fixed args.
5308 unsigned BuiltinID = FDecl->getBuiltinID();
5309 unsigned BuiltinIndex, NumFixed = 1;
5310 bool WarnAboutSemanticsChange = false;
5311 switch (BuiltinID) {
5312 default: llvm_unreachable("Unknown overloaded atomic builtin!");
5313 case Builtin::BI__sync_fetch_and_add:
5314 case Builtin::BI__sync_fetch_and_add_1:
5315 case Builtin::BI__sync_fetch_and_add_2:
5316 case Builtin::BI__sync_fetch_and_add_4:
5317 case Builtin::BI__sync_fetch_and_add_8:
5318 case Builtin::BI__sync_fetch_and_add_16:
5319 BuiltinIndex = 0;
5320 break;
5321
5322 case Builtin::BI__sync_fetch_and_sub:
5323 case Builtin::BI__sync_fetch_and_sub_1:
5324 case Builtin::BI__sync_fetch_and_sub_2:
5325 case Builtin::BI__sync_fetch_and_sub_4:
5326 case Builtin::BI__sync_fetch_and_sub_8:
5327 case Builtin::BI__sync_fetch_and_sub_16:
5328 BuiltinIndex = 1;
5329 break;
5330
5331 case Builtin::BI__sync_fetch_and_or:
5332 case Builtin::BI__sync_fetch_and_or_1:
5333 case Builtin::BI__sync_fetch_and_or_2:
5334 case Builtin::BI__sync_fetch_and_or_4:
5335 case Builtin::BI__sync_fetch_and_or_8:
5336 case Builtin::BI__sync_fetch_and_or_16:
5337 BuiltinIndex = 2;
5338 break;
5339
5340 case Builtin::BI__sync_fetch_and_and:
5341 case Builtin::BI__sync_fetch_and_and_1:
5342 case Builtin::BI__sync_fetch_and_and_2:
5343 case Builtin::BI__sync_fetch_and_and_4:
5344 case Builtin::BI__sync_fetch_and_and_8:
5345 case Builtin::BI__sync_fetch_and_and_16:
5346 BuiltinIndex = 3;
5347 break;
5348
5349 case Builtin::BI__sync_fetch_and_xor:
5350 case Builtin::BI__sync_fetch_and_xor_1:
5351 case Builtin::BI__sync_fetch_and_xor_2:
5352 case Builtin::BI__sync_fetch_and_xor_4:
5353 case Builtin::BI__sync_fetch_and_xor_8:
5354 case Builtin::BI__sync_fetch_and_xor_16:
5355 BuiltinIndex = 4;
5356 break;
5357
5358 case Builtin::BI__sync_fetch_and_nand:
5359 case Builtin::BI__sync_fetch_and_nand_1:
5360 case Builtin::BI__sync_fetch_and_nand_2:
5361 case Builtin::BI__sync_fetch_and_nand_4:
5362 case Builtin::BI__sync_fetch_and_nand_8:
5363 case Builtin::BI__sync_fetch_and_nand_16:
5364 BuiltinIndex = 5;
5365 WarnAboutSemanticsChange = true;
5366 break;
5367
5368 case Builtin::BI__sync_add_and_fetch:
5369 case Builtin::BI__sync_add_and_fetch_1:
5370 case Builtin::BI__sync_add_and_fetch_2:
5371 case Builtin::BI__sync_add_and_fetch_4:
5372 case Builtin::BI__sync_add_and_fetch_8:
5373 case Builtin::BI__sync_add_and_fetch_16:
5374 BuiltinIndex = 6;
5375 break;
5376
5377 case Builtin::BI__sync_sub_and_fetch:
5378 case Builtin::BI__sync_sub_and_fetch_1:
5379 case Builtin::BI__sync_sub_and_fetch_2:
5380 case Builtin::BI__sync_sub_and_fetch_4:
5381 case Builtin::BI__sync_sub_and_fetch_8:
5382 case Builtin::BI__sync_sub_and_fetch_16:
5383 BuiltinIndex = 7;
5384 break;
5385
5386 case Builtin::BI__sync_and_and_fetch:
5387 case Builtin::BI__sync_and_and_fetch_1:
5388 case Builtin::BI__sync_and_and_fetch_2:
5389 case Builtin::BI__sync_and_and_fetch_4:
5390 case Builtin::BI__sync_and_and_fetch_8:
5391 case Builtin::BI__sync_and_and_fetch_16:
5392 BuiltinIndex = 8;
5393 break;
5394
5395 case Builtin::BI__sync_or_and_fetch:
5396 case Builtin::BI__sync_or_and_fetch_1:
5397 case Builtin::BI__sync_or_and_fetch_2:
5398 case Builtin::BI__sync_or_and_fetch_4:
5399 case Builtin::BI__sync_or_and_fetch_8:
5400 case Builtin::BI__sync_or_and_fetch_16:
5401 BuiltinIndex = 9;
5402 break;
5403
5404 case Builtin::BI__sync_xor_and_fetch:
5405 case Builtin::BI__sync_xor_and_fetch_1:
5406 case Builtin::BI__sync_xor_and_fetch_2:
5407 case Builtin::BI__sync_xor_and_fetch_4:
5408 case Builtin::BI__sync_xor_and_fetch_8:
5409 case Builtin::BI__sync_xor_and_fetch_16:
5410 BuiltinIndex = 10;
5411 break;
5412
5413 case Builtin::BI__sync_nand_and_fetch:
5414 case Builtin::BI__sync_nand_and_fetch_1:
5415 case Builtin::BI__sync_nand_and_fetch_2:
5416 case Builtin::BI__sync_nand_and_fetch_4:
5417 case Builtin::BI__sync_nand_and_fetch_8:
5418 case Builtin::BI__sync_nand_and_fetch_16:
5419 BuiltinIndex = 11;
5420 WarnAboutSemanticsChange = true;
5421 break;
5422
5423 case Builtin::BI__sync_val_compare_and_swap:
5424 case Builtin::BI__sync_val_compare_and_swap_1:
5425 case Builtin::BI__sync_val_compare_and_swap_2:
5426 case Builtin::BI__sync_val_compare_and_swap_4:
5427 case Builtin::BI__sync_val_compare_and_swap_8:
5428 case Builtin::BI__sync_val_compare_and_swap_16:
5429 BuiltinIndex = 12;
5430 NumFixed = 2;
5431 break;
5432
5433 case Builtin::BI__sync_bool_compare_and_swap:
5434 case Builtin::BI__sync_bool_compare_and_swap_1:
5435 case Builtin::BI__sync_bool_compare_and_swap_2:
5436 case Builtin::BI__sync_bool_compare_and_swap_4:
5437 case Builtin::BI__sync_bool_compare_and_swap_8:
5438 case Builtin::BI__sync_bool_compare_and_swap_16:
5439 BuiltinIndex = 13;
5440 NumFixed = 2;
5441 ResultType = Context.BoolTy;
5442 break;
5443
5444 case Builtin::BI__sync_lock_test_and_set:
5445 case Builtin::BI__sync_lock_test_and_set_1:
5446 case Builtin::BI__sync_lock_test_and_set_2:
5447 case Builtin::BI__sync_lock_test_and_set_4:
5448 case Builtin::BI__sync_lock_test_and_set_8:
5449 case Builtin::BI__sync_lock_test_and_set_16:
5450 BuiltinIndex = 14;
5451 break;
5452
5453 case Builtin::BI__sync_lock_release:
5454 case Builtin::BI__sync_lock_release_1:
5455 case Builtin::BI__sync_lock_release_2:
5456 case Builtin::BI__sync_lock_release_4:
5457 case Builtin::BI__sync_lock_release_8:
5458 case Builtin::BI__sync_lock_release_16:
5459 BuiltinIndex = 15;
5460 NumFixed = 0;
5461 ResultType = Context.VoidTy;
5462 break;
5463
5464 case Builtin::BI__sync_swap:
5465 case Builtin::BI__sync_swap_1:
5466 case Builtin::BI__sync_swap_2:
5467 case Builtin::BI__sync_swap_4:
5468 case Builtin::BI__sync_swap_8:
5469 case Builtin::BI__sync_swap_16:
5470 BuiltinIndex = 16;
5471 break;
5472 }
5473
5474 // Now that we know how many fixed arguments we expect, first check that we
5475 // have at least that many.
5476 if (TheCall->getNumArgs() < 1+NumFixed) {
5477 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5478 << 0 << 1 + NumFixed << TheCall->getNumArgs()
5479 << Callee->getSourceRange();
5480 return ExprError();
5481 }
5482
5483 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
5484 << Callee->getSourceRange();
5485
5486 if (WarnAboutSemanticsChange) {
5487 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
5488 << Callee->getSourceRange();
5489 }
5490
5491 // Get the decl for the concrete builtin from this, we can tell what the
5492 // concrete integer type we should convert to is.
5493 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
5494 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
5495 FunctionDecl *NewBuiltinDecl;
5496 if (NewBuiltinID == BuiltinID)
5497 NewBuiltinDecl = FDecl;
5498 else {
5499 // Perform builtin lookup to avoid redeclaring it.
5500 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
5501 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
5502 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
5503 assert(Res.getFoundDecl());
5504 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
5505 if (!NewBuiltinDecl)
5506 return ExprError();
5507 }
5508
5509 // The first argument --- the pointer --- has a fixed type; we
5510 // deduce the types of the rest of the arguments accordingly. Walk
5511 // the remaining arguments, converting them to the deduced value type.
5512 for (unsigned i = 0; i != NumFixed; ++i) {
5513 ExprResult Arg = TheCall->getArg(i+1);
5514
5515 // GCC does an implicit conversion to the pointer or integer ValType. This
5516 // can fail in some cases (1i -> int**), check for this error case now.
5517 // Initialize the argument.
5518 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5519 ValType, /*consume*/ false);
5520 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5521 if (Arg.isInvalid())
5522 return ExprError();
5523
5524 // Okay, we have something that *can* be converted to the right type. Check
5525 // to see if there is a potentially weird extension going on here. This can
5526 // happen when you do an atomic operation on something like an char* and
5527 // pass in 42. The 42 gets converted to char. This is even more strange
5528 // for things like 45.123 -> char, etc.
5529 // FIXME: Do this check.
5530 TheCall->setArg(i+1, Arg.get());
5531 }
5532
5533 // Create a new DeclRefExpr to refer to the new decl.
5534 DeclRefExpr *NewDRE = DeclRefExpr::Create(
5535 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
5536 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
5537 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
5538
5539 // Set the callee in the CallExpr.
5540 // FIXME: This loses syntactic information.
5541 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
5542 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
5543 CK_BuiltinFnToFnPtr);
5544 TheCall->setCallee(PromotedCall.get());
5545
5546 // Change the result type of the call to match the original value type. This
5547 // is arbitrary, but the codegen for these builtins ins design to handle it
5548 // gracefully.
5549 TheCall->setType(ResultType);
5550
5551 // Prohibit use of _ExtInt with atomic builtins.
5552 // The arguments would have already been converted to the first argument's
5553 // type, so only need to check the first argument.
5554 const auto *ExtIntValType = ValType->getAs<ExtIntType>();
5555 if (ExtIntValType && !llvm::isPowerOf2_64(ExtIntValType->getNumBits())) {
5556 Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
5557 return ExprError();
5558 }
5559
5560 return TheCallResult;
5561 }
5562
5563 /// SemaBuiltinNontemporalOverloaded - We have a call to
5564 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
5565 /// overloaded function based on the pointer type of its last argument.
5566 ///
5567 /// This function goes through and does final semantic checking for these
5568 /// builtins.
SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult)5569 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
5570 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
5571 DeclRefExpr *DRE =
5572 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5573 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5574 unsigned BuiltinID = FDecl->getBuiltinID();
5575 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
5576 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
5577 "Unexpected nontemporal load/store builtin!");
5578 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
5579 unsigned numArgs = isStore ? 2 : 1;
5580
5581 // Ensure that we have the proper number of arguments.
5582 if (checkArgCount(*this, TheCall, numArgs))
5583 return ExprError();
5584
5585 // Inspect the last argument of the nontemporal builtin. This should always
5586 // be a pointer type, from which we imply the type of the memory access.
5587 // Because it is a pointer type, we don't have to worry about any implicit
5588 // casts here.
5589 Expr *PointerArg = TheCall->getArg(numArgs - 1);
5590 ExprResult PointerArgResult =
5591 DefaultFunctionArrayLvalueConversion(PointerArg);
5592
5593 if (PointerArgResult.isInvalid())
5594 return ExprError();
5595 PointerArg = PointerArgResult.get();
5596 TheCall->setArg(numArgs - 1, PointerArg);
5597
5598 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
5599 if (!pointerType) {
5600 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
5601 << PointerArg->getType() << PointerArg->getSourceRange();
5602 return ExprError();
5603 }
5604
5605 QualType ValType = pointerType->getPointeeType();
5606
5607 // Strip any qualifiers off ValType.
5608 ValType = ValType.getUnqualifiedType();
5609 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5610 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
5611 !ValType->isVectorType()) {
5612 Diag(DRE->getBeginLoc(),
5613 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
5614 << PointerArg->getType() << PointerArg->getSourceRange();
5615 return ExprError();
5616 }
5617
5618 if (!isStore) {
5619 TheCall->setType(ValType);
5620 return TheCallResult;
5621 }
5622
5623 ExprResult ValArg = TheCall->getArg(0);
5624 InitializedEntity Entity = InitializedEntity::InitializeParameter(
5625 Context, ValType, /*consume*/ false);
5626 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
5627 if (ValArg.isInvalid())
5628 return ExprError();
5629
5630 TheCall->setArg(0, ValArg.get());
5631 TheCall->setType(Context.VoidTy);
5632 return TheCallResult;
5633 }
5634
5635 /// CheckObjCString - Checks that the argument to the builtin
5636 /// CFString constructor is correct
5637 /// Note: It might also make sense to do the UTF-16 conversion here (would
5638 /// simplify the backend).
CheckObjCString(Expr * Arg)5639 bool Sema::CheckObjCString(Expr *Arg) {
5640 Arg = Arg->IgnoreParenCasts();
5641 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
5642
5643 if (!Literal || !Literal->isAscii()) {
5644 Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
5645 << Arg->getSourceRange();
5646 return true;
5647 }
5648
5649 if (Literal->containsNonAsciiOrNull()) {
5650 StringRef String = Literal->getString();
5651 unsigned NumBytes = String.size();
5652 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
5653 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
5654 llvm::UTF16 *ToPtr = &ToBuf[0];
5655
5656 llvm::ConversionResult Result =
5657 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
5658 ToPtr + NumBytes, llvm::strictConversion);
5659 // Check for conversion failure.
5660 if (Result != llvm::conversionOK)
5661 Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
5662 << Arg->getSourceRange();
5663 }
5664 return false;
5665 }
5666
5667 /// CheckObjCString - Checks that the format string argument to the os_log()
5668 /// and os_trace() functions is correct, and converts it to const char *.
CheckOSLogFormatStringArg(Expr * Arg)5669 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
5670 Arg = Arg->IgnoreParenCasts();
5671 auto *Literal = dyn_cast<StringLiteral>(Arg);
5672 if (!Literal) {
5673 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
5674 Literal = ObjcLiteral->getString();
5675 }
5676 }
5677
5678 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
5679 return ExprError(
5680 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
5681 << Arg->getSourceRange());
5682 }
5683
5684 ExprResult Result(Literal);
5685 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
5686 InitializedEntity Entity =
5687 InitializedEntity::InitializeParameter(Context, ResultTy, false);
5688 Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
5689 return Result;
5690 }
5691
5692 /// Check that the user is calling the appropriate va_start builtin for the
5693 /// target and calling convention.
checkVAStartABI(Sema & S,unsigned BuiltinID,Expr * Fn)5694 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
5695 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
5696 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
5697 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
5698 TT.getArch() == llvm::Triple::aarch64_32);
5699 bool IsWindows = TT.isOSWindows();
5700 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
5701 if (IsX64 || IsAArch64) {
5702 CallingConv CC = CC_C;
5703 if (const FunctionDecl *FD = S.getCurFunctionDecl())
5704 CC = FD->getType()->castAs<FunctionType>()->getCallConv();
5705 if (IsMSVAStart) {
5706 // Don't allow this in System V ABI functions.
5707 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
5708 return S.Diag(Fn->getBeginLoc(),
5709 diag::err_ms_va_start_used_in_sysv_function);
5710 } else {
5711 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
5712 // On x64 Windows, don't allow this in System V ABI functions.
5713 // (Yes, that means there's no corresponding way to support variadic
5714 // System V ABI functions on Windows.)
5715 if ((IsWindows && CC == CC_X86_64SysV) ||
5716 (!IsWindows && CC == CC_Win64))
5717 return S.Diag(Fn->getBeginLoc(),
5718 diag::err_va_start_used_in_wrong_abi_function)
5719 << !IsWindows;
5720 }
5721 return false;
5722 }
5723
5724 if (IsMSVAStart)
5725 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
5726 return false;
5727 }
5728
checkVAStartIsInVariadicFunction(Sema & S,Expr * Fn,ParmVarDecl ** LastParam=nullptr)5729 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
5730 ParmVarDecl **LastParam = nullptr) {
5731 // Determine whether the current function, block, or obj-c method is variadic
5732 // and get its parameter list.
5733 bool IsVariadic = false;
5734 ArrayRef<ParmVarDecl *> Params;
5735 DeclContext *Caller = S.CurContext;
5736 if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
5737 IsVariadic = Block->isVariadic();
5738 Params = Block->parameters();
5739 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
5740 IsVariadic = FD->isVariadic();
5741 Params = FD->parameters();
5742 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
5743 IsVariadic = MD->isVariadic();
5744 // FIXME: This isn't correct for methods (results in bogus warning).
5745 Params = MD->parameters();
5746 } else if (isa<CapturedDecl>(Caller)) {
5747 // We don't support va_start in a CapturedDecl.
5748 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
5749 return true;
5750 } else {
5751 // This must be some other declcontext that parses exprs.
5752 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
5753 return true;
5754 }
5755
5756 if (!IsVariadic) {
5757 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
5758 return true;
5759 }
5760
5761 if (LastParam)
5762 *LastParam = Params.empty() ? nullptr : Params.back();
5763
5764 return false;
5765 }
5766
5767 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
5768 /// for validity. Emit an error and return true on failure; return false
5769 /// on success.
SemaBuiltinVAStart(unsigned BuiltinID,CallExpr * TheCall)5770 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
5771 Expr *Fn = TheCall->getCallee();
5772
5773 if (checkVAStartABI(*this, BuiltinID, Fn))
5774 return true;
5775
5776 if (checkArgCount(*this, TheCall, 2))
5777 return true;
5778
5779 // Type-check the first argument normally.
5780 if (checkBuiltinArgument(*this, TheCall, 0))
5781 return true;
5782
5783 // Check that the current function is variadic, and get its last parameter.
5784 ParmVarDecl *LastParam;
5785 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
5786 return true;
5787
5788 // Verify that the second argument to the builtin is the last argument of the
5789 // current function or method.
5790 bool SecondArgIsLastNamedArgument = false;
5791 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
5792
5793 // These are valid if SecondArgIsLastNamedArgument is false after the next
5794 // block.
5795 QualType Type;
5796 SourceLocation ParamLoc;
5797 bool IsCRegister = false;
5798
5799 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
5800 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
5801 SecondArgIsLastNamedArgument = PV == LastParam;
5802
5803 Type = PV->getType();
5804 ParamLoc = PV->getLocation();
5805 IsCRegister =
5806 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
5807 }
5808 }
5809
5810 if (!SecondArgIsLastNamedArgument)
5811 Diag(TheCall->getArg(1)->getBeginLoc(),
5812 diag::warn_second_arg_of_va_start_not_last_named_param);
5813 else if (IsCRegister || Type->isReferenceType() ||
5814 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
5815 // Promotable integers are UB, but enumerations need a bit of
5816 // extra checking to see what their promotable type actually is.
5817 if (!Type->isPromotableIntegerType())
5818 return false;
5819 if (!Type->isEnumeralType())
5820 return true;
5821 const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
5822 return !(ED &&
5823 Context.typesAreCompatible(ED->getPromotionType(), Type));
5824 }()) {
5825 unsigned Reason = 0;
5826 if (Type->isReferenceType()) Reason = 1;
5827 else if (IsCRegister) Reason = 2;
5828 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
5829 Diag(ParamLoc, diag::note_parameter_type) << Type;
5830 }
5831
5832 TheCall->setType(Context.VoidTy);
5833 return false;
5834 }
5835
SemaBuiltinVAStartARMMicrosoft(CallExpr * Call)5836 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
5837 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
5838 // const char *named_addr);
5839
5840 Expr *Func = Call->getCallee();
5841
5842 if (Call->getNumArgs() < 3)
5843 return Diag(Call->getEndLoc(),
5844 diag::err_typecheck_call_too_few_args_at_least)
5845 << 0 /*function call*/ << 3 << Call->getNumArgs();
5846
5847 // Type-check the first argument normally.
5848 if (checkBuiltinArgument(*this, Call, 0))
5849 return true;
5850
5851 // Check that the current function is variadic.
5852 if (checkVAStartIsInVariadicFunction(*this, Func))
5853 return true;
5854
5855 // __va_start on Windows does not validate the parameter qualifiers
5856
5857 const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
5858 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
5859
5860 const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
5861 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
5862
5863 const QualType &ConstCharPtrTy =
5864 Context.getPointerType(Context.CharTy.withConst());
5865 if (!Arg1Ty->isPointerType() ||
5866 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
5867 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5868 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
5869 << 0 /* qualifier difference */
5870 << 3 /* parameter mismatch */
5871 << 2 << Arg1->getType() << ConstCharPtrTy;
5872
5873 const QualType SizeTy = Context.getSizeType();
5874 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
5875 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5876 << Arg2->getType() << SizeTy << 1 /* different class */
5877 << 0 /* qualifier difference */
5878 << 3 /* parameter mismatch */
5879 << 3 << Arg2->getType() << SizeTy;
5880
5881 return false;
5882 }
5883
5884 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
5885 /// friends. This is declared to take (...), so we have to check everything.
SemaBuiltinUnorderedCompare(CallExpr * TheCall)5886 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
5887 if (checkArgCount(*this, TheCall, 2))
5888 return true;
5889
5890 ExprResult OrigArg0 = TheCall->getArg(0);
5891 ExprResult OrigArg1 = TheCall->getArg(1);
5892
5893 // Do standard promotions between the two arguments, returning their common
5894 // type.
5895 QualType Res = UsualArithmeticConversions(
5896 OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison);
5897 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
5898 return true;
5899
5900 // Make sure any conversions are pushed back into the call; this is
5901 // type safe since unordered compare builtins are declared as "_Bool
5902 // foo(...)".
5903 TheCall->setArg(0, OrigArg0.get());
5904 TheCall->setArg(1, OrigArg1.get());
5905
5906 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
5907 return false;
5908
5909 // If the common type isn't a real floating type, then the arguments were
5910 // invalid for this operation.
5911 if (Res.isNull() || !Res->isRealFloatingType())
5912 return Diag(OrigArg0.get()->getBeginLoc(),
5913 diag::err_typecheck_call_invalid_ordered_compare)
5914 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
5915 << SourceRange(OrigArg0.get()->getBeginLoc(),
5916 OrigArg1.get()->getEndLoc());
5917
5918 return false;
5919 }
5920
5921 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
5922 /// __builtin_isnan and friends. This is declared to take (...), so we have
5923 /// to check everything. We expect the last argument to be a floating point
5924 /// value.
SemaBuiltinFPClassification(CallExpr * TheCall,unsigned NumArgs)5925 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
5926 if (checkArgCount(*this, TheCall, NumArgs))
5927 return true;
5928
5929 // __builtin_fpclassify is the only case where NumArgs != 1, so we can count
5930 // on all preceding parameters just being int. Try all of those.
5931 for (unsigned i = 0; i < NumArgs - 1; ++i) {
5932 Expr *Arg = TheCall->getArg(i);
5933
5934 if (Arg->isTypeDependent())
5935 return false;
5936
5937 ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing);
5938
5939 if (Res.isInvalid())
5940 return true;
5941 TheCall->setArg(i, Res.get());
5942 }
5943
5944 Expr *OrigArg = TheCall->getArg(NumArgs-1);
5945
5946 if (OrigArg->isTypeDependent())
5947 return false;
5948
5949 // Usual Unary Conversions will convert half to float, which we want for
5950 // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
5951 // type how it is, but do normal L->Rvalue conversions.
5952 if (Context.getTargetInfo().useFP16ConversionIntrinsics())
5953 OrigArg = UsualUnaryConversions(OrigArg).get();
5954 else
5955 OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get();
5956 TheCall->setArg(NumArgs - 1, OrigArg);
5957
5958 // This operation requires a non-_Complex floating-point number.
5959 if (!OrigArg->getType()->isRealFloatingType())
5960 return Diag(OrigArg->getBeginLoc(),
5961 diag::err_typecheck_call_invalid_unary_fp)
5962 << OrigArg->getType() << OrigArg->getSourceRange();
5963
5964 return false;
5965 }
5966
5967 /// Perform semantic analysis for a call to __builtin_complex.
SemaBuiltinComplex(CallExpr * TheCall)5968 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) {
5969 if (checkArgCount(*this, TheCall, 2))
5970 return true;
5971
5972 bool Dependent = false;
5973 for (unsigned I = 0; I != 2; ++I) {
5974 Expr *Arg = TheCall->getArg(I);
5975 QualType T = Arg->getType();
5976 if (T->isDependentType()) {
5977 Dependent = true;
5978 continue;
5979 }
5980
5981 // Despite supporting _Complex int, GCC requires a real floating point type
5982 // for the operands of __builtin_complex.
5983 if (!T->isRealFloatingType()) {
5984 return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
5985 << Arg->getType() << Arg->getSourceRange();
5986 }
5987
5988 ExprResult Converted = DefaultLvalueConversion(Arg);
5989 if (Converted.isInvalid())
5990 return true;
5991 TheCall->setArg(I, Converted.get());
5992 }
5993
5994 if (Dependent) {
5995 TheCall->setType(Context.DependentTy);
5996 return false;
5997 }
5998
5999 Expr *Real = TheCall->getArg(0);
6000 Expr *Imag = TheCall->getArg(1);
6001 if (!Context.hasSameType(Real->getType(), Imag->getType())) {
6002 return Diag(Real->getBeginLoc(),
6003 diag::err_typecheck_call_different_arg_types)
6004 << Real->getType() << Imag->getType()
6005 << Real->getSourceRange() << Imag->getSourceRange();
6006 }
6007
6008 // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers;
6009 // don't allow this builtin to form those types either.
6010 // FIXME: Should we allow these types?
6011 if (Real->getType()->isFloat16Type())
6012 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6013 << "_Float16";
6014 if (Real->getType()->isHalfType())
6015 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6016 << "half";
6017
6018 TheCall->setType(Context.getComplexType(Real->getType()));
6019 return false;
6020 }
6021
6022 // Customized Sema Checking for VSX builtins that have the following signature:
6023 // vector [...] builtinName(vector [...], vector [...], const int);
6024 // Which takes the same type of vectors (any legal vector type) for the first
6025 // two arguments and takes compile time constant for the third argument.
6026 // Example builtins are :
6027 // vector double vec_xxpermdi(vector double, vector double, int);
6028 // vector short vec_xxsldwi(vector short, vector short, int);
SemaBuiltinVSX(CallExpr * TheCall)6029 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
6030 unsigned ExpectedNumArgs = 3;
6031 if (checkArgCount(*this, TheCall, ExpectedNumArgs))
6032 return true;
6033
6034 // Check the third argument is a compile time constant
6035 if (!TheCall->getArg(2)->isIntegerConstantExpr(Context))
6036 return Diag(TheCall->getBeginLoc(),
6037 diag::err_vsx_builtin_nonconstant_argument)
6038 << 3 /* argument index */ << TheCall->getDirectCallee()
6039 << SourceRange(TheCall->getArg(2)->getBeginLoc(),
6040 TheCall->getArg(2)->getEndLoc());
6041
6042 QualType Arg1Ty = TheCall->getArg(0)->getType();
6043 QualType Arg2Ty = TheCall->getArg(1)->getType();
6044
6045 // Check the type of argument 1 and argument 2 are vectors.
6046 SourceLocation BuiltinLoc = TheCall->getBeginLoc();
6047 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
6048 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
6049 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
6050 << TheCall->getDirectCallee()
6051 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6052 TheCall->getArg(1)->getEndLoc());
6053 }
6054
6055 // Check the first two arguments are the same type.
6056 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
6057 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
6058 << TheCall->getDirectCallee()
6059 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6060 TheCall->getArg(1)->getEndLoc());
6061 }
6062
6063 // When default clang type checking is turned off and the customized type
6064 // checking is used, the returning type of the function must be explicitly
6065 // set. Otherwise it is _Bool by default.
6066 TheCall->setType(Arg1Ty);
6067
6068 return false;
6069 }
6070
6071 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
6072 // This is declared to take (...), so we have to check everything.
SemaBuiltinShuffleVector(CallExpr * TheCall)6073 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
6074 if (TheCall->getNumArgs() < 2)
6075 return ExprError(Diag(TheCall->getEndLoc(),
6076 diag::err_typecheck_call_too_few_args_at_least)
6077 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
6078 << TheCall->getSourceRange());
6079
6080 // Determine which of the following types of shufflevector we're checking:
6081 // 1) unary, vector mask: (lhs, mask)
6082 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
6083 QualType resType = TheCall->getArg(0)->getType();
6084 unsigned numElements = 0;
6085
6086 if (!TheCall->getArg(0)->isTypeDependent() &&
6087 !TheCall->getArg(1)->isTypeDependent()) {
6088 QualType LHSType = TheCall->getArg(0)->getType();
6089 QualType RHSType = TheCall->getArg(1)->getType();
6090
6091 if (!LHSType->isVectorType() || !RHSType->isVectorType())
6092 return ExprError(
6093 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
6094 << TheCall->getDirectCallee()
6095 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6096 TheCall->getArg(1)->getEndLoc()));
6097
6098 numElements = LHSType->castAs<VectorType>()->getNumElements();
6099 unsigned numResElements = TheCall->getNumArgs() - 2;
6100
6101 // Check to see if we have a call with 2 vector arguments, the unary shuffle
6102 // with mask. If so, verify that RHS is an integer vector type with the
6103 // same number of elts as lhs.
6104 if (TheCall->getNumArgs() == 2) {
6105 if (!RHSType->hasIntegerRepresentation() ||
6106 RHSType->castAs<VectorType>()->getNumElements() != numElements)
6107 return ExprError(Diag(TheCall->getBeginLoc(),
6108 diag::err_vec_builtin_incompatible_vector)
6109 << TheCall->getDirectCallee()
6110 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
6111 TheCall->getArg(1)->getEndLoc()));
6112 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
6113 return ExprError(Diag(TheCall->getBeginLoc(),
6114 diag::err_vec_builtin_incompatible_vector)
6115 << TheCall->getDirectCallee()
6116 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6117 TheCall->getArg(1)->getEndLoc()));
6118 } else if (numElements != numResElements) {
6119 QualType eltType = LHSType->castAs<VectorType>()->getElementType();
6120 resType = Context.getVectorType(eltType, numResElements,
6121 VectorType::GenericVector);
6122 }
6123 }
6124
6125 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
6126 if (TheCall->getArg(i)->isTypeDependent() ||
6127 TheCall->getArg(i)->isValueDependent())
6128 continue;
6129
6130 Optional<llvm::APSInt> Result;
6131 if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context)))
6132 return ExprError(Diag(TheCall->getBeginLoc(),
6133 diag::err_shufflevector_nonconstant_argument)
6134 << TheCall->getArg(i)->getSourceRange());
6135
6136 // Allow -1 which will be translated to undef in the IR.
6137 if (Result->isSigned() && Result->isAllOnesValue())
6138 continue;
6139
6140 if (Result->getActiveBits() > 64 ||
6141 Result->getZExtValue() >= numElements * 2)
6142 return ExprError(Diag(TheCall->getBeginLoc(),
6143 diag::err_shufflevector_argument_too_large)
6144 << TheCall->getArg(i)->getSourceRange());
6145 }
6146
6147 SmallVector<Expr*, 32> exprs;
6148
6149 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
6150 exprs.push_back(TheCall->getArg(i));
6151 TheCall->setArg(i, nullptr);
6152 }
6153
6154 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
6155 TheCall->getCallee()->getBeginLoc(),
6156 TheCall->getRParenLoc());
6157 }
6158
6159 /// SemaConvertVectorExpr - Handle __builtin_convertvector
SemaConvertVectorExpr(Expr * E,TypeSourceInfo * TInfo,SourceLocation BuiltinLoc,SourceLocation RParenLoc)6160 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
6161 SourceLocation BuiltinLoc,
6162 SourceLocation RParenLoc) {
6163 ExprValueKind VK = VK_RValue;
6164 ExprObjectKind OK = OK_Ordinary;
6165 QualType DstTy = TInfo->getType();
6166 QualType SrcTy = E->getType();
6167
6168 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
6169 return ExprError(Diag(BuiltinLoc,
6170 diag::err_convertvector_non_vector)
6171 << E->getSourceRange());
6172 if (!DstTy->isVectorType() && !DstTy->isDependentType())
6173 return ExprError(Diag(BuiltinLoc,
6174 diag::err_convertvector_non_vector_type));
6175
6176 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
6177 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
6178 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
6179 if (SrcElts != DstElts)
6180 return ExprError(Diag(BuiltinLoc,
6181 diag::err_convertvector_incompatible_vector)
6182 << E->getSourceRange());
6183 }
6184
6185 return new (Context)
6186 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
6187 }
6188
6189 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
6190 // This is declared to take (const void*, ...) and can take two
6191 // optional constant int args.
SemaBuiltinPrefetch(CallExpr * TheCall)6192 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
6193 unsigned NumArgs = TheCall->getNumArgs();
6194
6195 if (NumArgs > 3)
6196 return Diag(TheCall->getEndLoc(),
6197 diag::err_typecheck_call_too_many_args_at_most)
6198 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6199
6200 // Argument 0 is checked for us and the remaining arguments must be
6201 // constant integers.
6202 for (unsigned i = 1; i != NumArgs; ++i)
6203 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
6204 return true;
6205
6206 return false;
6207 }
6208
6209 /// SemaBuiltinAssume - Handle __assume (MS Extension).
6210 // __assume does not evaluate its arguments, and should warn if its argument
6211 // has side effects.
SemaBuiltinAssume(CallExpr * TheCall)6212 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
6213 Expr *Arg = TheCall->getArg(0);
6214 if (Arg->isInstantiationDependent()) return false;
6215
6216 if (Arg->HasSideEffects(Context))
6217 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
6218 << Arg->getSourceRange()
6219 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
6220
6221 return false;
6222 }
6223
6224 /// Handle __builtin_alloca_with_align. This is declared
6225 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
6226 /// than 8.
SemaBuiltinAllocaWithAlign(CallExpr * TheCall)6227 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
6228 // The alignment must be a constant integer.
6229 Expr *Arg = TheCall->getArg(1);
6230
6231 // We can't check the value of a dependent argument.
6232 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6233 if (const auto *UE =
6234 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
6235 if (UE->getKind() == UETT_AlignOf ||
6236 UE->getKind() == UETT_PreferredAlignOf)
6237 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
6238 << Arg->getSourceRange();
6239
6240 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
6241
6242 if (!Result.isPowerOf2())
6243 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6244 << Arg->getSourceRange();
6245
6246 if (Result < Context.getCharWidth())
6247 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
6248 << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
6249
6250 if (Result > std::numeric_limits<int32_t>::max())
6251 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
6252 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
6253 }
6254
6255 return false;
6256 }
6257
6258 /// Handle __builtin_assume_aligned. This is declared
6259 /// as (const void*, size_t, ...) and can take one optional constant int arg.
SemaBuiltinAssumeAligned(CallExpr * TheCall)6260 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
6261 unsigned NumArgs = TheCall->getNumArgs();
6262
6263 if (NumArgs > 3)
6264 return Diag(TheCall->getEndLoc(),
6265 diag::err_typecheck_call_too_many_args_at_most)
6266 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6267
6268 // The alignment must be a constant integer.
6269 Expr *Arg = TheCall->getArg(1);
6270
6271 // We can't check the value of a dependent argument.
6272 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6273 llvm::APSInt Result;
6274 if (SemaBuiltinConstantArg(TheCall, 1, Result))
6275 return true;
6276
6277 if (!Result.isPowerOf2())
6278 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6279 << Arg->getSourceRange();
6280
6281 if (Result > Sema::MaximumAlignment)
6282 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
6283 << Arg->getSourceRange() << Sema::MaximumAlignment;
6284 }
6285
6286 if (NumArgs > 2) {
6287 ExprResult Arg(TheCall->getArg(2));
6288 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6289 Context.getSizeType(), false);
6290 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6291 if (Arg.isInvalid()) return true;
6292 TheCall->setArg(2, Arg.get());
6293 }
6294
6295 return false;
6296 }
6297
SemaBuiltinOSLogFormat(CallExpr * TheCall)6298 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
6299 unsigned BuiltinID =
6300 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
6301 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
6302
6303 unsigned NumArgs = TheCall->getNumArgs();
6304 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
6305 if (NumArgs < NumRequiredArgs) {
6306 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
6307 << 0 /* function call */ << NumRequiredArgs << NumArgs
6308 << TheCall->getSourceRange();
6309 }
6310 if (NumArgs >= NumRequiredArgs + 0x100) {
6311 return Diag(TheCall->getEndLoc(),
6312 diag::err_typecheck_call_too_many_args_at_most)
6313 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
6314 << TheCall->getSourceRange();
6315 }
6316 unsigned i = 0;
6317
6318 // For formatting call, check buffer arg.
6319 if (!IsSizeCall) {
6320 ExprResult Arg(TheCall->getArg(i));
6321 InitializedEntity Entity = InitializedEntity::InitializeParameter(
6322 Context, Context.VoidPtrTy, false);
6323 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6324 if (Arg.isInvalid())
6325 return true;
6326 TheCall->setArg(i, Arg.get());
6327 i++;
6328 }
6329
6330 // Check string literal arg.
6331 unsigned FormatIdx = i;
6332 {
6333 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
6334 if (Arg.isInvalid())
6335 return true;
6336 TheCall->setArg(i, Arg.get());
6337 i++;
6338 }
6339
6340 // Make sure variadic args are scalar.
6341 unsigned FirstDataArg = i;
6342 while (i < NumArgs) {
6343 ExprResult Arg = DefaultVariadicArgumentPromotion(
6344 TheCall->getArg(i), VariadicFunction, nullptr);
6345 if (Arg.isInvalid())
6346 return true;
6347 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
6348 if (ArgSize.getQuantity() >= 0x100) {
6349 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
6350 << i << (int)ArgSize.getQuantity() << 0xff
6351 << TheCall->getSourceRange();
6352 }
6353 TheCall->setArg(i, Arg.get());
6354 i++;
6355 }
6356
6357 // Check formatting specifiers. NOTE: We're only doing this for the non-size
6358 // call to avoid duplicate diagnostics.
6359 if (!IsSizeCall) {
6360 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6361 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6362 bool Success = CheckFormatArguments(
6363 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
6364 VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
6365 CheckedVarArgs);
6366 if (!Success)
6367 return true;
6368 }
6369
6370 if (IsSizeCall) {
6371 TheCall->setType(Context.getSizeType());
6372 } else {
6373 TheCall->setType(Context.VoidPtrTy);
6374 }
6375 return false;
6376 }
6377
6378 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
6379 /// TheCall is a constant expression.
SemaBuiltinConstantArg(CallExpr * TheCall,int ArgNum,llvm::APSInt & Result)6380 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
6381 llvm::APSInt &Result) {
6382 Expr *Arg = TheCall->getArg(ArgNum);
6383 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6384 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6385
6386 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
6387
6388 Optional<llvm::APSInt> R;
6389 if (!(R = Arg->getIntegerConstantExpr(Context)))
6390 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
6391 << FDecl->getDeclName() << Arg->getSourceRange();
6392 Result = *R;
6393 return false;
6394 }
6395
6396 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
6397 /// TheCall is a constant expression in the range [Low, High].
SemaBuiltinConstantArgRange(CallExpr * TheCall,int ArgNum,int Low,int High,bool RangeIsError)6398 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
6399 int Low, int High, bool RangeIsError) {
6400 if (isConstantEvaluated())
6401 return false;
6402 llvm::APSInt Result;
6403
6404 // We can't check the value of a dependent argument.
6405 Expr *Arg = TheCall->getArg(ArgNum);
6406 if (Arg->isTypeDependent() || Arg->isValueDependent())
6407 return false;
6408
6409 // Check constant-ness first.
6410 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6411 return true;
6412
6413 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6414 if (RangeIsError)
6415 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
6416 << Result.toString(10) << Low << High << Arg->getSourceRange();
6417 else
6418 // Defer the warning until we know if the code will be emitted so that
6419 // dead code can ignore this.
6420 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
6421 PDiag(diag::warn_argument_invalid_range)
6422 << Result.toString(10) << Low << High
6423 << Arg->getSourceRange());
6424 }
6425
6426 return false;
6427 }
6428
6429 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
6430 /// TheCall is a constant expression is a multiple of Num..
SemaBuiltinConstantArgMultiple(CallExpr * TheCall,int ArgNum,unsigned Num)6431 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
6432 unsigned Num) {
6433 llvm::APSInt Result;
6434
6435 // We can't check the value of a dependent argument.
6436 Expr *Arg = TheCall->getArg(ArgNum);
6437 if (Arg->isTypeDependent() || Arg->isValueDependent())
6438 return false;
6439
6440 // Check constant-ness first.
6441 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6442 return true;
6443
6444 if (Result.getSExtValue() % Num != 0)
6445 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
6446 << Num << Arg->getSourceRange();
6447
6448 return false;
6449 }
6450
6451 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
6452 /// constant expression representing a power of 2.
SemaBuiltinConstantArgPower2(CallExpr * TheCall,int ArgNum)6453 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
6454 llvm::APSInt Result;
6455
6456 // We can't check the value of a dependent argument.
6457 Expr *Arg = TheCall->getArg(ArgNum);
6458 if (Arg->isTypeDependent() || Arg->isValueDependent())
6459 return false;
6460
6461 // Check constant-ness first.
6462 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6463 return true;
6464
6465 // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
6466 // and only if x is a power of 2.
6467 if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
6468 return false;
6469
6470 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
6471 << Arg->getSourceRange();
6472 }
6473
IsShiftedByte(llvm::APSInt Value)6474 static bool IsShiftedByte(llvm::APSInt Value) {
6475 if (Value.isNegative())
6476 return false;
6477
6478 // Check if it's a shifted byte, by shifting it down
6479 while (true) {
6480 // If the value fits in the bottom byte, the check passes.
6481 if (Value < 0x100)
6482 return true;
6483
6484 // Otherwise, if the value has _any_ bits in the bottom byte, the check
6485 // fails.
6486 if ((Value & 0xFF) != 0)
6487 return false;
6488
6489 // If the bottom 8 bits are all 0, but something above that is nonzero,
6490 // then shifting the value right by 8 bits won't affect whether it's a
6491 // shifted byte or not. So do that, and go round again.
6492 Value >>= 8;
6493 }
6494 }
6495
6496 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
6497 /// a constant expression representing an arbitrary byte value shifted left by
6498 /// a multiple of 8 bits.
SemaBuiltinConstantArgShiftedByte(CallExpr * TheCall,int ArgNum,unsigned ArgBits)6499 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
6500 unsigned ArgBits) {
6501 llvm::APSInt Result;
6502
6503 // We can't check the value of a dependent argument.
6504 Expr *Arg = TheCall->getArg(ArgNum);
6505 if (Arg->isTypeDependent() || Arg->isValueDependent())
6506 return false;
6507
6508 // Check constant-ness first.
6509 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6510 return true;
6511
6512 // Truncate to the given size.
6513 Result = Result.getLoBits(ArgBits);
6514 Result.setIsUnsigned(true);
6515
6516 if (IsShiftedByte(Result))
6517 return false;
6518
6519 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
6520 << Arg->getSourceRange();
6521 }
6522
6523 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
6524 /// TheCall is a constant expression representing either a shifted byte value,
6525 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
6526 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
6527 /// Arm MVE intrinsics.
SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr * TheCall,int ArgNum,unsigned ArgBits)6528 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
6529 int ArgNum,
6530 unsigned ArgBits) {
6531 llvm::APSInt Result;
6532
6533 // We can't check the value of a dependent argument.
6534 Expr *Arg = TheCall->getArg(ArgNum);
6535 if (Arg->isTypeDependent() || Arg->isValueDependent())
6536 return false;
6537
6538 // Check constant-ness first.
6539 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6540 return true;
6541
6542 // Truncate to the given size.
6543 Result = Result.getLoBits(ArgBits);
6544 Result.setIsUnsigned(true);
6545
6546 // Check to see if it's in either of the required forms.
6547 if (IsShiftedByte(Result) ||
6548 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
6549 return false;
6550
6551 return Diag(TheCall->getBeginLoc(),
6552 diag::err_argument_not_shifted_byte_or_xxff)
6553 << Arg->getSourceRange();
6554 }
6555
6556 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID,CallExpr * TheCall)6557 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
6558 if (BuiltinID == AArch64::BI__builtin_arm_irg) {
6559 if (checkArgCount(*this, TheCall, 2))
6560 return true;
6561 Expr *Arg0 = TheCall->getArg(0);
6562 Expr *Arg1 = TheCall->getArg(1);
6563
6564 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6565 if (FirstArg.isInvalid())
6566 return true;
6567 QualType FirstArgType = FirstArg.get()->getType();
6568 if (!FirstArgType->isAnyPointerType())
6569 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6570 << "first" << FirstArgType << Arg0->getSourceRange();
6571 TheCall->setArg(0, FirstArg.get());
6572
6573 ExprResult SecArg = DefaultLvalueConversion(Arg1);
6574 if (SecArg.isInvalid())
6575 return true;
6576 QualType SecArgType = SecArg.get()->getType();
6577 if (!SecArgType->isIntegerType())
6578 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6579 << "second" << SecArgType << Arg1->getSourceRange();
6580
6581 // Derive the return type from the pointer argument.
6582 TheCall->setType(FirstArgType);
6583 return false;
6584 }
6585
6586 if (BuiltinID == AArch64::BI__builtin_arm_addg) {
6587 if (checkArgCount(*this, TheCall, 2))
6588 return true;
6589
6590 Expr *Arg0 = TheCall->getArg(0);
6591 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6592 if (FirstArg.isInvalid())
6593 return true;
6594 QualType FirstArgType = FirstArg.get()->getType();
6595 if (!FirstArgType->isAnyPointerType())
6596 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6597 << "first" << FirstArgType << Arg0->getSourceRange();
6598 TheCall->setArg(0, FirstArg.get());
6599
6600 // Derive the return type from the pointer argument.
6601 TheCall->setType(FirstArgType);
6602
6603 // Second arg must be an constant in range [0,15]
6604 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6605 }
6606
6607 if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
6608 if (checkArgCount(*this, TheCall, 2))
6609 return true;
6610 Expr *Arg0 = TheCall->getArg(0);
6611 Expr *Arg1 = TheCall->getArg(1);
6612
6613 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6614 if (FirstArg.isInvalid())
6615 return true;
6616 QualType FirstArgType = FirstArg.get()->getType();
6617 if (!FirstArgType->isAnyPointerType())
6618 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6619 << "first" << FirstArgType << Arg0->getSourceRange();
6620
6621 QualType SecArgType = Arg1->getType();
6622 if (!SecArgType->isIntegerType())
6623 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6624 << "second" << SecArgType << Arg1->getSourceRange();
6625 TheCall->setType(Context.IntTy);
6626 return false;
6627 }
6628
6629 if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
6630 BuiltinID == AArch64::BI__builtin_arm_stg) {
6631 if (checkArgCount(*this, TheCall, 1))
6632 return true;
6633 Expr *Arg0 = TheCall->getArg(0);
6634 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6635 if (FirstArg.isInvalid())
6636 return true;
6637
6638 QualType FirstArgType = FirstArg.get()->getType();
6639 if (!FirstArgType->isAnyPointerType())
6640 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6641 << "first" << FirstArgType << Arg0->getSourceRange();
6642 TheCall->setArg(0, FirstArg.get());
6643
6644 // Derive the return type from the pointer argument.
6645 if (BuiltinID == AArch64::BI__builtin_arm_ldg)
6646 TheCall->setType(FirstArgType);
6647 return false;
6648 }
6649
6650 if (BuiltinID == AArch64::BI__builtin_arm_subp) {
6651 Expr *ArgA = TheCall->getArg(0);
6652 Expr *ArgB = TheCall->getArg(1);
6653
6654 ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
6655 ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
6656
6657 if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
6658 return true;
6659
6660 QualType ArgTypeA = ArgExprA.get()->getType();
6661 QualType ArgTypeB = ArgExprB.get()->getType();
6662
6663 auto isNull = [&] (Expr *E) -> bool {
6664 return E->isNullPointerConstant(
6665 Context, Expr::NPC_ValueDependentIsNotNull); };
6666
6667 // argument should be either a pointer or null
6668 if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
6669 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6670 << "first" << ArgTypeA << ArgA->getSourceRange();
6671
6672 if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
6673 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6674 << "second" << ArgTypeB << ArgB->getSourceRange();
6675
6676 // Ensure Pointee types are compatible
6677 if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
6678 ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
6679 QualType pointeeA = ArgTypeA->getPointeeType();
6680 QualType pointeeB = ArgTypeB->getPointeeType();
6681 if (!Context.typesAreCompatible(
6682 Context.getCanonicalType(pointeeA).getUnqualifiedType(),
6683 Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
6684 return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
6685 << ArgTypeA << ArgTypeB << ArgA->getSourceRange()
6686 << ArgB->getSourceRange();
6687 }
6688 }
6689
6690 // at least one argument should be pointer type
6691 if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
6692 return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
6693 << ArgTypeA << ArgTypeB << ArgA->getSourceRange();
6694
6695 if (isNull(ArgA)) // adopt type of the other pointer
6696 ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
6697
6698 if (isNull(ArgB))
6699 ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
6700
6701 TheCall->setArg(0, ArgExprA.get());
6702 TheCall->setArg(1, ArgExprB.get());
6703 TheCall->setType(Context.LongLongTy);
6704 return false;
6705 }
6706 assert(false && "Unhandled ARM MTE intrinsic");
6707 return true;
6708 }
6709
6710 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
6711 /// TheCall is an ARM/AArch64 special register string literal.
SemaBuiltinARMSpecialReg(unsigned BuiltinID,CallExpr * TheCall,int ArgNum,unsigned ExpectedFieldNum,bool AllowName)6712 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
6713 int ArgNum, unsigned ExpectedFieldNum,
6714 bool AllowName) {
6715 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
6716 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
6717 BuiltinID == ARM::BI__builtin_arm_rsr ||
6718 BuiltinID == ARM::BI__builtin_arm_rsrp ||
6719 BuiltinID == ARM::BI__builtin_arm_wsr ||
6720 BuiltinID == ARM::BI__builtin_arm_wsrp;
6721 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
6722 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
6723 BuiltinID == AArch64::BI__builtin_arm_rsr ||
6724 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
6725 BuiltinID == AArch64::BI__builtin_arm_wsr ||
6726 BuiltinID == AArch64::BI__builtin_arm_wsrp;
6727 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
6728
6729 // We can't check the value of a dependent argument.
6730 Expr *Arg = TheCall->getArg(ArgNum);
6731 if (Arg->isTypeDependent() || Arg->isValueDependent())
6732 return false;
6733
6734 // Check if the argument is a string literal.
6735 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
6736 return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
6737 << Arg->getSourceRange();
6738
6739 // Check the type of special register given.
6740 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
6741 SmallVector<StringRef, 6> Fields;
6742 Reg.split(Fields, ":");
6743
6744 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
6745 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6746 << Arg->getSourceRange();
6747
6748 // If the string is the name of a register then we cannot check that it is
6749 // valid here but if the string is of one the forms described in ACLE then we
6750 // can check that the supplied fields are integers and within the valid
6751 // ranges.
6752 if (Fields.size() > 1) {
6753 bool FiveFields = Fields.size() == 5;
6754
6755 bool ValidString = true;
6756 if (IsARMBuiltin) {
6757 ValidString &= Fields[0].startswith_lower("cp") ||
6758 Fields[0].startswith_lower("p");
6759 if (ValidString)
6760 Fields[0] =
6761 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
6762
6763 ValidString &= Fields[2].startswith_lower("c");
6764 if (ValidString)
6765 Fields[2] = Fields[2].drop_front(1);
6766
6767 if (FiveFields) {
6768 ValidString &= Fields[3].startswith_lower("c");
6769 if (ValidString)
6770 Fields[3] = Fields[3].drop_front(1);
6771 }
6772 }
6773
6774 SmallVector<int, 5> Ranges;
6775 if (FiveFields)
6776 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
6777 else
6778 Ranges.append({15, 7, 15});
6779
6780 for (unsigned i=0; i<Fields.size(); ++i) {
6781 int IntField;
6782 ValidString &= !Fields[i].getAsInteger(10, IntField);
6783 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
6784 }
6785
6786 if (!ValidString)
6787 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6788 << Arg->getSourceRange();
6789 } else if (IsAArch64Builtin && Fields.size() == 1) {
6790 // If the register name is one of those that appear in the condition below
6791 // and the special register builtin being used is one of the write builtins,
6792 // then we require that the argument provided for writing to the register
6793 // is an integer constant expression. This is because it will be lowered to
6794 // an MSR (immediate) instruction, so we need to know the immediate at
6795 // compile time.
6796 if (TheCall->getNumArgs() != 2)
6797 return false;
6798
6799 std::string RegLower = Reg.lower();
6800 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
6801 RegLower != "pan" && RegLower != "uao")
6802 return false;
6803
6804 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6805 }
6806
6807 return false;
6808 }
6809
6810 /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity.
6811 /// Emit an error and return true on failure; return false on success.
6812 /// TypeStr is a string containing the type descriptor of the value returned by
6813 /// the builtin and the descriptors of the expected type of the arguments.
SemaBuiltinPPCMMACall(CallExpr * TheCall,const char * TypeStr)6814 bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, const char *TypeStr) {
6815
6816 assert((TypeStr[0] != '\0') &&
6817 "Invalid types in PPC MMA builtin declaration");
6818
6819 unsigned Mask = 0;
6820 unsigned ArgNum = 0;
6821
6822 // The first type in TypeStr is the type of the value returned by the
6823 // builtin. So we first read that type and change the type of TheCall.
6824 QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
6825 TheCall->setType(type);
6826
6827 while (*TypeStr != '\0') {
6828 Mask = 0;
6829 QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
6830 if (ArgNum >= TheCall->getNumArgs()) {
6831 ArgNum++;
6832 break;
6833 }
6834
6835 Expr *Arg = TheCall->getArg(ArgNum);
6836 QualType ArgType = Arg->getType();
6837
6838 if ((ExpectedType->isVoidPointerType() && !ArgType->isPointerType()) ||
6839 (!ExpectedType->isVoidPointerType() &&
6840 ArgType.getCanonicalType() != ExpectedType))
6841 return Diag(Arg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6842 << ArgType << ExpectedType << 1 << 0 << 0;
6843
6844 // If the value of the Mask is not 0, we have a constraint in the size of
6845 // the integer argument so here we ensure the argument is a constant that
6846 // is in the valid range.
6847 if (Mask != 0 &&
6848 SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true))
6849 return true;
6850
6851 ArgNum++;
6852 }
6853
6854 // In case we exited early from the previous loop, there are other types to
6855 // read from TypeStr. So we need to read them all to ensure we have the right
6856 // number of arguments in TheCall and if it is not the case, to display a
6857 // better error message.
6858 while (*TypeStr != '\0') {
6859 (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
6860 ArgNum++;
6861 }
6862 if (checkArgCount(*this, TheCall, ArgNum))
6863 return true;
6864
6865 return false;
6866 }
6867
6868 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
6869 /// This checks that the target supports __builtin_longjmp and
6870 /// that val is a constant 1.
SemaBuiltinLongjmp(CallExpr * TheCall)6871 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
6872 if (!Context.getTargetInfo().hasSjLjLowering())
6873 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
6874 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6875
6876 Expr *Arg = TheCall->getArg(1);
6877 llvm::APSInt Result;
6878
6879 // TODO: This is less than ideal. Overload this to take a value.
6880 if (SemaBuiltinConstantArg(TheCall, 1, Result))
6881 return true;
6882
6883 if (Result != 1)
6884 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
6885 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
6886
6887 return false;
6888 }
6889
6890 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
6891 /// This checks that the target supports __builtin_setjmp.
SemaBuiltinSetjmp(CallExpr * TheCall)6892 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
6893 if (!Context.getTargetInfo().hasSjLjLowering())
6894 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
6895 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6896 return false;
6897 }
6898
6899 namespace {
6900
6901 class UncoveredArgHandler {
6902 enum { Unknown = -1, AllCovered = -2 };
6903
6904 signed FirstUncoveredArg = Unknown;
6905 SmallVector<const Expr *, 4> DiagnosticExprs;
6906
6907 public:
6908 UncoveredArgHandler() = default;
6909
hasUncoveredArg() const6910 bool hasUncoveredArg() const {
6911 return (FirstUncoveredArg >= 0);
6912 }
6913
getUncoveredArg() const6914 unsigned getUncoveredArg() const {
6915 assert(hasUncoveredArg() && "no uncovered argument");
6916 return FirstUncoveredArg;
6917 }
6918
setAllCovered()6919 void setAllCovered() {
6920 // A string has been found with all arguments covered, so clear out
6921 // the diagnostics.
6922 DiagnosticExprs.clear();
6923 FirstUncoveredArg = AllCovered;
6924 }
6925
Update(signed NewFirstUncoveredArg,const Expr * StrExpr)6926 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
6927 assert(NewFirstUncoveredArg >= 0 && "Outside range");
6928
6929 // Don't update if a previous string covers all arguments.
6930 if (FirstUncoveredArg == AllCovered)
6931 return;
6932
6933 // UncoveredArgHandler tracks the highest uncovered argument index
6934 // and with it all the strings that match this index.
6935 if (NewFirstUncoveredArg == FirstUncoveredArg)
6936 DiagnosticExprs.push_back(StrExpr);
6937 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
6938 DiagnosticExprs.clear();
6939 DiagnosticExprs.push_back(StrExpr);
6940 FirstUncoveredArg = NewFirstUncoveredArg;
6941 }
6942 }
6943
6944 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
6945 };
6946
6947 enum StringLiteralCheckType {
6948 SLCT_NotALiteral,
6949 SLCT_UncheckedLiteral,
6950 SLCT_CheckedLiteral
6951 };
6952
6953 } // namespace
6954
sumOffsets(llvm::APSInt & Offset,llvm::APSInt Addend,BinaryOperatorKind BinOpKind,bool AddendIsRight)6955 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
6956 BinaryOperatorKind BinOpKind,
6957 bool AddendIsRight) {
6958 unsigned BitWidth = Offset.getBitWidth();
6959 unsigned AddendBitWidth = Addend.getBitWidth();
6960 // There might be negative interim results.
6961 if (Addend.isUnsigned()) {
6962 Addend = Addend.zext(++AddendBitWidth);
6963 Addend.setIsSigned(true);
6964 }
6965 // Adjust the bit width of the APSInts.
6966 if (AddendBitWidth > BitWidth) {
6967 Offset = Offset.sext(AddendBitWidth);
6968 BitWidth = AddendBitWidth;
6969 } else if (BitWidth > AddendBitWidth) {
6970 Addend = Addend.sext(BitWidth);
6971 }
6972
6973 bool Ov = false;
6974 llvm::APSInt ResOffset = Offset;
6975 if (BinOpKind == BO_Add)
6976 ResOffset = Offset.sadd_ov(Addend, Ov);
6977 else {
6978 assert(AddendIsRight && BinOpKind == BO_Sub &&
6979 "operator must be add or sub with addend on the right");
6980 ResOffset = Offset.ssub_ov(Addend, Ov);
6981 }
6982
6983 // We add an offset to a pointer here so we should support an offset as big as
6984 // possible.
6985 if (Ov) {
6986 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
6987 "index (intermediate) result too big");
6988 Offset = Offset.sext(2 * BitWidth);
6989 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
6990 return;
6991 }
6992
6993 Offset = ResOffset;
6994 }
6995
6996 namespace {
6997
6998 // This is a wrapper class around StringLiteral to support offsetted string
6999 // literals as format strings. It takes the offset into account when returning
7000 // the string and its length or the source locations to display notes correctly.
7001 class FormatStringLiteral {
7002 const StringLiteral *FExpr;
7003 int64_t Offset;
7004
7005 public:
FormatStringLiteral(const StringLiteral * fexpr,int64_t Offset=0)7006 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
7007 : FExpr(fexpr), Offset(Offset) {}
7008
getString() const7009 StringRef getString() const {
7010 return FExpr->getString().drop_front(Offset);
7011 }
7012
getByteLength() const7013 unsigned getByteLength() const {
7014 return FExpr->getByteLength() - getCharByteWidth() * Offset;
7015 }
7016
getLength() const7017 unsigned getLength() const { return FExpr->getLength() - Offset; }
getCharByteWidth() const7018 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
7019
getKind() const7020 StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
7021
getType() const7022 QualType getType() const { return FExpr->getType(); }
7023
isAscii() const7024 bool isAscii() const { return FExpr->isAscii(); }
isWide() const7025 bool isWide() const { return FExpr->isWide(); }
isUTF8() const7026 bool isUTF8() const { return FExpr->isUTF8(); }
isUTF16() const7027 bool isUTF16() const { return FExpr->isUTF16(); }
isUTF32() const7028 bool isUTF32() const { return FExpr->isUTF32(); }
isPascal() const7029 bool isPascal() const { return FExpr->isPascal(); }
7030
getLocationOfByte(unsigned ByteNo,const SourceManager & SM,const LangOptions & Features,const TargetInfo & Target,unsigned * StartToken=nullptr,unsigned * StartTokenByteOffset=nullptr) const7031 SourceLocation getLocationOfByte(
7032 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
7033 const TargetInfo &Target, unsigned *StartToken = nullptr,
7034 unsigned *StartTokenByteOffset = nullptr) const {
7035 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
7036 StartToken, StartTokenByteOffset);
7037 }
7038
getBeginLoc() const7039 SourceLocation getBeginLoc() const LLVM_READONLY {
7040 return FExpr->getBeginLoc().getLocWithOffset(Offset);
7041 }
7042
getEndLoc() const7043 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
7044 };
7045
7046 } // namespace
7047
7048 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
7049 const Expr *OrigFormatExpr,
7050 ArrayRef<const Expr *> Args,
7051 bool HasVAListArg, unsigned format_idx,
7052 unsigned firstDataArg,
7053 Sema::FormatStringType Type,
7054 bool inFunctionCall,
7055 Sema::VariadicCallType CallType,
7056 llvm::SmallBitVector &CheckedVarArgs,
7057 UncoveredArgHandler &UncoveredArg,
7058 bool IgnoreStringsWithoutSpecifiers);
7059
7060 // Determine if an expression is a string literal or constant string.
7061 // If this function returns false on the arguments to a function expecting a
7062 // format string, we will usually need to emit a warning.
7063 // True string literals are then checked by CheckFormatString.
7064 static StringLiteralCheckType
checkFormatStringExpr(Sema & S,const Expr * E,ArrayRef<const Expr * > Args,bool HasVAListArg,unsigned format_idx,unsigned firstDataArg,Sema::FormatStringType Type,Sema::VariadicCallType CallType,bool InFunctionCall,llvm::SmallBitVector & CheckedVarArgs,UncoveredArgHandler & UncoveredArg,llvm::APSInt Offset,bool IgnoreStringsWithoutSpecifiers=false)7065 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
7066 bool HasVAListArg, unsigned format_idx,
7067 unsigned firstDataArg, Sema::FormatStringType Type,
7068 Sema::VariadicCallType CallType, bool InFunctionCall,
7069 llvm::SmallBitVector &CheckedVarArgs,
7070 UncoveredArgHandler &UncoveredArg,
7071 llvm::APSInt Offset,
7072 bool IgnoreStringsWithoutSpecifiers = false) {
7073 if (S.isConstantEvaluated())
7074 return SLCT_NotALiteral;
7075 tryAgain:
7076 assert(Offset.isSigned() && "invalid offset");
7077
7078 if (E->isTypeDependent() || E->isValueDependent())
7079 return SLCT_NotALiteral;
7080
7081 E = E->IgnoreParenCasts();
7082
7083 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
7084 // Technically -Wformat-nonliteral does not warn about this case.
7085 // The behavior of printf and friends in this case is implementation
7086 // dependent. Ideally if the format string cannot be null then
7087 // it should have a 'nonnull' attribute in the function prototype.
7088 return SLCT_UncheckedLiteral;
7089
7090 switch (E->getStmtClass()) {
7091 case Stmt::BinaryConditionalOperatorClass:
7092 case Stmt::ConditionalOperatorClass: {
7093 // The expression is a literal if both sub-expressions were, and it was
7094 // completely checked only if both sub-expressions were checked.
7095 const AbstractConditionalOperator *C =
7096 cast<AbstractConditionalOperator>(E);
7097
7098 // Determine whether it is necessary to check both sub-expressions, for
7099 // example, because the condition expression is a constant that can be
7100 // evaluated at compile time.
7101 bool CheckLeft = true, CheckRight = true;
7102
7103 bool Cond;
7104 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
7105 S.isConstantEvaluated())) {
7106 if (Cond)
7107 CheckRight = false;
7108 else
7109 CheckLeft = false;
7110 }
7111
7112 // We need to maintain the offsets for the right and the left hand side
7113 // separately to check if every possible indexed expression is a valid
7114 // string literal. They might have different offsets for different string
7115 // literals in the end.
7116 StringLiteralCheckType Left;
7117 if (!CheckLeft)
7118 Left = SLCT_UncheckedLiteral;
7119 else {
7120 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
7121 HasVAListArg, format_idx, firstDataArg,
7122 Type, CallType, InFunctionCall,
7123 CheckedVarArgs, UncoveredArg, Offset,
7124 IgnoreStringsWithoutSpecifiers);
7125 if (Left == SLCT_NotALiteral || !CheckRight) {
7126 return Left;
7127 }
7128 }
7129
7130 StringLiteralCheckType Right = checkFormatStringExpr(
7131 S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg,
7132 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7133 IgnoreStringsWithoutSpecifiers);
7134
7135 return (CheckLeft && Left < Right) ? Left : Right;
7136 }
7137
7138 case Stmt::ImplicitCastExprClass:
7139 E = cast<ImplicitCastExpr>(E)->getSubExpr();
7140 goto tryAgain;
7141
7142 case Stmt::OpaqueValueExprClass:
7143 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
7144 E = src;
7145 goto tryAgain;
7146 }
7147 return SLCT_NotALiteral;
7148
7149 case Stmt::PredefinedExprClass:
7150 // While __func__, etc., are technically not string literals, they
7151 // cannot contain format specifiers and thus are not a security
7152 // liability.
7153 return SLCT_UncheckedLiteral;
7154
7155 case Stmt::DeclRefExprClass: {
7156 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7157
7158 // As an exception, do not flag errors for variables binding to
7159 // const string literals.
7160 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
7161 bool isConstant = false;
7162 QualType T = DR->getType();
7163
7164 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
7165 isConstant = AT->getElementType().isConstant(S.Context);
7166 } else if (const PointerType *PT = T->getAs<PointerType>()) {
7167 isConstant = T.isConstant(S.Context) &&
7168 PT->getPointeeType().isConstant(S.Context);
7169 } else if (T->isObjCObjectPointerType()) {
7170 // In ObjC, there is usually no "const ObjectPointer" type,
7171 // so don't check if the pointee type is constant.
7172 isConstant = T.isConstant(S.Context);
7173 }
7174
7175 if (isConstant) {
7176 if (const Expr *Init = VD->getAnyInitializer()) {
7177 // Look through initializers like const char c[] = { "foo" }
7178 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
7179 if (InitList->isStringLiteralInit())
7180 Init = InitList->getInit(0)->IgnoreParenImpCasts();
7181 }
7182 return checkFormatStringExpr(S, Init, Args,
7183 HasVAListArg, format_idx,
7184 firstDataArg, Type, CallType,
7185 /*InFunctionCall*/ false, CheckedVarArgs,
7186 UncoveredArg, Offset);
7187 }
7188 }
7189
7190 // For vprintf* functions (i.e., HasVAListArg==true), we add a
7191 // special check to see if the format string is a function parameter
7192 // of the function calling the printf function. If the function
7193 // has an attribute indicating it is a printf-like function, then we
7194 // should suppress warnings concerning non-literals being used in a call
7195 // to a vprintf function. For example:
7196 //
7197 // void
7198 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
7199 // va_list ap;
7200 // va_start(ap, fmt);
7201 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
7202 // ...
7203 // }
7204 if (HasVAListArg) {
7205 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
7206 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
7207 int PVIndex = PV->getFunctionScopeIndex() + 1;
7208 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
7209 // adjust for implicit parameter
7210 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
7211 if (MD->isInstance())
7212 ++PVIndex;
7213 // We also check if the formats are compatible.
7214 // We can't pass a 'scanf' string to a 'printf' function.
7215 if (PVIndex == PVFormat->getFormatIdx() &&
7216 Type == S.GetFormatStringType(PVFormat))
7217 return SLCT_UncheckedLiteral;
7218 }
7219 }
7220 }
7221 }
7222 }
7223
7224 return SLCT_NotALiteral;
7225 }
7226
7227 case Stmt::CallExprClass:
7228 case Stmt::CXXMemberCallExprClass: {
7229 const CallExpr *CE = cast<CallExpr>(E);
7230 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
7231 bool IsFirst = true;
7232 StringLiteralCheckType CommonResult;
7233 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
7234 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
7235 StringLiteralCheckType Result = checkFormatStringExpr(
7236 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
7237 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7238 IgnoreStringsWithoutSpecifiers);
7239 if (IsFirst) {
7240 CommonResult = Result;
7241 IsFirst = false;
7242 }
7243 }
7244 if (!IsFirst)
7245 return CommonResult;
7246
7247 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
7248 unsigned BuiltinID = FD->getBuiltinID();
7249 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
7250 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
7251 const Expr *Arg = CE->getArg(0);
7252 return checkFormatStringExpr(S, Arg, Args,
7253 HasVAListArg, format_idx,
7254 firstDataArg, Type, CallType,
7255 InFunctionCall, CheckedVarArgs,
7256 UncoveredArg, Offset,
7257 IgnoreStringsWithoutSpecifiers);
7258 }
7259 }
7260 }
7261
7262 return SLCT_NotALiteral;
7263 }
7264 case Stmt::ObjCMessageExprClass: {
7265 const auto *ME = cast<ObjCMessageExpr>(E);
7266 if (const auto *MD = ME->getMethodDecl()) {
7267 if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
7268 // As a special case heuristic, if we're using the method -[NSBundle
7269 // localizedStringForKey:value:table:], ignore any key strings that lack
7270 // format specifiers. The idea is that if the key doesn't have any
7271 // format specifiers then its probably just a key to map to the
7272 // localized strings. If it does have format specifiers though, then its
7273 // likely that the text of the key is the format string in the
7274 // programmer's language, and should be checked.
7275 const ObjCInterfaceDecl *IFace;
7276 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
7277 IFace->getIdentifier()->isStr("NSBundle") &&
7278 MD->getSelector().isKeywordSelector(
7279 {"localizedStringForKey", "value", "table"})) {
7280 IgnoreStringsWithoutSpecifiers = true;
7281 }
7282
7283 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
7284 return checkFormatStringExpr(
7285 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
7286 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7287 IgnoreStringsWithoutSpecifiers);
7288 }
7289 }
7290
7291 return SLCT_NotALiteral;
7292 }
7293 case Stmt::ObjCStringLiteralClass:
7294 case Stmt::StringLiteralClass: {
7295 const StringLiteral *StrE = nullptr;
7296
7297 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
7298 StrE = ObjCFExpr->getString();
7299 else
7300 StrE = cast<StringLiteral>(E);
7301
7302 if (StrE) {
7303 if (Offset.isNegative() || Offset > StrE->getLength()) {
7304 // TODO: It would be better to have an explicit warning for out of
7305 // bounds literals.
7306 return SLCT_NotALiteral;
7307 }
7308 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
7309 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
7310 firstDataArg, Type, InFunctionCall, CallType,
7311 CheckedVarArgs, UncoveredArg,
7312 IgnoreStringsWithoutSpecifiers);
7313 return SLCT_CheckedLiteral;
7314 }
7315
7316 return SLCT_NotALiteral;
7317 }
7318 case Stmt::BinaryOperatorClass: {
7319 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
7320
7321 // A string literal + an int offset is still a string literal.
7322 if (BinOp->isAdditiveOp()) {
7323 Expr::EvalResult LResult, RResult;
7324
7325 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
7326 LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
7327 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
7328 RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
7329
7330 if (LIsInt != RIsInt) {
7331 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
7332
7333 if (LIsInt) {
7334 if (BinOpKind == BO_Add) {
7335 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
7336 E = BinOp->getRHS();
7337 goto tryAgain;
7338 }
7339 } else {
7340 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
7341 E = BinOp->getLHS();
7342 goto tryAgain;
7343 }
7344 }
7345 }
7346
7347 return SLCT_NotALiteral;
7348 }
7349 case Stmt::UnaryOperatorClass: {
7350 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
7351 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
7352 if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
7353 Expr::EvalResult IndexResult;
7354 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
7355 Expr::SE_NoSideEffects,
7356 S.isConstantEvaluated())) {
7357 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
7358 /*RHS is int*/ true);
7359 E = ASE->getBase();
7360 goto tryAgain;
7361 }
7362 }
7363
7364 return SLCT_NotALiteral;
7365 }
7366
7367 default:
7368 return SLCT_NotALiteral;
7369 }
7370 }
7371
GetFormatStringType(const FormatAttr * Format)7372 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
7373 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
7374 .Case("scanf", FST_Scanf)
7375 .Cases("printf", "printf0", FST_Printf)
7376 .Cases("NSString", "CFString", FST_NSString)
7377 .Case("strftime", FST_Strftime)
7378 .Case("strfmon", FST_Strfmon)
7379 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
7380 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
7381 .Case("os_trace", FST_OSLog)
7382 .Case("os_log", FST_OSLog)
7383 .Default(FST_Unknown);
7384 }
7385
7386 /// CheckFormatArguments - Check calls to printf and scanf (and similar
7387 /// functions) for correct use of format strings.
7388 /// Returns true if a format string has been fully checked.
CheckFormatArguments(const FormatAttr * Format,ArrayRef<const Expr * > Args,bool IsCXXMember,VariadicCallType CallType,SourceLocation Loc,SourceRange Range,llvm::SmallBitVector & CheckedVarArgs)7389 bool Sema::CheckFormatArguments(const FormatAttr *Format,
7390 ArrayRef<const Expr *> Args,
7391 bool IsCXXMember,
7392 VariadicCallType CallType,
7393 SourceLocation Loc, SourceRange Range,
7394 llvm::SmallBitVector &CheckedVarArgs) {
7395 FormatStringInfo FSI;
7396 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
7397 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
7398 FSI.FirstDataArg, GetFormatStringType(Format),
7399 CallType, Loc, Range, CheckedVarArgs);
7400 return false;
7401 }
7402
CheckFormatArguments(ArrayRef<const Expr * > Args,bool HasVAListArg,unsigned format_idx,unsigned firstDataArg,FormatStringType Type,VariadicCallType CallType,SourceLocation Loc,SourceRange Range,llvm::SmallBitVector & CheckedVarArgs)7403 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
7404 bool HasVAListArg, unsigned format_idx,
7405 unsigned firstDataArg, FormatStringType Type,
7406 VariadicCallType CallType,
7407 SourceLocation Loc, SourceRange Range,
7408 llvm::SmallBitVector &CheckedVarArgs) {
7409 // CHECK: printf/scanf-like function is called with no format string.
7410 if (format_idx >= Args.size()) {
7411 Diag(Loc, diag::warn_missing_format_string) << Range;
7412 return false;
7413 }
7414
7415 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
7416
7417 // CHECK: format string is not a string literal.
7418 //
7419 // Dynamically generated format strings are difficult to
7420 // automatically vet at compile time. Requiring that format strings
7421 // are string literals: (1) permits the checking of format strings by
7422 // the compiler and thereby (2) can practically remove the source of
7423 // many format string exploits.
7424
7425 // Format string can be either ObjC string (e.g. @"%d") or
7426 // C string (e.g. "%d")
7427 // ObjC string uses the same format specifiers as C string, so we can use
7428 // the same format string checking logic for both ObjC and C strings.
7429 UncoveredArgHandler UncoveredArg;
7430 StringLiteralCheckType CT =
7431 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
7432 format_idx, firstDataArg, Type, CallType,
7433 /*IsFunctionCall*/ true, CheckedVarArgs,
7434 UncoveredArg,
7435 /*no string offset*/ llvm::APSInt(64, false) = 0);
7436
7437 // Generate a diagnostic where an uncovered argument is detected.
7438 if (UncoveredArg.hasUncoveredArg()) {
7439 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
7440 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
7441 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
7442 }
7443
7444 if (CT != SLCT_NotALiteral)
7445 // Literal format string found, check done!
7446 return CT == SLCT_CheckedLiteral;
7447
7448 // Strftime is particular as it always uses a single 'time' argument,
7449 // so it is safe to pass a non-literal string.
7450 if (Type == FST_Strftime)
7451 return false;
7452
7453 // Do not emit diag when the string param is a macro expansion and the
7454 // format is either NSString or CFString. This is a hack to prevent
7455 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
7456 // which are usually used in place of NS and CF string literals.
7457 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
7458 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
7459 return false;
7460
7461 // If there are no arguments specified, warn with -Wformat-security, otherwise
7462 // warn only with -Wformat-nonliteral.
7463 if (Args.size() == firstDataArg) {
7464 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
7465 << OrigFormatExpr->getSourceRange();
7466 switch (Type) {
7467 default:
7468 break;
7469 case FST_Kprintf:
7470 case FST_FreeBSDKPrintf:
7471 case FST_Printf:
7472 Diag(FormatLoc, diag::note_format_security_fixit)
7473 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
7474 break;
7475 case FST_NSString:
7476 Diag(FormatLoc, diag::note_format_security_fixit)
7477 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
7478 break;
7479 }
7480 } else {
7481 Diag(FormatLoc, diag::warn_format_nonliteral)
7482 << OrigFormatExpr->getSourceRange();
7483 }
7484 return false;
7485 }
7486
7487 namespace {
7488
7489 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
7490 protected:
7491 Sema &S;
7492 const FormatStringLiteral *FExpr;
7493 const Expr *OrigFormatExpr;
7494 const Sema::FormatStringType FSType;
7495 const unsigned FirstDataArg;
7496 const unsigned NumDataArgs;
7497 const char *Beg; // Start of format string.
7498 const bool HasVAListArg;
7499 ArrayRef<const Expr *> Args;
7500 unsigned FormatIdx;
7501 llvm::SmallBitVector CoveredArgs;
7502 bool usesPositionalArgs = false;
7503 bool atFirstArg = true;
7504 bool inFunctionCall;
7505 Sema::VariadicCallType CallType;
7506 llvm::SmallBitVector &CheckedVarArgs;
7507 UncoveredArgHandler &UncoveredArg;
7508
7509 public:
CheckFormatHandler(Sema & s,const FormatStringLiteral * fexpr,const Expr * origFormatExpr,const Sema::FormatStringType type,unsigned firstDataArg,unsigned numDataArgs,const char * beg,bool hasVAListArg,ArrayRef<const Expr * > Args,unsigned formatIdx,bool inFunctionCall,Sema::VariadicCallType callType,llvm::SmallBitVector & CheckedVarArgs,UncoveredArgHandler & UncoveredArg)7510 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
7511 const Expr *origFormatExpr,
7512 const Sema::FormatStringType type, unsigned firstDataArg,
7513 unsigned numDataArgs, const char *beg, bool hasVAListArg,
7514 ArrayRef<const Expr *> Args, unsigned formatIdx,
7515 bool inFunctionCall, Sema::VariadicCallType callType,
7516 llvm::SmallBitVector &CheckedVarArgs,
7517 UncoveredArgHandler &UncoveredArg)
7518 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
7519 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
7520 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
7521 inFunctionCall(inFunctionCall), CallType(callType),
7522 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
7523 CoveredArgs.resize(numDataArgs);
7524 CoveredArgs.reset();
7525 }
7526
7527 void DoneProcessing();
7528
7529 void HandleIncompleteSpecifier(const char *startSpecifier,
7530 unsigned specifierLen) override;
7531
7532 void HandleInvalidLengthModifier(
7533 const analyze_format_string::FormatSpecifier &FS,
7534 const analyze_format_string::ConversionSpecifier &CS,
7535 const char *startSpecifier, unsigned specifierLen,
7536 unsigned DiagID);
7537
7538 void HandleNonStandardLengthModifier(
7539 const analyze_format_string::FormatSpecifier &FS,
7540 const char *startSpecifier, unsigned specifierLen);
7541
7542 void HandleNonStandardConversionSpecifier(
7543 const analyze_format_string::ConversionSpecifier &CS,
7544 const char *startSpecifier, unsigned specifierLen);
7545
7546 void HandlePosition(const char *startPos, unsigned posLen) override;
7547
7548 void HandleInvalidPosition(const char *startSpecifier,
7549 unsigned specifierLen,
7550 analyze_format_string::PositionContext p) override;
7551
7552 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
7553
7554 void HandleNullChar(const char *nullCharacter) override;
7555
7556 template <typename Range>
7557 static void
7558 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
7559 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
7560 bool IsStringLocation, Range StringRange,
7561 ArrayRef<FixItHint> Fixit = None);
7562
7563 protected:
7564 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
7565 const char *startSpec,
7566 unsigned specifierLen,
7567 const char *csStart, unsigned csLen);
7568
7569 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
7570 const char *startSpec,
7571 unsigned specifierLen);
7572
7573 SourceRange getFormatStringRange();
7574 CharSourceRange getSpecifierRange(const char *startSpecifier,
7575 unsigned specifierLen);
7576 SourceLocation getLocationOfByte(const char *x);
7577
7578 const Expr *getDataArg(unsigned i) const;
7579
7580 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
7581 const analyze_format_string::ConversionSpecifier &CS,
7582 const char *startSpecifier, unsigned specifierLen,
7583 unsigned argIndex);
7584
7585 template <typename Range>
7586 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
7587 bool IsStringLocation, Range StringRange,
7588 ArrayRef<FixItHint> Fixit = None);
7589 };
7590
7591 } // namespace
7592
getFormatStringRange()7593 SourceRange CheckFormatHandler::getFormatStringRange() {
7594 return OrigFormatExpr->getSourceRange();
7595 }
7596
7597 CharSourceRange CheckFormatHandler::
getSpecifierRange(const char * startSpecifier,unsigned specifierLen)7598 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
7599 SourceLocation Start = getLocationOfByte(startSpecifier);
7600 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
7601
7602 // Advance the end SourceLocation by one due to half-open ranges.
7603 End = End.getLocWithOffset(1);
7604
7605 return CharSourceRange::getCharRange(Start, End);
7606 }
7607
getLocationOfByte(const char * x)7608 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
7609 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
7610 S.getLangOpts(), S.Context.getTargetInfo());
7611 }
7612
HandleIncompleteSpecifier(const char * startSpecifier,unsigned specifierLen)7613 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
7614 unsigned specifierLen){
7615 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
7616 getLocationOfByte(startSpecifier),
7617 /*IsStringLocation*/true,
7618 getSpecifierRange(startSpecifier, specifierLen));
7619 }
7620
HandleInvalidLengthModifier(const analyze_format_string::FormatSpecifier & FS,const analyze_format_string::ConversionSpecifier & CS,const char * startSpecifier,unsigned specifierLen,unsigned DiagID)7621 void CheckFormatHandler::HandleInvalidLengthModifier(
7622 const analyze_format_string::FormatSpecifier &FS,
7623 const analyze_format_string::ConversionSpecifier &CS,
7624 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
7625 using namespace analyze_format_string;
7626
7627 const LengthModifier &LM = FS.getLengthModifier();
7628 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7629
7630 // See if we know how to fix this length modifier.
7631 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7632 if (FixedLM) {
7633 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7634 getLocationOfByte(LM.getStart()),
7635 /*IsStringLocation*/true,
7636 getSpecifierRange(startSpecifier, specifierLen));
7637
7638 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7639 << FixedLM->toString()
7640 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7641
7642 } else {
7643 FixItHint Hint;
7644 if (DiagID == diag::warn_format_nonsensical_length)
7645 Hint = FixItHint::CreateRemoval(LMRange);
7646
7647 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7648 getLocationOfByte(LM.getStart()),
7649 /*IsStringLocation*/true,
7650 getSpecifierRange(startSpecifier, specifierLen),
7651 Hint);
7652 }
7653 }
7654
HandleNonStandardLengthModifier(const analyze_format_string::FormatSpecifier & FS,const char * startSpecifier,unsigned specifierLen)7655 void CheckFormatHandler::HandleNonStandardLengthModifier(
7656 const analyze_format_string::FormatSpecifier &FS,
7657 const char *startSpecifier, unsigned specifierLen) {
7658 using namespace analyze_format_string;
7659
7660 const LengthModifier &LM = FS.getLengthModifier();
7661 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7662
7663 // See if we know how to fix this length modifier.
7664 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7665 if (FixedLM) {
7666 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7667 << LM.toString() << 0,
7668 getLocationOfByte(LM.getStart()),
7669 /*IsStringLocation*/true,
7670 getSpecifierRange(startSpecifier, specifierLen));
7671
7672 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7673 << FixedLM->toString()
7674 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7675
7676 } else {
7677 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7678 << LM.toString() << 0,
7679 getLocationOfByte(LM.getStart()),
7680 /*IsStringLocation*/true,
7681 getSpecifierRange(startSpecifier, specifierLen));
7682 }
7683 }
7684
HandleNonStandardConversionSpecifier(const analyze_format_string::ConversionSpecifier & CS,const char * startSpecifier,unsigned specifierLen)7685 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
7686 const analyze_format_string::ConversionSpecifier &CS,
7687 const char *startSpecifier, unsigned specifierLen) {
7688 using namespace analyze_format_string;
7689
7690 // See if we know how to fix this conversion specifier.
7691 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
7692 if (FixedCS) {
7693 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7694 << CS.toString() << /*conversion specifier*/1,
7695 getLocationOfByte(CS.getStart()),
7696 /*IsStringLocation*/true,
7697 getSpecifierRange(startSpecifier, specifierLen));
7698
7699 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
7700 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
7701 << FixedCS->toString()
7702 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
7703 } else {
7704 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7705 << CS.toString() << /*conversion specifier*/1,
7706 getLocationOfByte(CS.getStart()),
7707 /*IsStringLocation*/true,
7708 getSpecifierRange(startSpecifier, specifierLen));
7709 }
7710 }
7711
HandlePosition(const char * startPos,unsigned posLen)7712 void CheckFormatHandler::HandlePosition(const char *startPos,
7713 unsigned posLen) {
7714 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
7715 getLocationOfByte(startPos),
7716 /*IsStringLocation*/true,
7717 getSpecifierRange(startPos, posLen));
7718 }
7719
7720 void
HandleInvalidPosition(const char * startPos,unsigned posLen,analyze_format_string::PositionContext p)7721 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
7722 analyze_format_string::PositionContext p) {
7723 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
7724 << (unsigned) p,
7725 getLocationOfByte(startPos), /*IsStringLocation*/true,
7726 getSpecifierRange(startPos, posLen));
7727 }
7728
HandleZeroPosition(const char * startPos,unsigned posLen)7729 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
7730 unsigned posLen) {
7731 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
7732 getLocationOfByte(startPos),
7733 /*IsStringLocation*/true,
7734 getSpecifierRange(startPos, posLen));
7735 }
7736
HandleNullChar(const char * nullCharacter)7737 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
7738 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
7739 // The presence of a null character is likely an error.
7740 EmitFormatDiagnostic(
7741 S.PDiag(diag::warn_printf_format_string_contains_null_char),
7742 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
7743 getFormatStringRange());
7744 }
7745 }
7746
7747 // Note that this may return NULL if there was an error parsing or building
7748 // one of the argument expressions.
getDataArg(unsigned i) const7749 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
7750 return Args[FirstDataArg + i];
7751 }
7752
DoneProcessing()7753 void CheckFormatHandler::DoneProcessing() {
7754 // Does the number of data arguments exceed the number of
7755 // format conversions in the format string?
7756 if (!HasVAListArg) {
7757 // Find any arguments that weren't covered.
7758 CoveredArgs.flip();
7759 signed notCoveredArg = CoveredArgs.find_first();
7760 if (notCoveredArg >= 0) {
7761 assert((unsigned)notCoveredArg < NumDataArgs);
7762 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
7763 } else {
7764 UncoveredArg.setAllCovered();
7765 }
7766 }
7767 }
7768
Diagnose(Sema & S,bool IsFunctionCall,const Expr * ArgExpr)7769 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
7770 const Expr *ArgExpr) {
7771 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
7772 "Invalid state");
7773
7774 if (!ArgExpr)
7775 return;
7776
7777 SourceLocation Loc = ArgExpr->getBeginLoc();
7778
7779 if (S.getSourceManager().isInSystemMacro(Loc))
7780 return;
7781
7782 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
7783 for (auto E : DiagnosticExprs)
7784 PDiag << E->getSourceRange();
7785
7786 CheckFormatHandler::EmitFormatDiagnostic(
7787 S, IsFunctionCall, DiagnosticExprs[0],
7788 PDiag, Loc, /*IsStringLocation*/false,
7789 DiagnosticExprs[0]->getSourceRange());
7790 }
7791
7792 bool
HandleInvalidConversionSpecifier(unsigned argIndex,SourceLocation Loc,const char * startSpec,unsigned specifierLen,const char * csStart,unsigned csLen)7793 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
7794 SourceLocation Loc,
7795 const char *startSpec,
7796 unsigned specifierLen,
7797 const char *csStart,
7798 unsigned csLen) {
7799 bool keepGoing = true;
7800 if (argIndex < NumDataArgs) {
7801 // Consider the argument coverered, even though the specifier doesn't
7802 // make sense.
7803 CoveredArgs.set(argIndex);
7804 }
7805 else {
7806 // If argIndex exceeds the number of data arguments we
7807 // don't issue a warning because that is just a cascade of warnings (and
7808 // they may have intended '%%' anyway). We don't want to continue processing
7809 // the format string after this point, however, as we will like just get
7810 // gibberish when trying to match arguments.
7811 keepGoing = false;
7812 }
7813
7814 StringRef Specifier(csStart, csLen);
7815
7816 // If the specifier in non-printable, it could be the first byte of a UTF-8
7817 // sequence. In that case, print the UTF-8 code point. If not, print the byte
7818 // hex value.
7819 std::string CodePointStr;
7820 if (!llvm::sys::locale::isPrint(*csStart)) {
7821 llvm::UTF32 CodePoint;
7822 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
7823 const llvm::UTF8 *E =
7824 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
7825 llvm::ConversionResult Result =
7826 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
7827
7828 if (Result != llvm::conversionOK) {
7829 unsigned char FirstChar = *csStart;
7830 CodePoint = (llvm::UTF32)FirstChar;
7831 }
7832
7833 llvm::raw_string_ostream OS(CodePointStr);
7834 if (CodePoint < 256)
7835 OS << "\\x" << llvm::format("%02x", CodePoint);
7836 else if (CodePoint <= 0xFFFF)
7837 OS << "\\u" << llvm::format("%04x", CodePoint);
7838 else
7839 OS << "\\U" << llvm::format("%08x", CodePoint);
7840 OS.flush();
7841 Specifier = CodePointStr;
7842 }
7843
7844 EmitFormatDiagnostic(
7845 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
7846 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
7847
7848 return keepGoing;
7849 }
7850
7851 void
HandlePositionalNonpositionalArgs(SourceLocation Loc,const char * startSpec,unsigned specifierLen)7852 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
7853 const char *startSpec,
7854 unsigned specifierLen) {
7855 EmitFormatDiagnostic(
7856 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
7857 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
7858 }
7859
7860 bool
CheckNumArgs(const analyze_format_string::FormatSpecifier & FS,const analyze_format_string::ConversionSpecifier & CS,const char * startSpecifier,unsigned specifierLen,unsigned argIndex)7861 CheckFormatHandler::CheckNumArgs(
7862 const analyze_format_string::FormatSpecifier &FS,
7863 const analyze_format_string::ConversionSpecifier &CS,
7864 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
7865
7866 if (argIndex >= NumDataArgs) {
7867 PartialDiagnostic PDiag = FS.usesPositionalArg()
7868 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
7869 << (argIndex+1) << NumDataArgs)
7870 : S.PDiag(diag::warn_printf_insufficient_data_args);
7871 EmitFormatDiagnostic(
7872 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
7873 getSpecifierRange(startSpecifier, specifierLen));
7874
7875 // Since more arguments than conversion tokens are given, by extension
7876 // all arguments are covered, so mark this as so.
7877 UncoveredArg.setAllCovered();
7878 return false;
7879 }
7880 return true;
7881 }
7882
7883 template<typename Range>
EmitFormatDiagnostic(PartialDiagnostic PDiag,SourceLocation Loc,bool IsStringLocation,Range StringRange,ArrayRef<FixItHint> FixIt)7884 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
7885 SourceLocation Loc,
7886 bool IsStringLocation,
7887 Range StringRange,
7888 ArrayRef<FixItHint> FixIt) {
7889 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
7890 Loc, IsStringLocation, StringRange, FixIt);
7891 }
7892
7893 /// If the format string is not within the function call, emit a note
7894 /// so that the function call and string are in diagnostic messages.
7895 ///
7896 /// \param InFunctionCall if true, the format string is within the function
7897 /// call and only one diagnostic message will be produced. Otherwise, an
7898 /// extra note will be emitted pointing to location of the format string.
7899 ///
7900 /// \param ArgumentExpr the expression that is passed as the format string
7901 /// argument in the function call. Used for getting locations when two
7902 /// diagnostics are emitted.
7903 ///
7904 /// \param PDiag the callee should already have provided any strings for the
7905 /// diagnostic message. This function only adds locations and fixits
7906 /// to diagnostics.
7907 ///
7908 /// \param Loc primary location for diagnostic. If two diagnostics are
7909 /// required, one will be at Loc and a new SourceLocation will be created for
7910 /// the other one.
7911 ///
7912 /// \param IsStringLocation if true, Loc points to the format string should be
7913 /// used for the note. Otherwise, Loc points to the argument list and will
7914 /// be used with PDiag.
7915 ///
7916 /// \param StringRange some or all of the string to highlight. This is
7917 /// templated so it can accept either a CharSourceRange or a SourceRange.
7918 ///
7919 /// \param FixIt optional fix it hint for the format string.
7920 template <typename Range>
EmitFormatDiagnostic(Sema & S,bool InFunctionCall,const Expr * ArgumentExpr,const PartialDiagnostic & PDiag,SourceLocation Loc,bool IsStringLocation,Range StringRange,ArrayRef<FixItHint> FixIt)7921 void CheckFormatHandler::EmitFormatDiagnostic(
7922 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
7923 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
7924 Range StringRange, ArrayRef<FixItHint> FixIt) {
7925 if (InFunctionCall) {
7926 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
7927 D << StringRange;
7928 D << FixIt;
7929 } else {
7930 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
7931 << ArgumentExpr->getSourceRange();
7932
7933 const Sema::SemaDiagnosticBuilder &Note =
7934 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
7935 diag::note_format_string_defined);
7936
7937 Note << StringRange;
7938 Note << FixIt;
7939 }
7940 }
7941
7942 //===--- CHECK: Printf format string checking ------------------------------===//
7943
7944 namespace {
7945
7946 class CheckPrintfHandler : public CheckFormatHandler {
7947 public:
CheckPrintfHandler(Sema & s,const FormatStringLiteral * fexpr,const Expr * origFormatExpr,const Sema::FormatStringType type,unsigned firstDataArg,unsigned numDataArgs,bool isObjC,const char * beg,bool hasVAListArg,ArrayRef<const Expr * > Args,unsigned formatIdx,bool inFunctionCall,Sema::VariadicCallType CallType,llvm::SmallBitVector & CheckedVarArgs,UncoveredArgHandler & UncoveredArg)7948 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
7949 const Expr *origFormatExpr,
7950 const Sema::FormatStringType type, unsigned firstDataArg,
7951 unsigned numDataArgs, bool isObjC, const char *beg,
7952 bool hasVAListArg, ArrayRef<const Expr *> Args,
7953 unsigned formatIdx, bool inFunctionCall,
7954 Sema::VariadicCallType CallType,
7955 llvm::SmallBitVector &CheckedVarArgs,
7956 UncoveredArgHandler &UncoveredArg)
7957 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7958 numDataArgs, beg, hasVAListArg, Args, formatIdx,
7959 inFunctionCall, CallType, CheckedVarArgs,
7960 UncoveredArg) {}
7961
isObjCContext() const7962 bool isObjCContext() const { return FSType == Sema::FST_NSString; }
7963
7964 /// Returns true if '%@' specifiers are allowed in the format string.
allowsObjCArg() const7965 bool allowsObjCArg() const {
7966 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
7967 FSType == Sema::FST_OSTrace;
7968 }
7969
7970 bool HandleInvalidPrintfConversionSpecifier(
7971 const analyze_printf::PrintfSpecifier &FS,
7972 const char *startSpecifier,
7973 unsigned specifierLen) override;
7974
7975 void handleInvalidMaskType(StringRef MaskType) override;
7976
7977 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
7978 const char *startSpecifier,
7979 unsigned specifierLen) override;
7980 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
7981 const char *StartSpecifier,
7982 unsigned SpecifierLen,
7983 const Expr *E);
7984
7985 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
7986 const char *startSpecifier, unsigned specifierLen);
7987 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
7988 const analyze_printf::OptionalAmount &Amt,
7989 unsigned type,
7990 const char *startSpecifier, unsigned specifierLen);
7991 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7992 const analyze_printf::OptionalFlag &flag,
7993 const char *startSpecifier, unsigned specifierLen);
7994 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
7995 const analyze_printf::OptionalFlag &ignoredFlag,
7996 const analyze_printf::OptionalFlag &flag,
7997 const char *startSpecifier, unsigned specifierLen);
7998 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
7999 const Expr *E);
8000
8001 void HandleEmptyObjCModifierFlag(const char *startFlag,
8002 unsigned flagLen) override;
8003
8004 void HandleInvalidObjCModifierFlag(const char *startFlag,
8005 unsigned flagLen) override;
8006
8007 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
8008 const char *flagsEnd,
8009 const char *conversionPosition)
8010 override;
8011 };
8012
8013 } // namespace
8014
HandleInvalidPrintfConversionSpecifier(const analyze_printf::PrintfSpecifier & FS,const char * startSpecifier,unsigned specifierLen)8015 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
8016 const analyze_printf::PrintfSpecifier &FS,
8017 const char *startSpecifier,
8018 unsigned specifierLen) {
8019 const analyze_printf::PrintfConversionSpecifier &CS =
8020 FS.getConversionSpecifier();
8021
8022 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8023 getLocationOfByte(CS.getStart()),
8024 startSpecifier, specifierLen,
8025 CS.getStart(), CS.getLength());
8026 }
8027
handleInvalidMaskType(StringRef MaskType)8028 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
8029 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
8030 }
8031
HandleAmount(const analyze_format_string::OptionalAmount & Amt,unsigned k,const char * startSpecifier,unsigned specifierLen)8032 bool CheckPrintfHandler::HandleAmount(
8033 const analyze_format_string::OptionalAmount &Amt,
8034 unsigned k, const char *startSpecifier,
8035 unsigned specifierLen) {
8036 if (Amt.hasDataArgument()) {
8037 if (!HasVAListArg) {
8038 unsigned argIndex = Amt.getArgIndex();
8039 if (argIndex >= NumDataArgs) {
8040 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
8041 << k,
8042 getLocationOfByte(Amt.getStart()),
8043 /*IsStringLocation*/true,
8044 getSpecifierRange(startSpecifier, specifierLen));
8045 // Don't do any more checking. We will just emit
8046 // spurious errors.
8047 return false;
8048 }
8049
8050 // Type check the data argument. It should be an 'int'.
8051 // Although not in conformance with C99, we also allow the argument to be
8052 // an 'unsigned int' as that is a reasonably safe case. GCC also
8053 // doesn't emit a warning for that case.
8054 CoveredArgs.set(argIndex);
8055 const Expr *Arg = getDataArg(argIndex);
8056 if (!Arg)
8057 return false;
8058
8059 QualType T = Arg->getType();
8060
8061 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
8062 assert(AT.isValid());
8063
8064 if (!AT.matchesType(S.Context, T)) {
8065 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
8066 << k << AT.getRepresentativeTypeName(S.Context)
8067 << T << Arg->getSourceRange(),
8068 getLocationOfByte(Amt.getStart()),
8069 /*IsStringLocation*/true,
8070 getSpecifierRange(startSpecifier, specifierLen));
8071 // Don't do any more checking. We will just emit
8072 // spurious errors.
8073 return false;
8074 }
8075 }
8076 }
8077 return true;
8078 }
8079
HandleInvalidAmount(const analyze_printf::PrintfSpecifier & FS,const analyze_printf::OptionalAmount & Amt,unsigned type,const char * startSpecifier,unsigned specifierLen)8080 void CheckPrintfHandler::HandleInvalidAmount(
8081 const analyze_printf::PrintfSpecifier &FS,
8082 const analyze_printf::OptionalAmount &Amt,
8083 unsigned type,
8084 const char *startSpecifier,
8085 unsigned specifierLen) {
8086 const analyze_printf::PrintfConversionSpecifier &CS =
8087 FS.getConversionSpecifier();
8088
8089 FixItHint fixit =
8090 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
8091 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
8092 Amt.getConstantLength()))
8093 : FixItHint();
8094
8095 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
8096 << type << CS.toString(),
8097 getLocationOfByte(Amt.getStart()),
8098 /*IsStringLocation*/true,
8099 getSpecifierRange(startSpecifier, specifierLen),
8100 fixit);
8101 }
8102
HandleFlag(const analyze_printf::PrintfSpecifier & FS,const analyze_printf::OptionalFlag & flag,const char * startSpecifier,unsigned specifierLen)8103 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8104 const analyze_printf::OptionalFlag &flag,
8105 const char *startSpecifier,
8106 unsigned specifierLen) {
8107 // Warn about pointless flag with a fixit removal.
8108 const analyze_printf::PrintfConversionSpecifier &CS =
8109 FS.getConversionSpecifier();
8110 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
8111 << flag.toString() << CS.toString(),
8112 getLocationOfByte(flag.getPosition()),
8113 /*IsStringLocation*/true,
8114 getSpecifierRange(startSpecifier, specifierLen),
8115 FixItHint::CreateRemoval(
8116 getSpecifierRange(flag.getPosition(), 1)));
8117 }
8118
HandleIgnoredFlag(const analyze_printf::PrintfSpecifier & FS,const analyze_printf::OptionalFlag & ignoredFlag,const analyze_printf::OptionalFlag & flag,const char * startSpecifier,unsigned specifierLen)8119 void CheckPrintfHandler::HandleIgnoredFlag(
8120 const analyze_printf::PrintfSpecifier &FS,
8121 const analyze_printf::OptionalFlag &ignoredFlag,
8122 const analyze_printf::OptionalFlag &flag,
8123 const char *startSpecifier,
8124 unsigned specifierLen) {
8125 // Warn about ignored flag with a fixit removal.
8126 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
8127 << ignoredFlag.toString() << flag.toString(),
8128 getLocationOfByte(ignoredFlag.getPosition()),
8129 /*IsStringLocation*/true,
8130 getSpecifierRange(startSpecifier, specifierLen),
8131 FixItHint::CreateRemoval(
8132 getSpecifierRange(ignoredFlag.getPosition(), 1)));
8133 }
8134
HandleEmptyObjCModifierFlag(const char * startFlag,unsigned flagLen)8135 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
8136 unsigned flagLen) {
8137 // Warn about an empty flag.
8138 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
8139 getLocationOfByte(startFlag),
8140 /*IsStringLocation*/true,
8141 getSpecifierRange(startFlag, flagLen));
8142 }
8143
HandleInvalidObjCModifierFlag(const char * startFlag,unsigned flagLen)8144 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
8145 unsigned flagLen) {
8146 // Warn about an invalid flag.
8147 auto Range = getSpecifierRange(startFlag, flagLen);
8148 StringRef flag(startFlag, flagLen);
8149 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
8150 getLocationOfByte(startFlag),
8151 /*IsStringLocation*/true,
8152 Range, FixItHint::CreateRemoval(Range));
8153 }
8154
HandleObjCFlagsWithNonObjCConversion(const char * flagsStart,const char * flagsEnd,const char * conversionPosition)8155 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
8156 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
8157 // Warn about using '[...]' without a '@' conversion.
8158 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
8159 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
8160 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
8161 getLocationOfByte(conversionPosition),
8162 /*IsStringLocation*/true,
8163 Range, FixItHint::CreateRemoval(Range));
8164 }
8165
8166 // Determines if the specified is a C++ class or struct containing
8167 // a member with the specified name and kind (e.g. a CXXMethodDecl named
8168 // "c_str()").
8169 template<typename MemberKind>
8170 static llvm::SmallPtrSet<MemberKind*, 1>
CXXRecordMembersNamed(StringRef Name,Sema & S,QualType Ty)8171 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
8172 const RecordType *RT = Ty->getAs<RecordType>();
8173 llvm::SmallPtrSet<MemberKind*, 1> Results;
8174
8175 if (!RT)
8176 return Results;
8177 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
8178 if (!RD || !RD->getDefinition())
8179 return Results;
8180
8181 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
8182 Sema::LookupMemberName);
8183 R.suppressDiagnostics();
8184
8185 // We just need to include all members of the right kind turned up by the
8186 // filter, at this point.
8187 if (S.LookupQualifiedName(R, RT->getDecl()))
8188 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
8189 NamedDecl *decl = (*I)->getUnderlyingDecl();
8190 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
8191 Results.insert(FK);
8192 }
8193 return Results;
8194 }
8195
8196 /// Check if we could call '.c_str()' on an object.
8197 ///
8198 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
8199 /// allow the call, or if it would be ambiguous).
hasCStrMethod(const Expr * E)8200 bool Sema::hasCStrMethod(const Expr *E) {
8201 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8202
8203 MethodSet Results =
8204 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
8205 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8206 MI != ME; ++MI)
8207 if ((*MI)->getMinRequiredArguments() == 0)
8208 return true;
8209 return false;
8210 }
8211
8212 // Check if a (w)string was passed when a (w)char* was needed, and offer a
8213 // better diagnostic if so. AT is assumed to be valid.
8214 // Returns true when a c_str() conversion method is found.
checkForCStrMembers(const analyze_printf::ArgType & AT,const Expr * E)8215 bool CheckPrintfHandler::checkForCStrMembers(
8216 const analyze_printf::ArgType &AT, const Expr *E) {
8217 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8218
8219 MethodSet Results =
8220 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
8221
8222 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8223 MI != ME; ++MI) {
8224 const CXXMethodDecl *Method = *MI;
8225 if (Method->getMinRequiredArguments() == 0 &&
8226 AT.matchesType(S.Context, Method->getReturnType())) {
8227 // FIXME: Suggest parens if the expression needs them.
8228 SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
8229 S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
8230 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
8231 return true;
8232 }
8233 }
8234
8235 return false;
8236 }
8237
8238 bool
HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier & FS,const char * startSpecifier,unsigned specifierLen)8239 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
8240 &FS,
8241 const char *startSpecifier,
8242 unsigned specifierLen) {
8243 using namespace analyze_format_string;
8244 using namespace analyze_printf;
8245
8246 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
8247
8248 if (FS.consumesDataArgument()) {
8249 if (atFirstArg) {
8250 atFirstArg = false;
8251 usesPositionalArgs = FS.usesPositionalArg();
8252 }
8253 else if (usesPositionalArgs != FS.usesPositionalArg()) {
8254 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8255 startSpecifier, specifierLen);
8256 return false;
8257 }
8258 }
8259
8260 // First check if the field width, precision, and conversion specifier
8261 // have matching data arguments.
8262 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
8263 startSpecifier, specifierLen)) {
8264 return false;
8265 }
8266
8267 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
8268 startSpecifier, specifierLen)) {
8269 return false;
8270 }
8271
8272 if (!CS.consumesDataArgument()) {
8273 // FIXME: Technically specifying a precision or field width here
8274 // makes no sense. Worth issuing a warning at some point.
8275 return true;
8276 }
8277
8278 // Consume the argument.
8279 unsigned argIndex = FS.getArgIndex();
8280 if (argIndex < NumDataArgs) {
8281 // The check to see if the argIndex is valid will come later.
8282 // We set the bit here because we may exit early from this
8283 // function if we encounter some other error.
8284 CoveredArgs.set(argIndex);
8285 }
8286
8287 // FreeBSD kernel extensions.
8288 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
8289 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
8290 // We need at least two arguments.
8291 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
8292 return false;
8293
8294 // Claim the second argument.
8295 CoveredArgs.set(argIndex + 1);
8296
8297 // Type check the first argument (int for %b, pointer for %D)
8298 const Expr *Ex = getDataArg(argIndex);
8299 const analyze_printf::ArgType &AT =
8300 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
8301 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
8302 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
8303 EmitFormatDiagnostic(
8304 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8305 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
8306 << false << Ex->getSourceRange(),
8307 Ex->getBeginLoc(), /*IsStringLocation*/ false,
8308 getSpecifierRange(startSpecifier, specifierLen));
8309
8310 // Type check the second argument (char * for both %b and %D)
8311 Ex = getDataArg(argIndex + 1);
8312 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
8313 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
8314 EmitFormatDiagnostic(
8315 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8316 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
8317 << false << Ex->getSourceRange(),
8318 Ex->getBeginLoc(), /*IsStringLocation*/ false,
8319 getSpecifierRange(startSpecifier, specifierLen));
8320
8321 return true;
8322 }
8323
8324 // Check for using an Objective-C specific conversion specifier
8325 // in a non-ObjC literal.
8326 if (!allowsObjCArg() && CS.isObjCArg()) {
8327 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8328 specifierLen);
8329 }
8330
8331 // %P can only be used with os_log.
8332 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
8333 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8334 specifierLen);
8335 }
8336
8337 // %n is not allowed with os_log.
8338 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
8339 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
8340 getLocationOfByte(CS.getStart()),
8341 /*IsStringLocation*/ false,
8342 getSpecifierRange(startSpecifier, specifierLen));
8343
8344 return true;
8345 }
8346
8347 // Only scalars are allowed for os_trace.
8348 if (FSType == Sema::FST_OSTrace &&
8349 (CS.getKind() == ConversionSpecifier::PArg ||
8350 CS.getKind() == ConversionSpecifier::sArg ||
8351 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
8352 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8353 specifierLen);
8354 }
8355
8356 // Check for use of public/private annotation outside of os_log().
8357 if (FSType != Sema::FST_OSLog) {
8358 if (FS.isPublic().isSet()) {
8359 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8360 << "public",
8361 getLocationOfByte(FS.isPublic().getPosition()),
8362 /*IsStringLocation*/ false,
8363 getSpecifierRange(startSpecifier, specifierLen));
8364 }
8365 if (FS.isPrivate().isSet()) {
8366 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8367 << "private",
8368 getLocationOfByte(FS.isPrivate().getPosition()),
8369 /*IsStringLocation*/ false,
8370 getSpecifierRange(startSpecifier, specifierLen));
8371 }
8372 }
8373
8374 // Check for invalid use of field width
8375 if (!FS.hasValidFieldWidth()) {
8376 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
8377 startSpecifier, specifierLen);
8378 }
8379
8380 // Check for invalid use of precision
8381 if (!FS.hasValidPrecision()) {
8382 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
8383 startSpecifier, specifierLen);
8384 }
8385
8386 // Precision is mandatory for %P specifier.
8387 if (CS.getKind() == ConversionSpecifier::PArg &&
8388 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
8389 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
8390 getLocationOfByte(startSpecifier),
8391 /*IsStringLocation*/ false,
8392 getSpecifierRange(startSpecifier, specifierLen));
8393 }
8394
8395 // Check each flag does not conflict with any other component.
8396 if (!FS.hasValidThousandsGroupingPrefix())
8397 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
8398 if (!FS.hasValidLeadingZeros())
8399 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
8400 if (!FS.hasValidPlusPrefix())
8401 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
8402 if (!FS.hasValidSpacePrefix())
8403 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
8404 if (!FS.hasValidAlternativeForm())
8405 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
8406 if (!FS.hasValidLeftJustified())
8407 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
8408
8409 // Check that flags are not ignored by another flag
8410 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
8411 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
8412 startSpecifier, specifierLen);
8413 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
8414 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
8415 startSpecifier, specifierLen);
8416
8417 // Check the length modifier is valid with the given conversion specifier.
8418 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
8419 S.getLangOpts()))
8420 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8421 diag::warn_format_nonsensical_length);
8422 else if (!FS.hasStandardLengthModifier())
8423 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8424 else if (!FS.hasStandardLengthConversionCombination())
8425 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8426 diag::warn_format_non_standard_conversion_spec);
8427
8428 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8429 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8430
8431 // The remaining checks depend on the data arguments.
8432 if (HasVAListArg)
8433 return true;
8434
8435 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8436 return false;
8437
8438 const Expr *Arg = getDataArg(argIndex);
8439 if (!Arg)
8440 return true;
8441
8442 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
8443 }
8444
requiresParensToAddCast(const Expr * E)8445 static bool requiresParensToAddCast(const Expr *E) {
8446 // FIXME: We should have a general way to reason about operator
8447 // precedence and whether parens are actually needed here.
8448 // Take care of a few common cases where they aren't.
8449 const Expr *Inside = E->IgnoreImpCasts();
8450 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
8451 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
8452
8453 switch (Inside->getStmtClass()) {
8454 case Stmt::ArraySubscriptExprClass:
8455 case Stmt::CallExprClass:
8456 case Stmt::CharacterLiteralClass:
8457 case Stmt::CXXBoolLiteralExprClass:
8458 case Stmt::DeclRefExprClass:
8459 case Stmt::FloatingLiteralClass:
8460 case Stmt::IntegerLiteralClass:
8461 case Stmt::MemberExprClass:
8462 case Stmt::ObjCArrayLiteralClass:
8463 case Stmt::ObjCBoolLiteralExprClass:
8464 case Stmt::ObjCBoxedExprClass:
8465 case Stmt::ObjCDictionaryLiteralClass:
8466 case Stmt::ObjCEncodeExprClass:
8467 case Stmt::ObjCIvarRefExprClass:
8468 case Stmt::ObjCMessageExprClass:
8469 case Stmt::ObjCPropertyRefExprClass:
8470 case Stmt::ObjCStringLiteralClass:
8471 case Stmt::ObjCSubscriptRefExprClass:
8472 case Stmt::ParenExprClass:
8473 case Stmt::StringLiteralClass:
8474 case Stmt::UnaryOperatorClass:
8475 return false;
8476 default:
8477 return true;
8478 }
8479 }
8480
8481 static std::pair<QualType, StringRef>
shouldNotPrintDirectly(const ASTContext & Context,QualType IntendedTy,const Expr * E)8482 shouldNotPrintDirectly(const ASTContext &Context,
8483 QualType IntendedTy,
8484 const Expr *E) {
8485 // Use a 'while' to peel off layers of typedefs.
8486 QualType TyTy = IntendedTy;
8487 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
8488 StringRef Name = UserTy->getDecl()->getName();
8489 QualType CastTy = llvm::StringSwitch<QualType>(Name)
8490 .Case("CFIndex", Context.getNSIntegerType())
8491 .Case("NSInteger", Context.getNSIntegerType())
8492 .Case("NSUInteger", Context.getNSUIntegerType())
8493 .Case("SInt32", Context.IntTy)
8494 .Case("UInt32", Context.UnsignedIntTy)
8495 .Default(QualType());
8496
8497 if (!CastTy.isNull())
8498 return std::make_pair(CastTy, Name);
8499
8500 TyTy = UserTy->desugar();
8501 }
8502
8503 // Strip parens if necessary.
8504 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
8505 return shouldNotPrintDirectly(Context,
8506 PE->getSubExpr()->getType(),
8507 PE->getSubExpr());
8508
8509 // If this is a conditional expression, then its result type is constructed
8510 // via usual arithmetic conversions and thus there might be no necessary
8511 // typedef sugar there. Recurse to operands to check for NSInteger &
8512 // Co. usage condition.
8513 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
8514 QualType TrueTy, FalseTy;
8515 StringRef TrueName, FalseName;
8516
8517 std::tie(TrueTy, TrueName) =
8518 shouldNotPrintDirectly(Context,
8519 CO->getTrueExpr()->getType(),
8520 CO->getTrueExpr());
8521 std::tie(FalseTy, FalseName) =
8522 shouldNotPrintDirectly(Context,
8523 CO->getFalseExpr()->getType(),
8524 CO->getFalseExpr());
8525
8526 if (TrueTy == FalseTy)
8527 return std::make_pair(TrueTy, TrueName);
8528 else if (TrueTy.isNull())
8529 return std::make_pair(FalseTy, FalseName);
8530 else if (FalseTy.isNull())
8531 return std::make_pair(TrueTy, TrueName);
8532 }
8533
8534 return std::make_pair(QualType(), StringRef());
8535 }
8536
8537 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
8538 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
8539 /// type do not count.
8540 static bool
isArithmeticArgumentPromotion(Sema & S,const ImplicitCastExpr * ICE)8541 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
8542 QualType From = ICE->getSubExpr()->getType();
8543 QualType To = ICE->getType();
8544 // It's an integer promotion if the destination type is the promoted
8545 // source type.
8546 if (ICE->getCastKind() == CK_IntegralCast &&
8547 From->isPromotableIntegerType() &&
8548 S.Context.getPromotedIntegerType(From) == To)
8549 return true;
8550 // Look through vector types, since we do default argument promotion for
8551 // those in OpenCL.
8552 if (const auto *VecTy = From->getAs<ExtVectorType>())
8553 From = VecTy->getElementType();
8554 if (const auto *VecTy = To->getAs<ExtVectorType>())
8555 To = VecTy->getElementType();
8556 // It's a floating promotion if the source type is a lower rank.
8557 return ICE->getCastKind() == CK_FloatingCast &&
8558 S.Context.getFloatingTypeOrder(From, To) < 0;
8559 }
8560
8561 bool
checkFormatExpr(const analyze_printf::PrintfSpecifier & FS,const char * StartSpecifier,unsigned SpecifierLen,const Expr * E)8562 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8563 const char *StartSpecifier,
8564 unsigned SpecifierLen,
8565 const Expr *E) {
8566 using namespace analyze_format_string;
8567 using namespace analyze_printf;
8568
8569 // Now type check the data expression that matches the
8570 // format specifier.
8571 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
8572 if (!AT.isValid())
8573 return true;
8574
8575 QualType ExprTy = E->getType();
8576 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
8577 ExprTy = TET->getUnderlyingExpr()->getType();
8578 }
8579
8580 // Diagnose attempts to print a boolean value as a character. Unlike other
8581 // -Wformat diagnostics, this is fine from a type perspective, but it still
8582 // doesn't make sense.
8583 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
8584 E->isKnownToHaveBooleanValue()) {
8585 const CharSourceRange &CSR =
8586 getSpecifierRange(StartSpecifier, SpecifierLen);
8587 SmallString<4> FSString;
8588 llvm::raw_svector_ostream os(FSString);
8589 FS.toString(os);
8590 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
8591 << FSString,
8592 E->getExprLoc(), false, CSR);
8593 return true;
8594 }
8595
8596 analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
8597 if (Match == analyze_printf::ArgType::Match)
8598 return true;
8599
8600 // Look through argument promotions for our error message's reported type.
8601 // This includes the integral and floating promotions, but excludes array
8602 // and function pointer decay (seeing that an argument intended to be a
8603 // string has type 'char [6]' is probably more confusing than 'char *') and
8604 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
8605 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
8606 if (isArithmeticArgumentPromotion(S, ICE)) {
8607 E = ICE->getSubExpr();
8608 ExprTy = E->getType();
8609
8610 // Check if we didn't match because of an implicit cast from a 'char'
8611 // or 'short' to an 'int'. This is done because printf is a varargs
8612 // function.
8613 if (ICE->getType() == S.Context.IntTy ||
8614 ICE->getType() == S.Context.UnsignedIntTy) {
8615 // All further checking is done on the subexpression
8616 const analyze_printf::ArgType::MatchKind ImplicitMatch =
8617 AT.matchesType(S.Context, ExprTy);
8618 if (ImplicitMatch == analyze_printf::ArgType::Match)
8619 return true;
8620 if (ImplicitMatch == ArgType::NoMatchPedantic ||
8621 ImplicitMatch == ArgType::NoMatchTypeConfusion)
8622 Match = ImplicitMatch;
8623 }
8624 }
8625 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
8626 // Special case for 'a', which has type 'int' in C.
8627 // Note, however, that we do /not/ want to treat multibyte constants like
8628 // 'MooV' as characters! This form is deprecated but still exists.
8629 if (ExprTy == S.Context.IntTy)
8630 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
8631 ExprTy = S.Context.CharTy;
8632 }
8633
8634 // Look through enums to their underlying type.
8635 bool IsEnum = false;
8636 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
8637 ExprTy = EnumTy->getDecl()->getIntegerType();
8638 IsEnum = true;
8639 }
8640
8641 // %C in an Objective-C context prints a unichar, not a wchar_t.
8642 // If the argument is an integer of some kind, believe the %C and suggest
8643 // a cast instead of changing the conversion specifier.
8644 QualType IntendedTy = ExprTy;
8645 if (isObjCContext() &&
8646 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
8647 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
8648 !ExprTy->isCharType()) {
8649 // 'unichar' is defined as a typedef of unsigned short, but we should
8650 // prefer using the typedef if it is visible.
8651 IntendedTy = S.Context.UnsignedShortTy;
8652
8653 // While we are here, check if the value is an IntegerLiteral that happens
8654 // to be within the valid range.
8655 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
8656 const llvm::APInt &V = IL->getValue();
8657 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
8658 return true;
8659 }
8660
8661 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
8662 Sema::LookupOrdinaryName);
8663 if (S.LookupName(Result, S.getCurScope())) {
8664 NamedDecl *ND = Result.getFoundDecl();
8665 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
8666 if (TD->getUnderlyingType() == IntendedTy)
8667 IntendedTy = S.Context.getTypedefType(TD);
8668 }
8669 }
8670 }
8671
8672 // Special-case some of Darwin's platform-independence types by suggesting
8673 // casts to primitive types that are known to be large enough.
8674 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
8675 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
8676 QualType CastTy;
8677 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
8678 if (!CastTy.isNull()) {
8679 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
8680 // (long in ASTContext). Only complain to pedants.
8681 if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
8682 (AT.isSizeT() || AT.isPtrdiffT()) &&
8683 AT.matchesType(S.Context, CastTy))
8684 Match = ArgType::NoMatchPedantic;
8685 IntendedTy = CastTy;
8686 ShouldNotPrintDirectly = true;
8687 }
8688 }
8689
8690 // We may be able to offer a FixItHint if it is a supported type.
8691 PrintfSpecifier fixedFS = FS;
8692 bool Success =
8693 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
8694
8695 if (Success) {
8696 // Get the fix string from the fixed format specifier
8697 SmallString<16> buf;
8698 llvm::raw_svector_ostream os(buf);
8699 fixedFS.toString(os);
8700
8701 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
8702
8703 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
8704 unsigned Diag;
8705 switch (Match) {
8706 case ArgType::Match: llvm_unreachable("expected non-matching");
8707 case ArgType::NoMatchPedantic:
8708 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8709 break;
8710 case ArgType::NoMatchTypeConfusion:
8711 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8712 break;
8713 case ArgType::NoMatch:
8714 Diag = diag::warn_format_conversion_argument_type_mismatch;
8715 break;
8716 }
8717
8718 // In this case, the specifier is wrong and should be changed to match
8719 // the argument.
8720 EmitFormatDiagnostic(S.PDiag(Diag)
8721 << AT.getRepresentativeTypeName(S.Context)
8722 << IntendedTy << IsEnum << E->getSourceRange(),
8723 E->getBeginLoc(),
8724 /*IsStringLocation*/ false, SpecRange,
8725 FixItHint::CreateReplacement(SpecRange, os.str()));
8726 } else {
8727 // The canonical type for formatting this value is different from the
8728 // actual type of the expression. (This occurs, for example, with Darwin's
8729 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
8730 // should be printed as 'long' for 64-bit compatibility.)
8731 // Rather than emitting a normal format/argument mismatch, we want to
8732 // add a cast to the recommended type (and correct the format string
8733 // if necessary).
8734 SmallString<16> CastBuf;
8735 llvm::raw_svector_ostream CastFix(CastBuf);
8736 CastFix << "(";
8737 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
8738 CastFix << ")";
8739
8740 SmallVector<FixItHint,4> Hints;
8741 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
8742 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
8743
8744 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
8745 // If there's already a cast present, just replace it.
8746 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
8747 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
8748
8749 } else if (!requiresParensToAddCast(E)) {
8750 // If the expression has high enough precedence,
8751 // just write the C-style cast.
8752 Hints.push_back(
8753 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8754 } else {
8755 // Otherwise, add parens around the expression as well as the cast.
8756 CastFix << "(";
8757 Hints.push_back(
8758 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8759
8760 SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
8761 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
8762 }
8763
8764 if (ShouldNotPrintDirectly) {
8765 // The expression has a type that should not be printed directly.
8766 // We extract the name from the typedef because we don't want to show
8767 // the underlying type in the diagnostic.
8768 StringRef Name;
8769 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
8770 Name = TypedefTy->getDecl()->getName();
8771 else
8772 Name = CastTyName;
8773 unsigned Diag = Match == ArgType::NoMatchPedantic
8774 ? diag::warn_format_argument_needs_cast_pedantic
8775 : diag::warn_format_argument_needs_cast;
8776 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
8777 << E->getSourceRange(),
8778 E->getBeginLoc(), /*IsStringLocation=*/false,
8779 SpecRange, Hints);
8780 } else {
8781 // In this case, the expression could be printed using a different
8782 // specifier, but we've decided that the specifier is probably correct
8783 // and we should cast instead. Just use the normal warning message.
8784 EmitFormatDiagnostic(
8785 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8786 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
8787 << E->getSourceRange(),
8788 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
8789 }
8790 }
8791 } else {
8792 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
8793 SpecifierLen);
8794 // Since the warning for passing non-POD types to variadic functions
8795 // was deferred until now, we emit a warning for non-POD
8796 // arguments here.
8797 switch (S.isValidVarArgType(ExprTy)) {
8798 case Sema::VAK_Valid:
8799 case Sema::VAK_ValidInCXX11: {
8800 unsigned Diag;
8801 switch (Match) {
8802 case ArgType::Match: llvm_unreachable("expected non-matching");
8803 case ArgType::NoMatchPedantic:
8804 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8805 break;
8806 case ArgType::NoMatchTypeConfusion:
8807 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8808 break;
8809 case ArgType::NoMatch:
8810 Diag = diag::warn_format_conversion_argument_type_mismatch;
8811 break;
8812 }
8813
8814 EmitFormatDiagnostic(
8815 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
8816 << IsEnum << CSR << E->getSourceRange(),
8817 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8818 break;
8819 }
8820 case Sema::VAK_Undefined:
8821 case Sema::VAK_MSVCUndefined:
8822 EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
8823 << S.getLangOpts().CPlusPlus11 << ExprTy
8824 << CallType
8825 << AT.getRepresentativeTypeName(S.Context) << CSR
8826 << E->getSourceRange(),
8827 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8828 checkForCStrMembers(AT, E);
8829 break;
8830
8831 case Sema::VAK_Invalid:
8832 if (ExprTy->isObjCObjectType())
8833 EmitFormatDiagnostic(
8834 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
8835 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
8836 << AT.getRepresentativeTypeName(S.Context) << CSR
8837 << E->getSourceRange(),
8838 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8839 else
8840 // FIXME: If this is an initializer list, suggest removing the braces
8841 // or inserting a cast to the target type.
8842 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
8843 << isa<InitListExpr>(E) << ExprTy << CallType
8844 << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
8845 break;
8846 }
8847
8848 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
8849 "format string specifier index out of range");
8850 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
8851 }
8852
8853 return true;
8854 }
8855
8856 //===--- CHECK: Scanf format string checking ------------------------------===//
8857
8858 namespace {
8859
8860 class CheckScanfHandler : public CheckFormatHandler {
8861 public:
CheckScanfHandler(Sema & s,const FormatStringLiteral * fexpr,const Expr * origFormatExpr,Sema::FormatStringType type,unsigned firstDataArg,unsigned numDataArgs,const char * beg,bool hasVAListArg,ArrayRef<const Expr * > Args,unsigned formatIdx,bool inFunctionCall,Sema::VariadicCallType CallType,llvm::SmallBitVector & CheckedVarArgs,UncoveredArgHandler & UncoveredArg)8862 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
8863 const Expr *origFormatExpr, Sema::FormatStringType type,
8864 unsigned firstDataArg, unsigned numDataArgs,
8865 const char *beg, bool hasVAListArg,
8866 ArrayRef<const Expr *> Args, unsigned formatIdx,
8867 bool inFunctionCall, Sema::VariadicCallType CallType,
8868 llvm::SmallBitVector &CheckedVarArgs,
8869 UncoveredArgHandler &UncoveredArg)
8870 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8871 numDataArgs, beg, hasVAListArg, Args, formatIdx,
8872 inFunctionCall, CallType, CheckedVarArgs,
8873 UncoveredArg) {}
8874
8875 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
8876 const char *startSpecifier,
8877 unsigned specifierLen) override;
8878
8879 bool HandleInvalidScanfConversionSpecifier(
8880 const analyze_scanf::ScanfSpecifier &FS,
8881 const char *startSpecifier,
8882 unsigned specifierLen) override;
8883
8884 void HandleIncompleteScanList(const char *start, const char *end) override;
8885 };
8886
8887 } // namespace
8888
HandleIncompleteScanList(const char * start,const char * end)8889 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
8890 const char *end) {
8891 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
8892 getLocationOfByte(end), /*IsStringLocation*/true,
8893 getSpecifierRange(start, end - start));
8894 }
8895
HandleInvalidScanfConversionSpecifier(const analyze_scanf::ScanfSpecifier & FS,const char * startSpecifier,unsigned specifierLen)8896 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
8897 const analyze_scanf::ScanfSpecifier &FS,
8898 const char *startSpecifier,
8899 unsigned specifierLen) {
8900 const analyze_scanf::ScanfConversionSpecifier &CS =
8901 FS.getConversionSpecifier();
8902
8903 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8904 getLocationOfByte(CS.getStart()),
8905 startSpecifier, specifierLen,
8906 CS.getStart(), CS.getLength());
8907 }
8908
HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier & FS,const char * startSpecifier,unsigned specifierLen)8909 bool CheckScanfHandler::HandleScanfSpecifier(
8910 const analyze_scanf::ScanfSpecifier &FS,
8911 const char *startSpecifier,
8912 unsigned specifierLen) {
8913 using namespace analyze_scanf;
8914 using namespace analyze_format_string;
8915
8916 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
8917
8918 // Handle case where '%' and '*' don't consume an argument. These shouldn't
8919 // be used to decide if we are using positional arguments consistently.
8920 if (FS.consumesDataArgument()) {
8921 if (atFirstArg) {
8922 atFirstArg = false;
8923 usesPositionalArgs = FS.usesPositionalArg();
8924 }
8925 else if (usesPositionalArgs != FS.usesPositionalArg()) {
8926 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8927 startSpecifier, specifierLen);
8928 return false;
8929 }
8930 }
8931
8932 // Check if the field with is non-zero.
8933 const OptionalAmount &Amt = FS.getFieldWidth();
8934 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
8935 if (Amt.getConstantAmount() == 0) {
8936 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
8937 Amt.getConstantLength());
8938 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
8939 getLocationOfByte(Amt.getStart()),
8940 /*IsStringLocation*/true, R,
8941 FixItHint::CreateRemoval(R));
8942 }
8943 }
8944
8945 if (!FS.consumesDataArgument()) {
8946 // FIXME: Technically specifying a precision or field width here
8947 // makes no sense. Worth issuing a warning at some point.
8948 return true;
8949 }
8950
8951 // Consume the argument.
8952 unsigned argIndex = FS.getArgIndex();
8953 if (argIndex < NumDataArgs) {
8954 // The check to see if the argIndex is valid will come later.
8955 // We set the bit here because we may exit early from this
8956 // function if we encounter some other error.
8957 CoveredArgs.set(argIndex);
8958 }
8959
8960 // Check the length modifier is valid with the given conversion specifier.
8961 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
8962 S.getLangOpts()))
8963 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8964 diag::warn_format_nonsensical_length);
8965 else if (!FS.hasStandardLengthModifier())
8966 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8967 else if (!FS.hasStandardLengthConversionCombination())
8968 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8969 diag::warn_format_non_standard_conversion_spec);
8970
8971 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8972 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8973
8974 // The remaining checks depend on the data arguments.
8975 if (HasVAListArg)
8976 return true;
8977
8978 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8979 return false;
8980
8981 // Check that the argument type matches the format specifier.
8982 const Expr *Ex = getDataArg(argIndex);
8983 if (!Ex)
8984 return true;
8985
8986 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
8987
8988 if (!AT.isValid()) {
8989 return true;
8990 }
8991
8992 analyze_format_string::ArgType::MatchKind Match =
8993 AT.matchesType(S.Context, Ex->getType());
8994 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
8995 if (Match == analyze_format_string::ArgType::Match)
8996 return true;
8997
8998 ScanfSpecifier fixedFS = FS;
8999 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
9000 S.getLangOpts(), S.Context);
9001
9002 unsigned Diag =
9003 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9004 : diag::warn_format_conversion_argument_type_mismatch;
9005
9006 if (Success) {
9007 // Get the fix string from the fixed format specifier.
9008 SmallString<128> buf;
9009 llvm::raw_svector_ostream os(buf);
9010 fixedFS.toString(os);
9011
9012 EmitFormatDiagnostic(
9013 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
9014 << Ex->getType() << false << Ex->getSourceRange(),
9015 Ex->getBeginLoc(),
9016 /*IsStringLocation*/ false,
9017 getSpecifierRange(startSpecifier, specifierLen),
9018 FixItHint::CreateReplacement(
9019 getSpecifierRange(startSpecifier, specifierLen), os.str()));
9020 } else {
9021 EmitFormatDiagnostic(S.PDiag(Diag)
9022 << AT.getRepresentativeTypeName(S.Context)
9023 << Ex->getType() << false << Ex->getSourceRange(),
9024 Ex->getBeginLoc(),
9025 /*IsStringLocation*/ false,
9026 getSpecifierRange(startSpecifier, specifierLen));
9027 }
9028
9029 return true;
9030 }
9031
CheckFormatString(Sema & S,const FormatStringLiteral * FExpr,const Expr * OrigFormatExpr,ArrayRef<const Expr * > Args,bool HasVAListArg,unsigned format_idx,unsigned firstDataArg,Sema::FormatStringType Type,bool inFunctionCall,Sema::VariadicCallType CallType,llvm::SmallBitVector & CheckedVarArgs,UncoveredArgHandler & UncoveredArg,bool IgnoreStringsWithoutSpecifiers)9032 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
9033 const Expr *OrigFormatExpr,
9034 ArrayRef<const Expr *> Args,
9035 bool HasVAListArg, unsigned format_idx,
9036 unsigned firstDataArg,
9037 Sema::FormatStringType Type,
9038 bool inFunctionCall,
9039 Sema::VariadicCallType CallType,
9040 llvm::SmallBitVector &CheckedVarArgs,
9041 UncoveredArgHandler &UncoveredArg,
9042 bool IgnoreStringsWithoutSpecifiers) {
9043 // CHECK: is the format string a wide literal?
9044 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
9045 CheckFormatHandler::EmitFormatDiagnostic(
9046 S, inFunctionCall, Args[format_idx],
9047 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
9048 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9049 return;
9050 }
9051
9052 // Str - The format string. NOTE: this is NOT null-terminated!
9053 StringRef StrRef = FExpr->getString();
9054 const char *Str = StrRef.data();
9055 // Account for cases where the string literal is truncated in a declaration.
9056 const ConstantArrayType *T =
9057 S.Context.getAsConstantArrayType(FExpr->getType());
9058 assert(T && "String literal not of constant array type!");
9059 size_t TypeSize = T->getSize().getZExtValue();
9060 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9061 const unsigned numDataArgs = Args.size() - firstDataArg;
9062
9063 if (IgnoreStringsWithoutSpecifiers &&
9064 !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
9065 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
9066 return;
9067
9068 // Emit a warning if the string literal is truncated and does not contain an
9069 // embedded null character.
9070 if (TypeSize <= StrRef.size() &&
9071 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
9072 CheckFormatHandler::EmitFormatDiagnostic(
9073 S, inFunctionCall, Args[format_idx],
9074 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
9075 FExpr->getBeginLoc(),
9076 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
9077 return;
9078 }
9079
9080 // CHECK: empty format string?
9081 if (StrLen == 0 && numDataArgs > 0) {
9082 CheckFormatHandler::EmitFormatDiagnostic(
9083 S, inFunctionCall, Args[format_idx],
9084 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
9085 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9086 return;
9087 }
9088
9089 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
9090 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
9091 Type == Sema::FST_OSTrace) {
9092 CheckPrintfHandler H(
9093 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
9094 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
9095 HasVAListArg, Args, format_idx, inFunctionCall, CallType,
9096 CheckedVarArgs, UncoveredArg);
9097
9098 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
9099 S.getLangOpts(),
9100 S.Context.getTargetInfo(),
9101 Type == Sema::FST_FreeBSDKPrintf))
9102 H.DoneProcessing();
9103 } else if (Type == Sema::FST_Scanf) {
9104 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
9105 numDataArgs, Str, HasVAListArg, Args, format_idx,
9106 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
9107
9108 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
9109 S.getLangOpts(),
9110 S.Context.getTargetInfo()))
9111 H.DoneProcessing();
9112 } // TODO: handle other formats
9113 }
9114
FormatStringHasSArg(const StringLiteral * FExpr)9115 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
9116 // Str - The format string. NOTE: this is NOT null-terminated!
9117 StringRef StrRef = FExpr->getString();
9118 const char *Str = StrRef.data();
9119 // Account for cases where the string literal is truncated in a declaration.
9120 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
9121 assert(T && "String literal not of constant array type!");
9122 size_t TypeSize = T->getSize().getZExtValue();
9123 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9124 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
9125 getLangOpts(),
9126 Context.getTargetInfo());
9127 }
9128
9129 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
9130
9131 // Returns the related absolute value function that is larger, of 0 if one
9132 // does not exist.
getLargerAbsoluteValueFunction(unsigned AbsFunction)9133 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
9134 switch (AbsFunction) {
9135 default:
9136 return 0;
9137
9138 case Builtin::BI__builtin_abs:
9139 return Builtin::BI__builtin_labs;
9140 case Builtin::BI__builtin_labs:
9141 return Builtin::BI__builtin_llabs;
9142 case Builtin::BI__builtin_llabs:
9143 return 0;
9144
9145 case Builtin::BI__builtin_fabsf:
9146 return Builtin::BI__builtin_fabs;
9147 case Builtin::BI__builtin_fabs:
9148 return Builtin::BI__builtin_fabsl;
9149 case Builtin::BI__builtin_fabsl:
9150 return 0;
9151
9152 case Builtin::BI__builtin_cabsf:
9153 return Builtin::BI__builtin_cabs;
9154 case Builtin::BI__builtin_cabs:
9155 return Builtin::BI__builtin_cabsl;
9156 case Builtin::BI__builtin_cabsl:
9157 return 0;
9158
9159 case Builtin::BIabs:
9160 return Builtin::BIlabs;
9161 case Builtin::BIlabs:
9162 return Builtin::BIllabs;
9163 case Builtin::BIllabs:
9164 return 0;
9165
9166 case Builtin::BIfabsf:
9167 return Builtin::BIfabs;
9168 case Builtin::BIfabs:
9169 return Builtin::BIfabsl;
9170 case Builtin::BIfabsl:
9171 return 0;
9172
9173 case Builtin::BIcabsf:
9174 return Builtin::BIcabs;
9175 case Builtin::BIcabs:
9176 return Builtin::BIcabsl;
9177 case Builtin::BIcabsl:
9178 return 0;
9179 }
9180 }
9181
9182 // Returns the argument type of the absolute value function.
getAbsoluteValueArgumentType(ASTContext & Context,unsigned AbsType)9183 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
9184 unsigned AbsType) {
9185 if (AbsType == 0)
9186 return QualType();
9187
9188 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
9189 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
9190 if (Error != ASTContext::GE_None)
9191 return QualType();
9192
9193 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
9194 if (!FT)
9195 return QualType();
9196
9197 if (FT->getNumParams() != 1)
9198 return QualType();
9199
9200 return FT->getParamType(0);
9201 }
9202
9203 // Returns the best absolute value function, or zero, based on type and
9204 // current absolute value function.
getBestAbsFunction(ASTContext & Context,QualType ArgType,unsigned AbsFunctionKind)9205 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
9206 unsigned AbsFunctionKind) {
9207 unsigned BestKind = 0;
9208 uint64_t ArgSize = Context.getTypeSize(ArgType);
9209 for (unsigned Kind = AbsFunctionKind; Kind != 0;
9210 Kind = getLargerAbsoluteValueFunction(Kind)) {
9211 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
9212 if (Context.getTypeSize(ParamType) >= ArgSize) {
9213 if (BestKind == 0)
9214 BestKind = Kind;
9215 else if (Context.hasSameType(ParamType, ArgType)) {
9216 BestKind = Kind;
9217 break;
9218 }
9219 }
9220 }
9221 return BestKind;
9222 }
9223
9224 enum AbsoluteValueKind {
9225 AVK_Integer,
9226 AVK_Floating,
9227 AVK_Complex
9228 };
9229
getAbsoluteValueKind(QualType T)9230 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
9231 if (T->isIntegralOrEnumerationType())
9232 return AVK_Integer;
9233 if (T->isRealFloatingType())
9234 return AVK_Floating;
9235 if (T->isAnyComplexType())
9236 return AVK_Complex;
9237
9238 llvm_unreachable("Type not integer, floating, or complex");
9239 }
9240
9241 // Changes the absolute value function to a different type. Preserves whether
9242 // the function is a builtin.
changeAbsFunction(unsigned AbsKind,AbsoluteValueKind ValueKind)9243 static unsigned changeAbsFunction(unsigned AbsKind,
9244 AbsoluteValueKind ValueKind) {
9245 switch (ValueKind) {
9246 case AVK_Integer:
9247 switch (AbsKind) {
9248 default:
9249 return 0;
9250 case Builtin::BI__builtin_fabsf:
9251 case Builtin::BI__builtin_fabs:
9252 case Builtin::BI__builtin_fabsl:
9253 case Builtin::BI__builtin_cabsf:
9254 case Builtin::BI__builtin_cabs:
9255 case Builtin::BI__builtin_cabsl:
9256 return Builtin::BI__builtin_abs;
9257 case Builtin::BIfabsf:
9258 case Builtin::BIfabs:
9259 case Builtin::BIfabsl:
9260 case Builtin::BIcabsf:
9261 case Builtin::BIcabs:
9262 case Builtin::BIcabsl:
9263 return Builtin::BIabs;
9264 }
9265 case AVK_Floating:
9266 switch (AbsKind) {
9267 default:
9268 return 0;
9269 case Builtin::BI__builtin_abs:
9270 case Builtin::BI__builtin_labs:
9271 case Builtin::BI__builtin_llabs:
9272 case Builtin::BI__builtin_cabsf:
9273 case Builtin::BI__builtin_cabs:
9274 case Builtin::BI__builtin_cabsl:
9275 return Builtin::BI__builtin_fabsf;
9276 case Builtin::BIabs:
9277 case Builtin::BIlabs:
9278 case Builtin::BIllabs:
9279 case Builtin::BIcabsf:
9280 case Builtin::BIcabs:
9281 case Builtin::BIcabsl:
9282 return Builtin::BIfabsf;
9283 }
9284 case AVK_Complex:
9285 switch (AbsKind) {
9286 default:
9287 return 0;
9288 case Builtin::BI__builtin_abs:
9289 case Builtin::BI__builtin_labs:
9290 case Builtin::BI__builtin_llabs:
9291 case Builtin::BI__builtin_fabsf:
9292 case Builtin::BI__builtin_fabs:
9293 case Builtin::BI__builtin_fabsl:
9294 return Builtin::BI__builtin_cabsf;
9295 case Builtin::BIabs:
9296 case Builtin::BIlabs:
9297 case Builtin::BIllabs:
9298 case Builtin::BIfabsf:
9299 case Builtin::BIfabs:
9300 case Builtin::BIfabsl:
9301 return Builtin::BIcabsf;
9302 }
9303 }
9304 llvm_unreachable("Unable to convert function");
9305 }
9306
getAbsoluteValueFunctionKind(const FunctionDecl * FDecl)9307 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
9308 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
9309 if (!FnInfo)
9310 return 0;
9311
9312 switch (FDecl->getBuiltinID()) {
9313 default:
9314 return 0;
9315 case Builtin::BI__builtin_abs:
9316 case Builtin::BI__builtin_fabs:
9317 case Builtin::BI__builtin_fabsf:
9318 case Builtin::BI__builtin_fabsl:
9319 case Builtin::BI__builtin_labs:
9320 case Builtin::BI__builtin_llabs:
9321 case Builtin::BI__builtin_cabs:
9322 case Builtin::BI__builtin_cabsf:
9323 case Builtin::BI__builtin_cabsl:
9324 case Builtin::BIabs:
9325 case Builtin::BIlabs:
9326 case Builtin::BIllabs:
9327 case Builtin::BIfabs:
9328 case Builtin::BIfabsf:
9329 case Builtin::BIfabsl:
9330 case Builtin::BIcabs:
9331 case Builtin::BIcabsf:
9332 case Builtin::BIcabsl:
9333 return FDecl->getBuiltinID();
9334 }
9335 llvm_unreachable("Unknown Builtin type");
9336 }
9337
9338 // If the replacement is valid, emit a note with replacement function.
9339 // Additionally, suggest including the proper header if not already included.
emitReplacement(Sema & S,SourceLocation Loc,SourceRange Range,unsigned AbsKind,QualType ArgType)9340 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
9341 unsigned AbsKind, QualType ArgType) {
9342 bool EmitHeaderHint = true;
9343 const char *HeaderName = nullptr;
9344 const char *FunctionName = nullptr;
9345 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
9346 FunctionName = "std::abs";
9347 if (ArgType->isIntegralOrEnumerationType()) {
9348 HeaderName = "cstdlib";
9349 } else if (ArgType->isRealFloatingType()) {
9350 HeaderName = "cmath";
9351 } else {
9352 llvm_unreachable("Invalid Type");
9353 }
9354
9355 // Lookup all std::abs
9356 if (NamespaceDecl *Std = S.getStdNamespace()) {
9357 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
9358 R.suppressDiagnostics();
9359 S.LookupQualifiedName(R, Std);
9360
9361 for (const auto *I : R) {
9362 const FunctionDecl *FDecl = nullptr;
9363 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
9364 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
9365 } else {
9366 FDecl = dyn_cast<FunctionDecl>(I);
9367 }
9368 if (!FDecl)
9369 continue;
9370
9371 // Found std::abs(), check that they are the right ones.
9372 if (FDecl->getNumParams() != 1)
9373 continue;
9374
9375 // Check that the parameter type can handle the argument.
9376 QualType ParamType = FDecl->getParamDecl(0)->getType();
9377 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
9378 S.Context.getTypeSize(ArgType) <=
9379 S.Context.getTypeSize(ParamType)) {
9380 // Found a function, don't need the header hint.
9381 EmitHeaderHint = false;
9382 break;
9383 }
9384 }
9385 }
9386 } else {
9387 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
9388 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
9389
9390 if (HeaderName) {
9391 DeclarationName DN(&S.Context.Idents.get(FunctionName));
9392 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
9393 R.suppressDiagnostics();
9394 S.LookupName(R, S.getCurScope());
9395
9396 if (R.isSingleResult()) {
9397 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
9398 if (FD && FD->getBuiltinID() == AbsKind) {
9399 EmitHeaderHint = false;
9400 } else {
9401 return;
9402 }
9403 } else if (!R.empty()) {
9404 return;
9405 }
9406 }
9407 }
9408
9409 S.Diag(Loc, diag::note_replace_abs_function)
9410 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
9411
9412 if (!HeaderName)
9413 return;
9414
9415 if (!EmitHeaderHint)
9416 return;
9417
9418 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
9419 << FunctionName;
9420 }
9421
9422 template <std::size_t StrLen>
IsStdFunction(const FunctionDecl * FDecl,const char (& Str)[StrLen])9423 static bool IsStdFunction(const FunctionDecl *FDecl,
9424 const char (&Str)[StrLen]) {
9425 if (!FDecl)
9426 return false;
9427 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
9428 return false;
9429 if (!FDecl->isInStdNamespace())
9430 return false;
9431
9432 return true;
9433 }
9434
9435 // Warn when using the wrong abs() function.
CheckAbsoluteValueFunction(const CallExpr * Call,const FunctionDecl * FDecl)9436 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
9437 const FunctionDecl *FDecl) {
9438 if (Call->getNumArgs() != 1)
9439 return;
9440
9441 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
9442 bool IsStdAbs = IsStdFunction(FDecl, "abs");
9443 if (AbsKind == 0 && !IsStdAbs)
9444 return;
9445
9446 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9447 QualType ParamType = Call->getArg(0)->getType();
9448
9449 // Unsigned types cannot be negative. Suggest removing the absolute value
9450 // function call.
9451 if (ArgType->isUnsignedIntegerType()) {
9452 const char *FunctionName =
9453 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
9454 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
9455 Diag(Call->getExprLoc(), diag::note_remove_abs)
9456 << FunctionName
9457 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
9458 return;
9459 }
9460
9461 // Taking the absolute value of a pointer is very suspicious, they probably
9462 // wanted to index into an array, dereference a pointer, call a function, etc.
9463 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
9464 unsigned DiagType = 0;
9465 if (ArgType->isFunctionType())
9466 DiagType = 1;
9467 else if (ArgType->isArrayType())
9468 DiagType = 2;
9469
9470 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
9471 return;
9472 }
9473
9474 // std::abs has overloads which prevent most of the absolute value problems
9475 // from occurring.
9476 if (IsStdAbs)
9477 return;
9478
9479 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
9480 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
9481
9482 // The argument and parameter are the same kind. Check if they are the right
9483 // size.
9484 if (ArgValueKind == ParamValueKind) {
9485 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
9486 return;
9487
9488 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
9489 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
9490 << FDecl << ArgType << ParamType;
9491
9492 if (NewAbsKind == 0)
9493 return;
9494
9495 emitReplacement(*this, Call->getExprLoc(),
9496 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9497 return;
9498 }
9499
9500 // ArgValueKind != ParamValueKind
9501 // The wrong type of absolute value function was used. Attempt to find the
9502 // proper one.
9503 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
9504 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
9505 if (NewAbsKind == 0)
9506 return;
9507
9508 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
9509 << FDecl << ParamValueKind << ArgValueKind;
9510
9511 emitReplacement(*this, Call->getExprLoc(),
9512 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9513 }
9514
9515 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
CheckMaxUnsignedZero(const CallExpr * Call,const FunctionDecl * FDecl)9516 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
9517 const FunctionDecl *FDecl) {
9518 if (!Call || !FDecl) return;
9519
9520 // Ignore template specializations and macros.
9521 if (inTemplateInstantiation()) return;
9522 if (Call->getExprLoc().isMacroID()) return;
9523
9524 // Only care about the one template argument, two function parameter std::max
9525 if (Call->getNumArgs() != 2) return;
9526 if (!IsStdFunction(FDecl, "max")) return;
9527 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
9528 if (!ArgList) return;
9529 if (ArgList->size() != 1) return;
9530
9531 // Check that template type argument is unsigned integer.
9532 const auto& TA = ArgList->get(0);
9533 if (TA.getKind() != TemplateArgument::Type) return;
9534 QualType ArgType = TA.getAsType();
9535 if (!ArgType->isUnsignedIntegerType()) return;
9536
9537 // See if either argument is a literal zero.
9538 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
9539 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
9540 if (!MTE) return false;
9541 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
9542 if (!Num) return false;
9543 if (Num->getValue() != 0) return false;
9544 return true;
9545 };
9546
9547 const Expr *FirstArg = Call->getArg(0);
9548 const Expr *SecondArg = Call->getArg(1);
9549 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
9550 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
9551
9552 // Only warn when exactly one argument is zero.
9553 if (IsFirstArgZero == IsSecondArgZero) return;
9554
9555 SourceRange FirstRange = FirstArg->getSourceRange();
9556 SourceRange SecondRange = SecondArg->getSourceRange();
9557
9558 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
9559
9560 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
9561 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
9562
9563 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
9564 SourceRange RemovalRange;
9565 if (IsFirstArgZero) {
9566 RemovalRange = SourceRange(FirstRange.getBegin(),
9567 SecondRange.getBegin().getLocWithOffset(-1));
9568 } else {
9569 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
9570 SecondRange.getEnd());
9571 }
9572
9573 Diag(Call->getExprLoc(), diag::note_remove_max_call)
9574 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
9575 << FixItHint::CreateRemoval(RemovalRange);
9576 }
9577
9578 //===--- CHECK: Standard memory functions ---------------------------------===//
9579
9580 /// Takes the expression passed to the size_t parameter of functions
9581 /// such as memcmp, strncat, etc and warns if it's a comparison.
9582 ///
9583 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
CheckMemorySizeofForComparison(Sema & S,const Expr * E,IdentifierInfo * FnName,SourceLocation FnLoc,SourceLocation RParenLoc)9584 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
9585 IdentifierInfo *FnName,
9586 SourceLocation FnLoc,
9587 SourceLocation RParenLoc) {
9588 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
9589 if (!Size)
9590 return false;
9591
9592 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
9593 if (!Size->isComparisonOp() && !Size->isLogicalOp())
9594 return false;
9595
9596 SourceRange SizeRange = Size->getSourceRange();
9597 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
9598 << SizeRange << FnName;
9599 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
9600 << FnName
9601 << FixItHint::CreateInsertion(
9602 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
9603 << FixItHint::CreateRemoval(RParenLoc);
9604 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
9605 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
9606 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
9607 ")");
9608
9609 return true;
9610 }
9611
9612 /// Determine whether the given type is or contains a dynamic class type
9613 /// (e.g., whether it has a vtable).
getContainedDynamicClass(QualType T,bool & IsContained)9614 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
9615 bool &IsContained) {
9616 // Look through array types while ignoring qualifiers.
9617 const Type *Ty = T->getBaseElementTypeUnsafe();
9618 IsContained = false;
9619
9620 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
9621 RD = RD ? RD->getDefinition() : nullptr;
9622 if (!RD || RD->isInvalidDecl())
9623 return nullptr;
9624
9625 if (RD->isDynamicClass())
9626 return RD;
9627
9628 // Check all the fields. If any bases were dynamic, the class is dynamic.
9629 // It's impossible for a class to transitively contain itself by value, so
9630 // infinite recursion is impossible.
9631 for (auto *FD : RD->fields()) {
9632 bool SubContained;
9633 if (const CXXRecordDecl *ContainedRD =
9634 getContainedDynamicClass(FD->getType(), SubContained)) {
9635 IsContained = true;
9636 return ContainedRD;
9637 }
9638 }
9639
9640 return nullptr;
9641 }
9642
getAsSizeOfExpr(const Expr * E)9643 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
9644 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
9645 if (Unary->getKind() == UETT_SizeOf)
9646 return Unary;
9647 return nullptr;
9648 }
9649
9650 /// If E is a sizeof expression, returns its argument expression,
9651 /// otherwise returns NULL.
getSizeOfExprArg(const Expr * E)9652 static const Expr *getSizeOfExprArg(const Expr *E) {
9653 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
9654 if (!SizeOf->isArgumentType())
9655 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
9656 return nullptr;
9657 }
9658
9659 /// If E is a sizeof expression, returns its argument type.
getSizeOfArgType(const Expr * E)9660 static QualType getSizeOfArgType(const Expr *E) {
9661 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
9662 return SizeOf->getTypeOfArgument();
9663 return QualType();
9664 }
9665
9666 namespace {
9667
9668 struct SearchNonTrivialToInitializeField
9669 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
9670 using Super =
9671 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
9672
SearchNonTrivialToInitializeField__anon33aba9e81611::SearchNonTrivialToInitializeField9673 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
9674
visitWithKind__anon33aba9e81611::SearchNonTrivialToInitializeField9675 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
9676 SourceLocation SL) {
9677 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9678 asDerived().visitArray(PDIK, AT, SL);
9679 return;
9680 }
9681
9682 Super::visitWithKind(PDIK, FT, SL);
9683 }
9684
visitARCStrong__anon33aba9e81611::SearchNonTrivialToInitializeField9685 void visitARCStrong(QualType FT, SourceLocation SL) {
9686 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9687 }
visitARCWeak__anon33aba9e81611::SearchNonTrivialToInitializeField9688 void visitARCWeak(QualType FT, SourceLocation SL) {
9689 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9690 }
visitStruct__anon33aba9e81611::SearchNonTrivialToInitializeField9691 void visitStruct(QualType FT, SourceLocation SL) {
9692 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
9693 visit(FD->getType(), FD->getLocation());
9694 }
visitArray__anon33aba9e81611::SearchNonTrivialToInitializeField9695 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
9696 const ArrayType *AT, SourceLocation SL) {
9697 visit(getContext().getBaseElementType(AT), SL);
9698 }
visitTrivial__anon33aba9e81611::SearchNonTrivialToInitializeField9699 void visitTrivial(QualType FT, SourceLocation SL) {}
9700
diag__anon33aba9e81611::SearchNonTrivialToInitializeField9701 static void diag(QualType RT, const Expr *E, Sema &S) {
9702 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
9703 }
9704
getContext__anon33aba9e81611::SearchNonTrivialToInitializeField9705 ASTContext &getContext() { return S.getASTContext(); }
9706
9707 const Expr *E;
9708 Sema &S;
9709 };
9710
9711 struct SearchNonTrivialToCopyField
9712 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
9713 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
9714
SearchNonTrivialToCopyField__anon33aba9e81611::SearchNonTrivialToCopyField9715 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
9716
visitWithKind__anon33aba9e81611::SearchNonTrivialToCopyField9717 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
9718 SourceLocation SL) {
9719 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9720 asDerived().visitArray(PCK, AT, SL);
9721 return;
9722 }
9723
9724 Super::visitWithKind(PCK, FT, SL);
9725 }
9726
visitARCStrong__anon33aba9e81611::SearchNonTrivialToCopyField9727 void visitARCStrong(QualType FT, SourceLocation SL) {
9728 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9729 }
visitARCWeak__anon33aba9e81611::SearchNonTrivialToCopyField9730 void visitARCWeak(QualType FT, SourceLocation SL) {
9731 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9732 }
visitStruct__anon33aba9e81611::SearchNonTrivialToCopyField9733 void visitStruct(QualType FT, SourceLocation SL) {
9734 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
9735 visit(FD->getType(), FD->getLocation());
9736 }
visitArray__anon33aba9e81611::SearchNonTrivialToCopyField9737 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
9738 SourceLocation SL) {
9739 visit(getContext().getBaseElementType(AT), SL);
9740 }
preVisit__anon33aba9e81611::SearchNonTrivialToCopyField9741 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
9742 SourceLocation SL) {}
visitTrivial__anon33aba9e81611::SearchNonTrivialToCopyField9743 void visitTrivial(QualType FT, SourceLocation SL) {}
visitVolatileTrivial__anon33aba9e81611::SearchNonTrivialToCopyField9744 void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
9745
diag__anon33aba9e81611::SearchNonTrivialToCopyField9746 static void diag(QualType RT, const Expr *E, Sema &S) {
9747 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
9748 }
9749
getContext__anon33aba9e81611::SearchNonTrivialToCopyField9750 ASTContext &getContext() { return S.getASTContext(); }
9751
9752 const Expr *E;
9753 Sema &S;
9754 };
9755
9756 }
9757
9758 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
doesExprLikelyComputeSize(const Expr * SizeofExpr)9759 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
9760 SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
9761
9762 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
9763 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
9764 return false;
9765
9766 return doesExprLikelyComputeSize(BO->getLHS()) ||
9767 doesExprLikelyComputeSize(BO->getRHS());
9768 }
9769
9770 return getAsSizeOfExpr(SizeofExpr) != nullptr;
9771 }
9772
9773 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
9774 ///
9775 /// \code
9776 /// #define MACRO 0
9777 /// foo(MACRO);
9778 /// foo(0);
9779 /// \endcode
9780 ///
9781 /// This should return true for the first call to foo, but not for the second
9782 /// (regardless of whether foo is a macro or function).
isArgumentExpandedFromMacro(SourceManager & SM,SourceLocation CallLoc,SourceLocation ArgLoc)9783 static bool isArgumentExpandedFromMacro(SourceManager &SM,
9784 SourceLocation CallLoc,
9785 SourceLocation ArgLoc) {
9786 if (!CallLoc.isMacroID())
9787 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
9788
9789 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
9790 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
9791 }
9792
9793 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
9794 /// last two arguments transposed.
CheckMemaccessSize(Sema & S,unsigned BId,const CallExpr * Call)9795 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
9796 if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
9797 return;
9798
9799 const Expr *SizeArg =
9800 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
9801
9802 auto isLiteralZero = [](const Expr *E) {
9803 return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
9804 };
9805
9806 // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
9807 SourceLocation CallLoc = Call->getRParenLoc();
9808 SourceManager &SM = S.getSourceManager();
9809 if (isLiteralZero(SizeArg) &&
9810 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
9811
9812 SourceLocation DiagLoc = SizeArg->getExprLoc();
9813
9814 // Some platforms #define bzero to __builtin_memset. See if this is the
9815 // case, and if so, emit a better diagnostic.
9816 if (BId == Builtin::BIbzero ||
9817 (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
9818 CallLoc, SM, S.getLangOpts()) == "bzero")) {
9819 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
9820 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
9821 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
9822 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
9823 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
9824 }
9825 return;
9826 }
9827
9828 // If the second argument to a memset is a sizeof expression and the third
9829 // isn't, this is also likely an error. This should catch
9830 // 'memset(buf, sizeof(buf), 0xff)'.
9831 if (BId == Builtin::BImemset &&
9832 doesExprLikelyComputeSize(Call->getArg(1)) &&
9833 !doesExprLikelyComputeSize(Call->getArg(2))) {
9834 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
9835 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
9836 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
9837 return;
9838 }
9839 }
9840
9841 /// Check for dangerous or invalid arguments to memset().
9842 ///
9843 /// This issues warnings on known problematic, dangerous or unspecified
9844 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
9845 /// function calls.
9846 ///
9847 /// \param Call The call expression to diagnose.
CheckMemaccessArguments(const CallExpr * Call,unsigned BId,IdentifierInfo * FnName)9848 void Sema::CheckMemaccessArguments(const CallExpr *Call,
9849 unsigned BId,
9850 IdentifierInfo *FnName) {
9851 assert(BId != 0);
9852
9853 // It is possible to have a non-standard definition of memset. Validate
9854 // we have enough arguments, and if not, abort further checking.
9855 unsigned ExpectedNumArgs =
9856 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
9857 if (Call->getNumArgs() < ExpectedNumArgs)
9858 return;
9859
9860 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
9861 BId == Builtin::BIstrndup ? 1 : 2);
9862 unsigned LenArg =
9863 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
9864 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
9865
9866 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
9867 Call->getBeginLoc(), Call->getRParenLoc()))
9868 return;
9869
9870 // Catch cases like 'memset(buf, sizeof(buf), 0)'.
9871 CheckMemaccessSize(*this, BId, Call);
9872
9873 // We have special checking when the length is a sizeof expression.
9874 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
9875 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
9876 llvm::FoldingSetNodeID SizeOfArgID;
9877
9878 // Although widely used, 'bzero' is not a standard function. Be more strict
9879 // with the argument types before allowing diagnostics and only allow the
9880 // form bzero(ptr, sizeof(...)).
9881 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9882 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
9883 return;
9884
9885 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
9886 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
9887 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
9888
9889 QualType DestTy = Dest->getType();
9890 QualType PointeeTy;
9891 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
9892 PointeeTy = DestPtrTy->getPointeeType();
9893
9894 // Never warn about void type pointers. This can be used to suppress
9895 // false positives.
9896 if (PointeeTy->isVoidType())
9897 continue;
9898
9899 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
9900 // actually comparing the expressions for equality. Because computing the
9901 // expression IDs can be expensive, we only do this if the diagnostic is
9902 // enabled.
9903 if (SizeOfArg &&
9904 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
9905 SizeOfArg->getExprLoc())) {
9906 // We only compute IDs for expressions if the warning is enabled, and
9907 // cache the sizeof arg's ID.
9908 if (SizeOfArgID == llvm::FoldingSetNodeID())
9909 SizeOfArg->Profile(SizeOfArgID, Context, true);
9910 llvm::FoldingSetNodeID DestID;
9911 Dest->Profile(DestID, Context, true);
9912 if (DestID == SizeOfArgID) {
9913 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
9914 // over sizeof(src) as well.
9915 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
9916 StringRef ReadableName = FnName->getName();
9917
9918 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
9919 if (UnaryOp->getOpcode() == UO_AddrOf)
9920 ActionIdx = 1; // If its an address-of operator, just remove it.
9921 if (!PointeeTy->isIncompleteType() &&
9922 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
9923 ActionIdx = 2; // If the pointee's size is sizeof(char),
9924 // suggest an explicit length.
9925
9926 // If the function is defined as a builtin macro, do not show macro
9927 // expansion.
9928 SourceLocation SL = SizeOfArg->getExprLoc();
9929 SourceRange DSR = Dest->getSourceRange();
9930 SourceRange SSR = SizeOfArg->getSourceRange();
9931 SourceManager &SM = getSourceManager();
9932
9933 if (SM.isMacroArgExpansion(SL)) {
9934 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
9935 SL = SM.getSpellingLoc(SL);
9936 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
9937 SM.getSpellingLoc(DSR.getEnd()));
9938 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
9939 SM.getSpellingLoc(SSR.getEnd()));
9940 }
9941
9942 DiagRuntimeBehavior(SL, SizeOfArg,
9943 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
9944 << ReadableName
9945 << PointeeTy
9946 << DestTy
9947 << DSR
9948 << SSR);
9949 DiagRuntimeBehavior(SL, SizeOfArg,
9950 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
9951 << ActionIdx
9952 << SSR);
9953
9954 break;
9955 }
9956 }
9957
9958 // Also check for cases where the sizeof argument is the exact same
9959 // type as the memory argument, and where it points to a user-defined
9960 // record type.
9961 if (SizeOfArgTy != QualType()) {
9962 if (PointeeTy->isRecordType() &&
9963 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
9964 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
9965 PDiag(diag::warn_sizeof_pointer_type_memaccess)
9966 << FnName << SizeOfArgTy << ArgIdx
9967 << PointeeTy << Dest->getSourceRange()
9968 << LenExpr->getSourceRange());
9969 break;
9970 }
9971 }
9972 } else if (DestTy->isArrayType()) {
9973 PointeeTy = DestTy;
9974 }
9975
9976 if (PointeeTy == QualType())
9977 continue;
9978
9979 // Always complain about dynamic classes.
9980 bool IsContained;
9981 if (const CXXRecordDecl *ContainedRD =
9982 getContainedDynamicClass(PointeeTy, IsContained)) {
9983
9984 unsigned OperationType = 0;
9985 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
9986 // "overwritten" if we're warning about the destination for any call
9987 // but memcmp; otherwise a verb appropriate to the call.
9988 if (ArgIdx != 0 || IsCmp) {
9989 if (BId == Builtin::BImemcpy)
9990 OperationType = 1;
9991 else if(BId == Builtin::BImemmove)
9992 OperationType = 2;
9993 else if (IsCmp)
9994 OperationType = 3;
9995 }
9996
9997 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9998 PDiag(diag::warn_dyn_class_memaccess)
9999 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
10000 << IsContained << ContainedRD << OperationType
10001 << Call->getCallee()->getSourceRange());
10002 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
10003 BId != Builtin::BImemset)
10004 DiagRuntimeBehavior(
10005 Dest->getExprLoc(), Dest,
10006 PDiag(diag::warn_arc_object_memaccess)
10007 << ArgIdx << FnName << PointeeTy
10008 << Call->getCallee()->getSourceRange());
10009 else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
10010 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10011 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
10012 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10013 PDiag(diag::warn_cstruct_memaccess)
10014 << ArgIdx << FnName << PointeeTy << 0);
10015 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
10016 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
10017 RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
10018 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10019 PDiag(diag::warn_cstruct_memaccess)
10020 << ArgIdx << FnName << PointeeTy << 1);
10021 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
10022 } else {
10023 continue;
10024 }
10025 } else
10026 continue;
10027
10028 DiagRuntimeBehavior(
10029 Dest->getExprLoc(), Dest,
10030 PDiag(diag::note_bad_memaccess_silence)
10031 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
10032 break;
10033 }
10034 }
10035
10036 // A little helper routine: ignore addition and subtraction of integer literals.
10037 // This intentionally does not ignore all integer constant expressions because
10038 // we don't want to remove sizeof().
ignoreLiteralAdditions(const Expr * Ex,ASTContext & Ctx)10039 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
10040 Ex = Ex->IgnoreParenCasts();
10041
10042 while (true) {
10043 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
10044 if (!BO || !BO->isAdditiveOp())
10045 break;
10046
10047 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
10048 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
10049
10050 if (isa<IntegerLiteral>(RHS))
10051 Ex = LHS;
10052 else if (isa<IntegerLiteral>(LHS))
10053 Ex = RHS;
10054 else
10055 break;
10056 }
10057
10058 return Ex;
10059 }
10060
isConstantSizeArrayWithMoreThanOneElement(QualType Ty,ASTContext & Context)10061 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
10062 ASTContext &Context) {
10063 // Only handle constant-sized or VLAs, but not flexible members.
10064 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
10065 // Only issue the FIXIT for arrays of size > 1.
10066 if (CAT->getSize().getSExtValue() <= 1)
10067 return false;
10068 } else if (!Ty->isVariableArrayType()) {
10069 return false;
10070 }
10071 return true;
10072 }
10073
10074 // Warn if the user has made the 'size' argument to strlcpy or strlcat
10075 // be the size of the source, instead of the destination.
CheckStrlcpycatArguments(const CallExpr * Call,IdentifierInfo * FnName)10076 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
10077 IdentifierInfo *FnName) {
10078
10079 // Don't crash if the user has the wrong number of arguments
10080 unsigned NumArgs = Call->getNumArgs();
10081 if ((NumArgs != 3) && (NumArgs != 4))
10082 return;
10083
10084 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
10085 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
10086 const Expr *CompareWithSrc = nullptr;
10087
10088 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
10089 Call->getBeginLoc(), Call->getRParenLoc()))
10090 return;
10091
10092 // Look for 'strlcpy(dst, x, sizeof(x))'
10093 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
10094 CompareWithSrc = Ex;
10095 else {
10096 // Look for 'strlcpy(dst, x, strlen(x))'
10097 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
10098 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
10099 SizeCall->getNumArgs() == 1)
10100 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
10101 }
10102 }
10103
10104 if (!CompareWithSrc)
10105 return;
10106
10107 // Determine if the argument to sizeof/strlen is equal to the source
10108 // argument. In principle there's all kinds of things you could do
10109 // here, for instance creating an == expression and evaluating it with
10110 // EvaluateAsBooleanCondition, but this uses a more direct technique:
10111 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
10112 if (!SrcArgDRE)
10113 return;
10114
10115 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
10116 if (!CompareWithSrcDRE ||
10117 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
10118 return;
10119
10120 const Expr *OriginalSizeArg = Call->getArg(2);
10121 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
10122 << OriginalSizeArg->getSourceRange() << FnName;
10123
10124 // Output a FIXIT hint if the destination is an array (rather than a
10125 // pointer to an array). This could be enhanced to handle some
10126 // pointers if we know the actual size, like if DstArg is 'array+2'
10127 // we could say 'sizeof(array)-2'.
10128 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
10129 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
10130 return;
10131
10132 SmallString<128> sizeString;
10133 llvm::raw_svector_ostream OS(sizeString);
10134 OS << "sizeof(";
10135 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10136 OS << ")";
10137
10138 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
10139 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
10140 OS.str());
10141 }
10142
10143 /// Check if two expressions refer to the same declaration.
referToTheSameDecl(const Expr * E1,const Expr * E2)10144 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
10145 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
10146 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
10147 return D1->getDecl() == D2->getDecl();
10148 return false;
10149 }
10150
getStrlenExprArg(const Expr * E)10151 static const Expr *getStrlenExprArg(const Expr *E) {
10152 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10153 const FunctionDecl *FD = CE->getDirectCallee();
10154 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
10155 return nullptr;
10156 return CE->getArg(0)->IgnoreParenCasts();
10157 }
10158 return nullptr;
10159 }
10160
10161 // Warn on anti-patterns as the 'size' argument to strncat.
10162 // The correct size argument should look like following:
10163 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
CheckStrncatArguments(const CallExpr * CE,IdentifierInfo * FnName)10164 void Sema::CheckStrncatArguments(const CallExpr *CE,
10165 IdentifierInfo *FnName) {
10166 // Don't crash if the user has the wrong number of arguments.
10167 if (CE->getNumArgs() < 3)
10168 return;
10169 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
10170 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
10171 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
10172
10173 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
10174 CE->getRParenLoc()))
10175 return;
10176
10177 // Identify common expressions, which are wrongly used as the size argument
10178 // to strncat and may lead to buffer overflows.
10179 unsigned PatternType = 0;
10180 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
10181 // - sizeof(dst)
10182 if (referToTheSameDecl(SizeOfArg, DstArg))
10183 PatternType = 1;
10184 // - sizeof(src)
10185 else if (referToTheSameDecl(SizeOfArg, SrcArg))
10186 PatternType = 2;
10187 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
10188 if (BE->getOpcode() == BO_Sub) {
10189 const Expr *L = BE->getLHS()->IgnoreParenCasts();
10190 const Expr *R = BE->getRHS()->IgnoreParenCasts();
10191 // - sizeof(dst) - strlen(dst)
10192 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
10193 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
10194 PatternType = 1;
10195 // - sizeof(src) - (anything)
10196 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
10197 PatternType = 2;
10198 }
10199 }
10200
10201 if (PatternType == 0)
10202 return;
10203
10204 // Generate the diagnostic.
10205 SourceLocation SL = LenArg->getBeginLoc();
10206 SourceRange SR = LenArg->getSourceRange();
10207 SourceManager &SM = getSourceManager();
10208
10209 // If the function is defined as a builtin macro, do not show macro expansion.
10210 if (SM.isMacroArgExpansion(SL)) {
10211 SL = SM.getSpellingLoc(SL);
10212 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
10213 SM.getSpellingLoc(SR.getEnd()));
10214 }
10215
10216 // Check if the destination is an array (rather than a pointer to an array).
10217 QualType DstTy = DstArg->getType();
10218 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
10219 Context);
10220 if (!isKnownSizeArray) {
10221 if (PatternType == 1)
10222 Diag(SL, diag::warn_strncat_wrong_size) << SR;
10223 else
10224 Diag(SL, diag::warn_strncat_src_size) << SR;
10225 return;
10226 }
10227
10228 if (PatternType == 1)
10229 Diag(SL, diag::warn_strncat_large_size) << SR;
10230 else
10231 Diag(SL, diag::warn_strncat_src_size) << SR;
10232
10233 SmallString<128> sizeString;
10234 llvm::raw_svector_ostream OS(sizeString);
10235 OS << "sizeof(";
10236 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10237 OS << ") - ";
10238 OS << "strlen(";
10239 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10240 OS << ") - 1";
10241
10242 Diag(SL, diag::note_strncat_wrong_size)
10243 << FixItHint::CreateReplacement(SR, OS.str());
10244 }
10245
10246 namespace {
CheckFreeArgumentsOnLvalue(Sema & S,const std::string & CalleeName,const UnaryOperator * UnaryExpr,const VarDecl * Var)10247 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
10248 const UnaryOperator *UnaryExpr,
10249 const VarDecl *Var) {
10250 StorageClass Class = Var->getStorageClass();
10251 if (Class == StorageClass::SC_Extern ||
10252 Class == StorageClass::SC_PrivateExtern ||
10253 Var->getType()->isReferenceType())
10254 return;
10255
10256 S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
10257 << CalleeName << Var;
10258 }
10259
CheckFreeArgumentsOnLvalue(Sema & S,const std::string & CalleeName,const UnaryOperator * UnaryExpr,const Decl * D)10260 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
10261 const UnaryOperator *UnaryExpr, const Decl *D) {
10262 if (const auto *Field = dyn_cast<FieldDecl>(D))
10263 S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
10264 << CalleeName << Field;
10265 }
10266
CheckFreeArgumentsAddressof(Sema & S,const std::string & CalleeName,const UnaryOperator * UnaryExpr)10267 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
10268 const UnaryOperator *UnaryExpr) {
10269 if (UnaryExpr->getOpcode() != UnaryOperator::Opcode::UO_AddrOf)
10270 return;
10271
10272 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr()))
10273 if (const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl()))
10274 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, Var);
10275
10276 if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
10277 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
10278 Lvalue->getMemberDecl());
10279 }
10280
CheckFreeArgumentsStackArray(Sema & S,const std::string & CalleeName,const DeclRefExpr * Lvalue)10281 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
10282 const DeclRefExpr *Lvalue) {
10283 if (!Lvalue->getType()->isArrayType())
10284 return;
10285
10286 const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
10287 if (Var == nullptr)
10288 return;
10289
10290 S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
10291 << CalleeName << Var;
10292 }
10293 } // namespace
10294
10295 /// Alerts the user that they are attempting to free a non-malloc'd object.
CheckFreeArguments(const CallExpr * E)10296 void Sema::CheckFreeArguments(const CallExpr *E) {
10297 const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
10298 const std::string CalleeName =
10299 dyn_cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
10300
10301 if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
10302 return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
10303
10304 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
10305 return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
10306 }
10307
10308 void
CheckReturnValExpr(Expr * RetValExp,QualType lhsType,SourceLocation ReturnLoc,bool isObjCMethod,const AttrVec * Attrs,const FunctionDecl * FD)10309 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
10310 SourceLocation ReturnLoc,
10311 bool isObjCMethod,
10312 const AttrVec *Attrs,
10313 const FunctionDecl *FD) {
10314 // Check if the return value is null but should not be.
10315 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
10316 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
10317 CheckNonNullExpr(*this, RetValExp))
10318 Diag(ReturnLoc, diag::warn_null_ret)
10319 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
10320
10321 // C++11 [basic.stc.dynamic.allocation]p4:
10322 // If an allocation function declared with a non-throwing
10323 // exception-specification fails to allocate storage, it shall return
10324 // a null pointer. Any other allocation function that fails to allocate
10325 // storage shall indicate failure only by throwing an exception [...]
10326 if (FD) {
10327 OverloadedOperatorKind Op = FD->getOverloadedOperator();
10328 if (Op == OO_New || Op == OO_Array_New) {
10329 const FunctionProtoType *Proto
10330 = FD->getType()->castAs<FunctionProtoType>();
10331 if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
10332 CheckNonNullExpr(*this, RetValExp))
10333 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
10334 << FD << getLangOpts().CPlusPlus11;
10335 }
10336 }
10337
10338 // PPC MMA non-pointer types are not allowed as return type. Checking the type
10339 // here prevent the user from using a PPC MMA type as trailing return type.
10340 if (Context.getTargetInfo().getTriple().isPPC64())
10341 CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
10342 }
10343
10344 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
10345
10346 /// Check for comparisons of floating point operands using != and ==.
10347 /// Issue a warning if these are no self-comparisons, as they are not likely
10348 /// to do what the programmer intended.
CheckFloatComparison(SourceLocation Loc,Expr * LHS,Expr * RHS)10349 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
10350 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
10351 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
10352
10353 // Special case: check for x == x (which is OK).
10354 // Do not emit warnings for such cases.
10355 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
10356 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
10357 if (DRL->getDecl() == DRR->getDecl())
10358 return;
10359
10360 // Special case: check for comparisons against literals that can be exactly
10361 // represented by APFloat. In such cases, do not emit a warning. This
10362 // is a heuristic: often comparison against such literals are used to
10363 // detect if a value in a variable has not changed. This clearly can
10364 // lead to false negatives.
10365 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
10366 if (FLL->isExact())
10367 return;
10368 } else
10369 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
10370 if (FLR->isExact())
10371 return;
10372
10373 // Check for comparisons with builtin types.
10374 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
10375 if (CL->getBuiltinCallee())
10376 return;
10377
10378 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
10379 if (CR->getBuiltinCallee())
10380 return;
10381
10382 // Emit the diagnostic.
10383 Diag(Loc, diag::warn_floatingpoint_eq)
10384 << LHS->getSourceRange() << RHS->getSourceRange();
10385 }
10386
10387 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
10388 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
10389
10390 namespace {
10391
10392 /// Structure recording the 'active' range of an integer-valued
10393 /// expression.
10394 struct IntRange {
10395 /// The number of bits active in the int. Note that this includes exactly one
10396 /// sign bit if !NonNegative.
10397 unsigned Width;
10398
10399 /// True if the int is known not to have negative values. If so, all leading
10400 /// bits before Width are known zero, otherwise they are known to be the
10401 /// same as the MSB within Width.
10402 bool NonNegative;
10403
IntRange__anon33aba9e81911::IntRange10404 IntRange(unsigned Width, bool NonNegative)
10405 : Width(Width), NonNegative(NonNegative) {}
10406
10407 /// Number of bits excluding the sign bit.
valueBits__anon33aba9e81911::IntRange10408 unsigned valueBits() const {
10409 return NonNegative ? Width : Width - 1;
10410 }
10411
10412 /// Returns the range of the bool type.
forBoolType__anon33aba9e81911::IntRange10413 static IntRange forBoolType() {
10414 return IntRange(1, true);
10415 }
10416
10417 /// Returns the range of an opaque value of the given integral type.
forValueOfType__anon33aba9e81911::IntRange10418 static IntRange forValueOfType(ASTContext &C, QualType T) {
10419 return forValueOfCanonicalType(C,
10420 T->getCanonicalTypeInternal().getTypePtr());
10421 }
10422
10423 /// Returns the range of an opaque value of a canonical integral type.
forValueOfCanonicalType__anon33aba9e81911::IntRange10424 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
10425 assert(T->isCanonicalUnqualified());
10426
10427 if (const VectorType *VT = dyn_cast<VectorType>(T))
10428 T = VT->getElementType().getTypePtr();
10429 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
10430 T = CT->getElementType().getTypePtr();
10431 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
10432 T = AT->getValueType().getTypePtr();
10433
10434 if (!C.getLangOpts().CPlusPlus) {
10435 // For enum types in C code, use the underlying datatype.
10436 if (const EnumType *ET = dyn_cast<EnumType>(T))
10437 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
10438 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
10439 // For enum types in C++, use the known bit width of the enumerators.
10440 EnumDecl *Enum = ET->getDecl();
10441 // In C++11, enums can have a fixed underlying type. Use this type to
10442 // compute the range.
10443 if (Enum->isFixed()) {
10444 return IntRange(C.getIntWidth(QualType(T, 0)),
10445 !ET->isSignedIntegerOrEnumerationType());
10446 }
10447
10448 unsigned NumPositive = Enum->getNumPositiveBits();
10449 unsigned NumNegative = Enum->getNumNegativeBits();
10450
10451 if (NumNegative == 0)
10452 return IntRange(NumPositive, true/*NonNegative*/);
10453 else
10454 return IntRange(std::max(NumPositive + 1, NumNegative),
10455 false/*NonNegative*/);
10456 }
10457
10458 if (const auto *EIT = dyn_cast<ExtIntType>(T))
10459 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
10460
10461 const BuiltinType *BT = cast<BuiltinType>(T);
10462 assert(BT->isInteger());
10463
10464 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
10465 }
10466
10467 /// Returns the "target" range of a canonical integral type, i.e.
10468 /// the range of values expressible in the type.
10469 ///
10470 /// This matches forValueOfCanonicalType except that enums have the
10471 /// full range of their type, not the range of their enumerators.
forTargetOfCanonicalType__anon33aba9e81911::IntRange10472 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
10473 assert(T->isCanonicalUnqualified());
10474
10475 if (const VectorType *VT = dyn_cast<VectorType>(T))
10476 T = VT->getElementType().getTypePtr();
10477 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
10478 T = CT->getElementType().getTypePtr();
10479 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
10480 T = AT->getValueType().getTypePtr();
10481 if (const EnumType *ET = dyn_cast<EnumType>(T))
10482 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
10483
10484 if (const auto *EIT = dyn_cast<ExtIntType>(T))
10485 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
10486
10487 const BuiltinType *BT = cast<BuiltinType>(T);
10488 assert(BT->isInteger());
10489
10490 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
10491 }
10492
10493 /// Returns the supremum of two ranges: i.e. their conservative merge.
join__anon33aba9e81911::IntRange10494 static IntRange join(IntRange L, IntRange R) {
10495 bool Unsigned = L.NonNegative && R.NonNegative;
10496 return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
10497 L.NonNegative && R.NonNegative);
10498 }
10499
10500 /// Return the range of a bitwise-AND of the two ranges.
bit_and__anon33aba9e81911::IntRange10501 static IntRange bit_and(IntRange L, IntRange R) {
10502 unsigned Bits = std::max(L.Width, R.Width);
10503 bool NonNegative = false;
10504 if (L.NonNegative) {
10505 Bits = std::min(Bits, L.Width);
10506 NonNegative = true;
10507 }
10508 if (R.NonNegative) {
10509 Bits = std::min(Bits, R.Width);
10510 NonNegative = true;
10511 }
10512 return IntRange(Bits, NonNegative);
10513 }
10514
10515 /// Return the range of a sum of the two ranges.
sum__anon33aba9e81911::IntRange10516 static IntRange sum(IntRange L, IntRange R) {
10517 bool Unsigned = L.NonNegative && R.NonNegative;
10518 return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
10519 Unsigned);
10520 }
10521
10522 /// Return the range of a difference of the two ranges.
difference__anon33aba9e81911::IntRange10523 static IntRange difference(IntRange L, IntRange R) {
10524 // We need a 1-bit-wider range if:
10525 // 1) LHS can be negative: least value can be reduced.
10526 // 2) RHS can be negative: greatest value can be increased.
10527 bool CanWiden = !L.NonNegative || !R.NonNegative;
10528 bool Unsigned = L.NonNegative && R.Width == 0;
10529 return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
10530 !Unsigned,
10531 Unsigned);
10532 }
10533
10534 /// Return the range of a product of the two ranges.
product__anon33aba9e81911::IntRange10535 static IntRange product(IntRange L, IntRange R) {
10536 // If both LHS and RHS can be negative, we can form
10537 // -2^L * -2^R = 2^(L + R)
10538 // which requires L + R + 1 value bits to represent.
10539 bool CanWiden = !L.NonNegative && !R.NonNegative;
10540 bool Unsigned = L.NonNegative && R.NonNegative;
10541 return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
10542 Unsigned);
10543 }
10544
10545 /// Return the range of a remainder operation between the two ranges.
rem__anon33aba9e81911::IntRange10546 static IntRange rem(IntRange L, IntRange R) {
10547 // The result of a remainder can't be larger than the result of
10548 // either side. The sign of the result is the sign of the LHS.
10549 bool Unsigned = L.NonNegative;
10550 return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
10551 Unsigned);
10552 }
10553 };
10554
10555 } // namespace
10556
GetValueRange(ASTContext & C,llvm::APSInt & value,unsigned MaxWidth)10557 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
10558 unsigned MaxWidth) {
10559 if (value.isSigned() && value.isNegative())
10560 return IntRange(value.getMinSignedBits(), false);
10561
10562 if (value.getBitWidth() > MaxWidth)
10563 value = value.trunc(MaxWidth);
10564
10565 // isNonNegative() just checks the sign bit without considering
10566 // signedness.
10567 return IntRange(value.getActiveBits(), true);
10568 }
10569
GetValueRange(ASTContext & C,APValue & result,QualType Ty,unsigned MaxWidth)10570 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
10571 unsigned MaxWidth) {
10572 if (result.isInt())
10573 return GetValueRange(C, result.getInt(), MaxWidth);
10574
10575 if (result.isVector()) {
10576 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
10577 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
10578 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
10579 R = IntRange::join(R, El);
10580 }
10581 return R;
10582 }
10583
10584 if (result.isComplexInt()) {
10585 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
10586 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
10587 return IntRange::join(R, I);
10588 }
10589
10590 // This can happen with lossless casts to intptr_t of "based" lvalues.
10591 // Assume it might use arbitrary bits.
10592 // FIXME: The only reason we need to pass the type in here is to get
10593 // the sign right on this one case. It would be nice if APValue
10594 // preserved this.
10595 assert(result.isLValue() || result.isAddrLabelDiff());
10596 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
10597 }
10598
GetExprType(const Expr * E)10599 static QualType GetExprType(const Expr *E) {
10600 QualType Ty = E->getType();
10601 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
10602 Ty = AtomicRHS->getValueType();
10603 return Ty;
10604 }
10605
10606 /// Pseudo-evaluate the given integer expression, estimating the
10607 /// range of values it might take.
10608 ///
10609 /// \param MaxWidth The width to which the value will be truncated.
10610 /// \param Approximate If \c true, return a likely range for the result: in
10611 /// particular, assume that aritmetic on narrower types doesn't leave
10612 /// those types. If \c false, return a range including all possible
10613 /// result values.
GetExprRange(ASTContext & C,const Expr * E,unsigned MaxWidth,bool InConstantContext,bool Approximate)10614 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
10615 bool InConstantContext, bool Approximate) {
10616 E = E->IgnoreParens();
10617
10618 // Try a full evaluation first.
10619 Expr::EvalResult result;
10620 if (E->EvaluateAsRValue(result, C, InConstantContext))
10621 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
10622
10623 // I think we only want to look through implicit casts here; if the
10624 // user has an explicit widening cast, we should treat the value as
10625 // being of the new, wider type.
10626 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
10627 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
10628 return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
10629 Approximate);
10630
10631 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
10632
10633 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
10634 CE->getCastKind() == CK_BooleanToSignedIntegral;
10635
10636 // Assume that non-integer casts can span the full range of the type.
10637 if (!isIntegerCast)
10638 return OutputTypeRange;
10639
10640 IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
10641 std::min(MaxWidth, OutputTypeRange.Width),
10642 InConstantContext, Approximate);
10643
10644 // Bail out if the subexpr's range is as wide as the cast type.
10645 if (SubRange.Width >= OutputTypeRange.Width)
10646 return OutputTypeRange;
10647
10648 // Otherwise, we take the smaller width, and we're non-negative if
10649 // either the output type or the subexpr is.
10650 return IntRange(SubRange.Width,
10651 SubRange.NonNegative || OutputTypeRange.NonNegative);
10652 }
10653
10654 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
10655 // If we can fold the condition, just take that operand.
10656 bool CondResult;
10657 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
10658 return GetExprRange(C,
10659 CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
10660 MaxWidth, InConstantContext, Approximate);
10661
10662 // Otherwise, conservatively merge.
10663 // GetExprRange requires an integer expression, but a throw expression
10664 // results in a void type.
10665 Expr *E = CO->getTrueExpr();
10666 IntRange L = E->getType()->isVoidType()
10667 ? IntRange{0, true}
10668 : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
10669 E = CO->getFalseExpr();
10670 IntRange R = E->getType()->isVoidType()
10671 ? IntRange{0, true}
10672 : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
10673 return IntRange::join(L, R);
10674 }
10675
10676 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
10677 IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
10678
10679 switch (BO->getOpcode()) {
10680 case BO_Cmp:
10681 llvm_unreachable("builtin <=> should have class type");
10682
10683 // Boolean-valued operations are single-bit and positive.
10684 case BO_LAnd:
10685 case BO_LOr:
10686 case BO_LT:
10687 case BO_GT:
10688 case BO_LE:
10689 case BO_GE:
10690 case BO_EQ:
10691 case BO_NE:
10692 return IntRange::forBoolType();
10693
10694 // The type of the assignments is the type of the LHS, so the RHS
10695 // is not necessarily the same type.
10696 case BO_MulAssign:
10697 case BO_DivAssign:
10698 case BO_RemAssign:
10699 case BO_AddAssign:
10700 case BO_SubAssign:
10701 case BO_XorAssign:
10702 case BO_OrAssign:
10703 // TODO: bitfields?
10704 return IntRange::forValueOfType(C, GetExprType(E));
10705
10706 // Simple assignments just pass through the RHS, which will have
10707 // been coerced to the LHS type.
10708 case BO_Assign:
10709 // TODO: bitfields?
10710 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
10711 Approximate);
10712
10713 // Operations with opaque sources are black-listed.
10714 case BO_PtrMemD:
10715 case BO_PtrMemI:
10716 return IntRange::forValueOfType(C, GetExprType(E));
10717
10718 // Bitwise-and uses the *infinum* of the two source ranges.
10719 case BO_And:
10720 case BO_AndAssign:
10721 Combine = IntRange::bit_and;
10722 break;
10723
10724 // Left shift gets black-listed based on a judgement call.
10725 case BO_Shl:
10726 // ...except that we want to treat '1 << (blah)' as logically
10727 // positive. It's an important idiom.
10728 if (IntegerLiteral *I
10729 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
10730 if (I->getValue() == 1) {
10731 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
10732 return IntRange(R.Width, /*NonNegative*/ true);
10733 }
10734 }
10735 LLVM_FALLTHROUGH;
10736
10737 case BO_ShlAssign:
10738 return IntRange::forValueOfType(C, GetExprType(E));
10739
10740 // Right shift by a constant can narrow its left argument.
10741 case BO_Shr:
10742 case BO_ShrAssign: {
10743 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext,
10744 Approximate);
10745
10746 // If the shift amount is a positive constant, drop the width by
10747 // that much.
10748 if (Optional<llvm::APSInt> shift =
10749 BO->getRHS()->getIntegerConstantExpr(C)) {
10750 if (shift->isNonNegative()) {
10751 unsigned zext = shift->getZExtValue();
10752 if (zext >= L.Width)
10753 L.Width = (L.NonNegative ? 0 : 1);
10754 else
10755 L.Width -= zext;
10756 }
10757 }
10758
10759 return L;
10760 }
10761
10762 // Comma acts as its right operand.
10763 case BO_Comma:
10764 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
10765 Approximate);
10766
10767 case BO_Add:
10768 if (!Approximate)
10769 Combine = IntRange::sum;
10770 break;
10771
10772 case BO_Sub:
10773 if (BO->getLHS()->getType()->isPointerType())
10774 return IntRange::forValueOfType(C, GetExprType(E));
10775 if (!Approximate)
10776 Combine = IntRange::difference;
10777 break;
10778
10779 case BO_Mul:
10780 if (!Approximate)
10781 Combine = IntRange::product;
10782 break;
10783
10784 // The width of a division result is mostly determined by the size
10785 // of the LHS.
10786 case BO_Div: {
10787 // Don't 'pre-truncate' the operands.
10788 unsigned opWidth = C.getIntWidth(GetExprType(E));
10789 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext,
10790 Approximate);
10791
10792 // If the divisor is constant, use that.
10793 if (Optional<llvm::APSInt> divisor =
10794 BO->getRHS()->getIntegerConstantExpr(C)) {
10795 unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
10796 if (log2 >= L.Width)
10797 L.Width = (L.NonNegative ? 0 : 1);
10798 else
10799 L.Width = std::min(L.Width - log2, MaxWidth);
10800 return L;
10801 }
10802
10803 // Otherwise, just use the LHS's width.
10804 // FIXME: This is wrong if the LHS could be its minimal value and the RHS
10805 // could be -1.
10806 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext,
10807 Approximate);
10808 return IntRange(L.Width, L.NonNegative && R.NonNegative);
10809 }
10810
10811 case BO_Rem:
10812 Combine = IntRange::rem;
10813 break;
10814
10815 // The default behavior is okay for these.
10816 case BO_Xor:
10817 case BO_Or:
10818 break;
10819 }
10820
10821 // Combine the two ranges, but limit the result to the type in which we
10822 // performed the computation.
10823 QualType T = GetExprType(E);
10824 unsigned opWidth = C.getIntWidth(T);
10825 IntRange L =
10826 GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate);
10827 IntRange R =
10828 GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate);
10829 IntRange C = Combine(L, R);
10830 C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
10831 C.Width = std::min(C.Width, MaxWidth);
10832 return C;
10833 }
10834
10835 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
10836 switch (UO->getOpcode()) {
10837 // Boolean-valued operations are white-listed.
10838 case UO_LNot:
10839 return IntRange::forBoolType();
10840
10841 // Operations with opaque sources are black-listed.
10842 case UO_Deref:
10843 case UO_AddrOf: // should be impossible
10844 return IntRange::forValueOfType(C, GetExprType(E));
10845
10846 default:
10847 return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
10848 Approximate);
10849 }
10850 }
10851
10852 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
10853 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
10854 Approximate);
10855
10856 if (const auto *BitField = E->getSourceBitField())
10857 return IntRange(BitField->getBitWidthValue(C),
10858 BitField->getType()->isUnsignedIntegerOrEnumerationType());
10859
10860 return IntRange::forValueOfType(C, GetExprType(E));
10861 }
10862
GetExprRange(ASTContext & C,const Expr * E,bool InConstantContext,bool Approximate)10863 static IntRange GetExprRange(ASTContext &C, const Expr *E,
10864 bool InConstantContext, bool Approximate) {
10865 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
10866 Approximate);
10867 }
10868
10869 /// Checks whether the given value, which currently has the given
10870 /// source semantics, has the same value when coerced through the
10871 /// target semantics.
IsSameFloatAfterCast(const llvm::APFloat & value,const llvm::fltSemantics & Src,const llvm::fltSemantics & Tgt)10872 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
10873 const llvm::fltSemantics &Src,
10874 const llvm::fltSemantics &Tgt) {
10875 llvm::APFloat truncated = value;
10876
10877 bool ignored;
10878 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
10879 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
10880
10881 return truncated.bitwiseIsEqual(value);
10882 }
10883
10884 /// Checks whether the given value, which currently has the given
10885 /// source semantics, has the same value when coerced through the
10886 /// target semantics.
10887 ///
10888 /// The value might be a vector of floats (or a complex number).
IsSameFloatAfterCast(const APValue & value,const llvm::fltSemantics & Src,const llvm::fltSemantics & Tgt)10889 static bool IsSameFloatAfterCast(const APValue &value,
10890 const llvm::fltSemantics &Src,
10891 const llvm::fltSemantics &Tgt) {
10892 if (value.isFloat())
10893 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
10894
10895 if (value.isVector()) {
10896 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
10897 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
10898 return false;
10899 return true;
10900 }
10901
10902 assert(value.isComplexFloat());
10903 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
10904 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
10905 }
10906
10907 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
10908 bool IsListInit = false);
10909
IsEnumConstOrFromMacro(Sema & S,Expr * E)10910 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
10911 // Suppress cases where we are comparing against an enum constant.
10912 if (const DeclRefExpr *DR =
10913 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
10914 if (isa<EnumConstantDecl>(DR->getDecl()))
10915 return true;
10916
10917 // Suppress cases where the value is expanded from a macro, unless that macro
10918 // is how a language represents a boolean literal. This is the case in both C
10919 // and Objective-C.
10920 SourceLocation BeginLoc = E->getBeginLoc();
10921 if (BeginLoc.isMacroID()) {
10922 StringRef MacroName = Lexer::getImmediateMacroName(
10923 BeginLoc, S.getSourceManager(), S.getLangOpts());
10924 return MacroName != "YES" && MacroName != "NO" &&
10925 MacroName != "true" && MacroName != "false";
10926 }
10927
10928 return false;
10929 }
10930
isKnownToHaveUnsignedValue(Expr * E)10931 static bool isKnownToHaveUnsignedValue(Expr *E) {
10932 return E->getType()->isIntegerType() &&
10933 (!E->getType()->isSignedIntegerType() ||
10934 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
10935 }
10936
10937 namespace {
10938 /// The promoted range of values of a type. In general this has the
10939 /// following structure:
10940 ///
10941 /// |-----------| . . . |-----------|
10942 /// ^ ^ ^ ^
10943 /// Min HoleMin HoleMax Max
10944 ///
10945 /// ... where there is only a hole if a signed type is promoted to unsigned
10946 /// (in which case Min and Max are the smallest and largest representable
10947 /// values).
10948 struct PromotedRange {
10949 // Min, or HoleMax if there is a hole.
10950 llvm::APSInt PromotedMin;
10951 // Max, or HoleMin if there is a hole.
10952 llvm::APSInt PromotedMax;
10953
PromotedRange__anon33aba9e81a11::PromotedRange10954 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
10955 if (R.Width == 0)
10956 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
10957 else if (R.Width >= BitWidth && !Unsigned) {
10958 // Promotion made the type *narrower*. This happens when promoting
10959 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
10960 // Treat all values of 'signed int' as being in range for now.
10961 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
10962 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
10963 } else {
10964 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
10965 .extOrTrunc(BitWidth);
10966 PromotedMin.setIsUnsigned(Unsigned);
10967
10968 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
10969 .extOrTrunc(BitWidth);
10970 PromotedMax.setIsUnsigned(Unsigned);
10971 }
10972 }
10973
10974 // Determine whether this range is contiguous (has no hole).
isContiguous__anon33aba9e81a11::PromotedRange10975 bool isContiguous() const { return PromotedMin <= PromotedMax; }
10976
10977 // Where a constant value is within the range.
10978 enum ComparisonResult {
10979 LT = 0x1,
10980 LE = 0x2,
10981 GT = 0x4,
10982 GE = 0x8,
10983 EQ = 0x10,
10984 NE = 0x20,
10985 InRangeFlag = 0x40,
10986
10987 Less = LE | LT | NE,
10988 Min = LE | InRangeFlag,
10989 InRange = InRangeFlag,
10990 Max = GE | InRangeFlag,
10991 Greater = GE | GT | NE,
10992
10993 OnlyValue = LE | GE | EQ | InRangeFlag,
10994 InHole = NE
10995 };
10996
compare__anon33aba9e81a11::PromotedRange10997 ComparisonResult compare(const llvm::APSInt &Value) const {
10998 assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
10999 Value.isUnsigned() == PromotedMin.isUnsigned());
11000 if (!isContiguous()) {
11001 assert(Value.isUnsigned() && "discontiguous range for signed compare");
11002 if (Value.isMinValue()) return Min;
11003 if (Value.isMaxValue()) return Max;
11004 if (Value >= PromotedMin) return InRange;
11005 if (Value <= PromotedMax) return InRange;
11006 return InHole;
11007 }
11008
11009 switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
11010 case -1: return Less;
11011 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
11012 case 1:
11013 switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
11014 case -1: return InRange;
11015 case 0: return Max;
11016 case 1: return Greater;
11017 }
11018 }
11019
11020 llvm_unreachable("impossible compare result");
11021 }
11022
11023 static llvm::Optional<StringRef>
constantValue__anon33aba9e81a11::PromotedRange11024 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
11025 if (Op == BO_Cmp) {
11026 ComparisonResult LTFlag = LT, GTFlag = GT;
11027 if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
11028
11029 if (R & EQ) return StringRef("'std::strong_ordering::equal'");
11030 if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
11031 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
11032 return llvm::None;
11033 }
11034
11035 ComparisonResult TrueFlag, FalseFlag;
11036 if (Op == BO_EQ) {
11037 TrueFlag = EQ;
11038 FalseFlag = NE;
11039 } else if (Op == BO_NE) {
11040 TrueFlag = NE;
11041 FalseFlag = EQ;
11042 } else {
11043 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
11044 TrueFlag = LT;
11045 FalseFlag = GE;
11046 } else {
11047 TrueFlag = GT;
11048 FalseFlag = LE;
11049 }
11050 if (Op == BO_GE || Op == BO_LE)
11051 std::swap(TrueFlag, FalseFlag);
11052 }
11053 if (R & TrueFlag)
11054 return StringRef("true");
11055 if (R & FalseFlag)
11056 return StringRef("false");
11057 return llvm::None;
11058 }
11059 };
11060 }
11061
HasEnumType(Expr * E)11062 static bool HasEnumType(Expr *E) {
11063 // Strip off implicit integral promotions.
11064 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
11065 if (ICE->getCastKind() != CK_IntegralCast &&
11066 ICE->getCastKind() != CK_NoOp)
11067 break;
11068 E = ICE->getSubExpr();
11069 }
11070
11071 return E->getType()->isEnumeralType();
11072 }
11073
classifyConstantValue(Expr * Constant)11074 static int classifyConstantValue(Expr *Constant) {
11075 // The values of this enumeration are used in the diagnostics
11076 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
11077 enum ConstantValueKind {
11078 Miscellaneous = 0,
11079 LiteralTrue,
11080 LiteralFalse
11081 };
11082 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
11083 return BL->getValue() ? ConstantValueKind::LiteralTrue
11084 : ConstantValueKind::LiteralFalse;
11085 return ConstantValueKind::Miscellaneous;
11086 }
11087
CheckTautologicalComparison(Sema & S,BinaryOperator * E,Expr * Constant,Expr * Other,const llvm::APSInt & Value,bool RhsConstant)11088 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
11089 Expr *Constant, Expr *Other,
11090 const llvm::APSInt &Value,
11091 bool RhsConstant) {
11092 if (S.inTemplateInstantiation())
11093 return false;
11094
11095 Expr *OriginalOther = Other;
11096
11097 Constant = Constant->IgnoreParenImpCasts();
11098 Other = Other->IgnoreParenImpCasts();
11099
11100 // Suppress warnings on tautological comparisons between values of the same
11101 // enumeration type. There are only two ways we could warn on this:
11102 // - If the constant is outside the range of representable values of
11103 // the enumeration. In such a case, we should warn about the cast
11104 // to enumeration type, not about the comparison.
11105 // - If the constant is the maximum / minimum in-range value. For an
11106 // enumeratin type, such comparisons can be meaningful and useful.
11107 if (Constant->getType()->isEnumeralType() &&
11108 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
11109 return false;
11110
11111 IntRange OtherValueRange = GetExprRange(
11112 S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false);
11113
11114 QualType OtherT = Other->getType();
11115 if (const auto *AT = OtherT->getAs<AtomicType>())
11116 OtherT = AT->getValueType();
11117 IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
11118
11119 // Special case for ObjC BOOL on targets where its a typedef for a signed char
11120 // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
11121 bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
11122 S.NSAPIObj->isObjCBOOLType(OtherT) &&
11123 OtherT->isSpecificBuiltinType(BuiltinType::SChar);
11124
11125 // Whether we're treating Other as being a bool because of the form of
11126 // expression despite it having another type (typically 'int' in C).
11127 bool OtherIsBooleanDespiteType =
11128 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
11129 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
11130 OtherTypeRange = OtherValueRange = IntRange::forBoolType();
11131
11132 // Check if all values in the range of possible values of this expression
11133 // lead to the same comparison outcome.
11134 PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(),
11135 Value.isUnsigned());
11136 auto Cmp = OtherPromotedValueRange.compare(Value);
11137 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
11138 if (!Result)
11139 return false;
11140
11141 // Also consider the range determined by the type alone. This allows us to
11142 // classify the warning under the proper diagnostic group.
11143 bool TautologicalTypeCompare = false;
11144 {
11145 PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
11146 Value.isUnsigned());
11147 auto TypeCmp = OtherPromotedTypeRange.compare(Value);
11148 if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
11149 RhsConstant)) {
11150 TautologicalTypeCompare = true;
11151 Cmp = TypeCmp;
11152 Result = TypeResult;
11153 }
11154 }
11155
11156 // Don't warn if the non-constant operand actually always evaluates to the
11157 // same value.
11158 if (!TautologicalTypeCompare && OtherValueRange.Width == 0)
11159 return false;
11160
11161 // Suppress the diagnostic for an in-range comparison if the constant comes
11162 // from a macro or enumerator. We don't want to diagnose
11163 //
11164 // some_long_value <= INT_MAX
11165 //
11166 // when sizeof(int) == sizeof(long).
11167 bool InRange = Cmp & PromotedRange::InRangeFlag;
11168 if (InRange && IsEnumConstOrFromMacro(S, Constant))
11169 return false;
11170
11171 // A comparison of an unsigned bit-field against 0 is really a type problem,
11172 // even though at the type level the bit-field might promote to 'signed int'.
11173 if (Other->refersToBitField() && InRange && Value == 0 &&
11174 Other->getType()->isUnsignedIntegerOrEnumerationType())
11175 TautologicalTypeCompare = true;
11176
11177 // If this is a comparison to an enum constant, include that
11178 // constant in the diagnostic.
11179 const EnumConstantDecl *ED = nullptr;
11180 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
11181 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
11182
11183 // Should be enough for uint128 (39 decimal digits)
11184 SmallString<64> PrettySourceValue;
11185 llvm::raw_svector_ostream OS(PrettySourceValue);
11186 if (ED) {
11187 OS << '\'' << *ED << "' (" << Value << ")";
11188 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
11189 Constant->IgnoreParenImpCasts())) {
11190 OS << (BL->getValue() ? "YES" : "NO");
11191 } else {
11192 OS << Value;
11193 }
11194
11195 if (!TautologicalTypeCompare) {
11196 S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
11197 << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative
11198 << E->getOpcodeStr() << OS.str() << *Result
11199 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11200 return true;
11201 }
11202
11203 if (IsObjCSignedCharBool) {
11204 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
11205 S.PDiag(diag::warn_tautological_compare_objc_bool)
11206 << OS.str() << *Result);
11207 return true;
11208 }
11209
11210 // FIXME: We use a somewhat different formatting for the in-range cases and
11211 // cases involving boolean values for historical reasons. We should pick a
11212 // consistent way of presenting these diagnostics.
11213 if (!InRange || Other->isKnownToHaveBooleanValue()) {
11214
11215 S.DiagRuntimeBehavior(
11216 E->getOperatorLoc(), E,
11217 S.PDiag(!InRange ? diag::warn_out_of_range_compare
11218 : diag::warn_tautological_bool_compare)
11219 << OS.str() << classifyConstantValue(Constant) << OtherT
11220 << OtherIsBooleanDespiteType << *Result
11221 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
11222 } else {
11223 unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
11224 ? (HasEnumType(OriginalOther)
11225 ? diag::warn_unsigned_enum_always_true_comparison
11226 : diag::warn_unsigned_always_true_comparison)
11227 : diag::warn_tautological_constant_compare;
11228
11229 S.Diag(E->getOperatorLoc(), Diag)
11230 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
11231 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11232 }
11233
11234 return true;
11235 }
11236
11237 /// Analyze the operands of the given comparison. Implements the
11238 /// fallback case from AnalyzeComparison.
AnalyzeImpConvsInComparison(Sema & S,BinaryOperator * E)11239 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
11240 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11241 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11242 }
11243
11244 /// Implements -Wsign-compare.
11245 ///
11246 /// \param E the binary operator to check for warnings
AnalyzeComparison(Sema & S,BinaryOperator * E)11247 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
11248 // The type the comparison is being performed in.
11249 QualType T = E->getLHS()->getType();
11250
11251 // Only analyze comparison operators where both sides have been converted to
11252 // the same type.
11253 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
11254 return AnalyzeImpConvsInComparison(S, E);
11255
11256 // Don't analyze value-dependent comparisons directly.
11257 if (E->isValueDependent())
11258 return AnalyzeImpConvsInComparison(S, E);
11259
11260 Expr *LHS = E->getLHS();
11261 Expr *RHS = E->getRHS();
11262
11263 if (T->isIntegralType(S.Context)) {
11264 Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context);
11265 Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context);
11266
11267 // We don't care about expressions whose result is a constant.
11268 if (RHSValue && LHSValue)
11269 return AnalyzeImpConvsInComparison(S, E);
11270
11271 // We only care about expressions where just one side is literal
11272 if ((bool)RHSValue ^ (bool)LHSValue) {
11273 // Is the constant on the RHS or LHS?
11274 const bool RhsConstant = (bool)RHSValue;
11275 Expr *Const = RhsConstant ? RHS : LHS;
11276 Expr *Other = RhsConstant ? LHS : RHS;
11277 const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
11278
11279 // Check whether an integer constant comparison results in a value
11280 // of 'true' or 'false'.
11281 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
11282 return AnalyzeImpConvsInComparison(S, E);
11283 }
11284 }
11285
11286 if (!T->hasUnsignedIntegerRepresentation()) {
11287 // We don't do anything special if this isn't an unsigned integral
11288 // comparison: we're only interested in integral comparisons, and
11289 // signed comparisons only happen in cases we don't care to warn about.
11290 return AnalyzeImpConvsInComparison(S, E);
11291 }
11292
11293 LHS = LHS->IgnoreParenImpCasts();
11294 RHS = RHS->IgnoreParenImpCasts();
11295
11296 if (!S.getLangOpts().CPlusPlus) {
11297 // Avoid warning about comparison of integers with different signs when
11298 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
11299 // the type of `E`.
11300 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
11301 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11302 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
11303 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11304 }
11305
11306 // Check to see if one of the (unmodified) operands is of different
11307 // signedness.
11308 Expr *signedOperand, *unsignedOperand;
11309 if (LHS->getType()->hasSignedIntegerRepresentation()) {
11310 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
11311 "unsigned comparison between two signed integer expressions?");
11312 signedOperand = LHS;
11313 unsignedOperand = RHS;
11314 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
11315 signedOperand = RHS;
11316 unsignedOperand = LHS;
11317 } else {
11318 return AnalyzeImpConvsInComparison(S, E);
11319 }
11320
11321 // Otherwise, calculate the effective range of the signed operand.
11322 IntRange signedRange = GetExprRange(
11323 S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true);
11324
11325 // Go ahead and analyze implicit conversions in the operands. Note
11326 // that we skip the implicit conversions on both sides.
11327 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
11328 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
11329
11330 // If the signed range is non-negative, -Wsign-compare won't fire.
11331 if (signedRange.NonNegative)
11332 return;
11333
11334 // For (in)equality comparisons, if the unsigned operand is a
11335 // constant which cannot collide with a overflowed signed operand,
11336 // then reinterpreting the signed operand as unsigned will not
11337 // change the result of the comparison.
11338 if (E->isEqualityOp()) {
11339 unsigned comparisonWidth = S.Context.getIntWidth(T);
11340 IntRange unsignedRange =
11341 GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(),
11342 /*Approximate*/ true);
11343
11344 // We should never be unable to prove that the unsigned operand is
11345 // non-negative.
11346 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
11347
11348 if (unsignedRange.Width < comparisonWidth)
11349 return;
11350 }
11351
11352 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
11353 S.PDiag(diag::warn_mixed_sign_comparison)
11354 << LHS->getType() << RHS->getType()
11355 << LHS->getSourceRange() << RHS->getSourceRange());
11356 }
11357
11358 /// Analyzes an attempt to assign the given value to a bitfield.
11359 ///
11360 /// Returns true if there was something fishy about the attempt.
AnalyzeBitFieldAssignment(Sema & S,FieldDecl * Bitfield,Expr * Init,SourceLocation InitLoc)11361 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
11362 SourceLocation InitLoc) {
11363 assert(Bitfield->isBitField());
11364 if (Bitfield->isInvalidDecl())
11365 return false;
11366
11367 // White-list bool bitfields.
11368 QualType BitfieldType = Bitfield->getType();
11369 if (BitfieldType->isBooleanType())
11370 return false;
11371
11372 if (BitfieldType->isEnumeralType()) {
11373 EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
11374 // If the underlying enum type was not explicitly specified as an unsigned
11375 // type and the enum contain only positive values, MSVC++ will cause an
11376 // inconsistency by storing this as a signed type.
11377 if (S.getLangOpts().CPlusPlus11 &&
11378 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
11379 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
11380 BitfieldEnumDecl->getNumNegativeBits() == 0) {
11381 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
11382 << BitfieldEnumDecl;
11383 }
11384 }
11385
11386 if (Bitfield->getType()->isBooleanType())
11387 return false;
11388
11389 // Ignore value- or type-dependent expressions.
11390 if (Bitfield->getBitWidth()->isValueDependent() ||
11391 Bitfield->getBitWidth()->isTypeDependent() ||
11392 Init->isValueDependent() ||
11393 Init->isTypeDependent())
11394 return false;
11395
11396 Expr *OriginalInit = Init->IgnoreParenImpCasts();
11397 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
11398
11399 Expr::EvalResult Result;
11400 if (!OriginalInit->EvaluateAsInt(Result, S.Context,
11401 Expr::SE_AllowSideEffects)) {
11402 // The RHS is not constant. If the RHS has an enum type, make sure the
11403 // bitfield is wide enough to hold all the values of the enum without
11404 // truncation.
11405 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
11406 EnumDecl *ED = EnumTy->getDecl();
11407 bool SignedBitfield = BitfieldType->isSignedIntegerType();
11408
11409 // Enum types are implicitly signed on Windows, so check if there are any
11410 // negative enumerators to see if the enum was intended to be signed or
11411 // not.
11412 bool SignedEnum = ED->getNumNegativeBits() > 0;
11413
11414 // Check for surprising sign changes when assigning enum values to a
11415 // bitfield of different signedness. If the bitfield is signed and we
11416 // have exactly the right number of bits to store this unsigned enum,
11417 // suggest changing the enum to an unsigned type. This typically happens
11418 // on Windows where unfixed enums always use an underlying type of 'int'.
11419 unsigned DiagID = 0;
11420 if (SignedEnum && !SignedBitfield) {
11421 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
11422 } else if (SignedBitfield && !SignedEnum &&
11423 ED->getNumPositiveBits() == FieldWidth) {
11424 DiagID = diag::warn_signed_bitfield_enum_conversion;
11425 }
11426
11427 if (DiagID) {
11428 S.Diag(InitLoc, DiagID) << Bitfield << ED;
11429 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
11430 SourceRange TypeRange =
11431 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
11432 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
11433 << SignedEnum << TypeRange;
11434 }
11435
11436 // Compute the required bitwidth. If the enum has negative values, we need
11437 // one more bit than the normal number of positive bits to represent the
11438 // sign bit.
11439 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
11440 ED->getNumNegativeBits())
11441 : ED->getNumPositiveBits();
11442
11443 // Check the bitwidth.
11444 if (BitsNeeded > FieldWidth) {
11445 Expr *WidthExpr = Bitfield->getBitWidth();
11446 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
11447 << Bitfield << ED;
11448 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
11449 << BitsNeeded << ED << WidthExpr->getSourceRange();
11450 }
11451 }
11452
11453 return false;
11454 }
11455
11456 llvm::APSInt Value = Result.Val.getInt();
11457
11458 unsigned OriginalWidth = Value.getBitWidth();
11459
11460 if (!Value.isSigned() || Value.isNegative())
11461 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
11462 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
11463 OriginalWidth = Value.getMinSignedBits();
11464
11465 if (OriginalWidth <= FieldWidth)
11466 return false;
11467
11468 // Compute the value which the bitfield will contain.
11469 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
11470 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
11471
11472 // Check whether the stored value is equal to the original value.
11473 TruncatedValue = TruncatedValue.extend(OriginalWidth);
11474 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
11475 return false;
11476
11477 // Special-case bitfields of width 1: booleans are naturally 0/1, and
11478 // therefore don't strictly fit into a signed bitfield of width 1.
11479 if (FieldWidth == 1 && Value == 1)
11480 return false;
11481
11482 std::string PrettyValue = Value.toString(10);
11483 std::string PrettyTrunc = TruncatedValue.toString(10);
11484
11485 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
11486 << PrettyValue << PrettyTrunc << OriginalInit->getType()
11487 << Init->getSourceRange();
11488
11489 return true;
11490 }
11491
11492 /// Analyze the given simple or compound assignment for warning-worthy
11493 /// operations.
AnalyzeAssignment(Sema & S,BinaryOperator * E)11494 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
11495 // Just recurse on the LHS.
11496 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11497
11498 // We want to recurse on the RHS as normal unless we're assigning to
11499 // a bitfield.
11500 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
11501 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
11502 E->getOperatorLoc())) {
11503 // Recurse, ignoring any implicit conversions on the RHS.
11504 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
11505 E->getOperatorLoc());
11506 }
11507 }
11508
11509 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11510
11511 // Diagnose implicitly sequentially-consistent atomic assignment.
11512 if (E->getLHS()->getType()->isAtomicType())
11513 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
11514 }
11515
11516 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
DiagnoseImpCast(Sema & S,Expr * E,QualType SourceType,QualType T,SourceLocation CContext,unsigned diag,bool pruneControlFlow=false)11517 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
11518 SourceLocation CContext, unsigned diag,
11519 bool pruneControlFlow = false) {
11520 if (pruneControlFlow) {
11521 S.DiagRuntimeBehavior(E->getExprLoc(), E,
11522 S.PDiag(diag)
11523 << SourceType << T << E->getSourceRange()
11524 << SourceRange(CContext));
11525 return;
11526 }
11527 S.Diag(E->getExprLoc(), diag)
11528 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
11529 }
11530
11531 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
DiagnoseImpCast(Sema & S,Expr * E,QualType T,SourceLocation CContext,unsigned diag,bool pruneControlFlow=false)11532 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
11533 SourceLocation CContext,
11534 unsigned diag, bool pruneControlFlow = false) {
11535 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
11536 }
11537
isObjCSignedCharBool(Sema & S,QualType Ty)11538 static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
11539 return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
11540 S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
11541 }
11542
adornObjCBoolConversionDiagWithTernaryFixit(Sema & S,Expr * SourceExpr,const Sema::SemaDiagnosticBuilder & Builder)11543 static void adornObjCBoolConversionDiagWithTernaryFixit(
11544 Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
11545 Expr *Ignored = SourceExpr->IgnoreImplicit();
11546 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
11547 Ignored = OVE->getSourceExpr();
11548 bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
11549 isa<BinaryOperator>(Ignored) ||
11550 isa<CXXOperatorCallExpr>(Ignored);
11551 SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
11552 if (NeedsParens)
11553 Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
11554 << FixItHint::CreateInsertion(EndLoc, ")");
11555 Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
11556 }
11557
11558 /// Diagnose an implicit cast from a floating point value to an integer value.
DiagnoseFloatingImpCast(Sema & S,Expr * E,QualType T,SourceLocation CContext)11559 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
11560 SourceLocation CContext) {
11561 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
11562 const bool PruneWarnings = S.inTemplateInstantiation();
11563
11564 Expr *InnerE = E->IgnoreParenImpCasts();
11565 // We also want to warn on, e.g., "int i = -1.234"
11566 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
11567 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
11568 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
11569
11570 const bool IsLiteral =
11571 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
11572
11573 llvm::APFloat Value(0.0);
11574 bool IsConstant =
11575 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
11576 if (!IsConstant) {
11577 if (isObjCSignedCharBool(S, T)) {
11578 return adornObjCBoolConversionDiagWithTernaryFixit(
11579 S, E,
11580 S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
11581 << E->getType());
11582 }
11583
11584 return DiagnoseImpCast(S, E, T, CContext,
11585 diag::warn_impcast_float_integer, PruneWarnings);
11586 }
11587
11588 bool isExact = false;
11589
11590 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
11591 T->hasUnsignedIntegerRepresentation());
11592 llvm::APFloat::opStatus Result = Value.convertToInteger(
11593 IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
11594
11595 // FIXME: Force the precision of the source value down so we don't print
11596 // digits which are usually useless (we don't really care here if we
11597 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
11598 // would automatically print the shortest representation, but it's a bit
11599 // tricky to implement.
11600 SmallString<16> PrettySourceValue;
11601 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
11602 precision = (precision * 59 + 195) / 196;
11603 Value.toString(PrettySourceValue, precision);
11604
11605 if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
11606 return adornObjCBoolConversionDiagWithTernaryFixit(
11607 S, E,
11608 S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
11609 << PrettySourceValue);
11610 }
11611
11612 if (Result == llvm::APFloat::opOK && isExact) {
11613 if (IsLiteral) return;
11614 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
11615 PruneWarnings);
11616 }
11617
11618 // Conversion of a floating-point value to a non-bool integer where the
11619 // integral part cannot be represented by the integer type is undefined.
11620 if (!IsBool && Result == llvm::APFloat::opInvalidOp)
11621 return DiagnoseImpCast(
11622 S, E, T, CContext,
11623 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
11624 : diag::warn_impcast_float_to_integer_out_of_range,
11625 PruneWarnings);
11626
11627 unsigned DiagID = 0;
11628 if (IsLiteral) {
11629 // Warn on floating point literal to integer.
11630 DiagID = diag::warn_impcast_literal_float_to_integer;
11631 } else if (IntegerValue == 0) {
11632 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
11633 return DiagnoseImpCast(S, E, T, CContext,
11634 diag::warn_impcast_float_integer, PruneWarnings);
11635 }
11636 // Warn on non-zero to zero conversion.
11637 DiagID = diag::warn_impcast_float_to_integer_zero;
11638 } else {
11639 if (IntegerValue.isUnsigned()) {
11640 if (!IntegerValue.isMaxValue()) {
11641 return DiagnoseImpCast(S, E, T, CContext,
11642 diag::warn_impcast_float_integer, PruneWarnings);
11643 }
11644 } else { // IntegerValue.isSigned()
11645 if (!IntegerValue.isMaxSignedValue() &&
11646 !IntegerValue.isMinSignedValue()) {
11647 return DiagnoseImpCast(S, E, T, CContext,
11648 diag::warn_impcast_float_integer, PruneWarnings);
11649 }
11650 }
11651 // Warn on evaluatable floating point expression to integer conversion.
11652 DiagID = diag::warn_impcast_float_to_integer;
11653 }
11654
11655 SmallString<16> PrettyTargetValue;
11656 if (IsBool)
11657 PrettyTargetValue = Value.isZero() ? "false" : "true";
11658 else
11659 IntegerValue.toString(PrettyTargetValue);
11660
11661 if (PruneWarnings) {
11662 S.DiagRuntimeBehavior(E->getExprLoc(), E,
11663 S.PDiag(DiagID)
11664 << E->getType() << T.getUnqualifiedType()
11665 << PrettySourceValue << PrettyTargetValue
11666 << E->getSourceRange() << SourceRange(CContext));
11667 } else {
11668 S.Diag(E->getExprLoc(), DiagID)
11669 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
11670 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
11671 }
11672 }
11673
11674 /// Analyze the given compound assignment for the possible losing of
11675 /// floating-point precision.
AnalyzeCompoundAssignment(Sema & S,BinaryOperator * E)11676 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
11677 assert(isa<CompoundAssignOperator>(E) &&
11678 "Must be compound assignment operation");
11679 // Recurse on the LHS and RHS in here
11680 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11681 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11682
11683 if (E->getLHS()->getType()->isAtomicType())
11684 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
11685
11686 // Now check the outermost expression
11687 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
11688 const auto *RBT = cast<CompoundAssignOperator>(E)
11689 ->getComputationResultType()
11690 ->getAs<BuiltinType>();
11691
11692 // The below checks assume source is floating point.
11693 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
11694
11695 // If source is floating point but target is an integer.
11696 if (ResultBT->isInteger())
11697 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
11698 E->getExprLoc(), diag::warn_impcast_float_integer);
11699
11700 if (!ResultBT->isFloatingPoint())
11701 return;
11702
11703 // If both source and target are floating points, warn about losing precision.
11704 int Order = S.getASTContext().getFloatingTypeSemanticOrder(
11705 QualType(ResultBT, 0), QualType(RBT, 0));
11706 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
11707 // warn about dropping FP rank.
11708 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
11709 diag::warn_impcast_float_result_precision);
11710 }
11711
PrettyPrintInRange(const llvm::APSInt & Value,IntRange Range)11712 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
11713 IntRange Range) {
11714 if (!Range.Width) return "0";
11715
11716 llvm::APSInt ValueInRange = Value;
11717 ValueInRange.setIsSigned(!Range.NonNegative);
11718 ValueInRange = ValueInRange.trunc(Range.Width);
11719 return ValueInRange.toString(10);
11720 }
11721
IsImplicitBoolFloatConversion(Sema & S,Expr * Ex,bool ToBool)11722 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
11723 if (!isa<ImplicitCastExpr>(Ex))
11724 return false;
11725
11726 Expr *InnerE = Ex->IgnoreParenImpCasts();
11727 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
11728 const Type *Source =
11729 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
11730 if (Target->isDependentType())
11731 return false;
11732
11733 const BuiltinType *FloatCandidateBT =
11734 dyn_cast<BuiltinType>(ToBool ? Source : Target);
11735 const Type *BoolCandidateType = ToBool ? Target : Source;
11736
11737 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
11738 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
11739 }
11740
CheckImplicitArgumentConversions(Sema & S,CallExpr * TheCall,SourceLocation CC)11741 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
11742 SourceLocation CC) {
11743 unsigned NumArgs = TheCall->getNumArgs();
11744 for (unsigned i = 0; i < NumArgs; ++i) {
11745 Expr *CurrA = TheCall->getArg(i);
11746 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
11747 continue;
11748
11749 bool IsSwapped = ((i > 0) &&
11750 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
11751 IsSwapped |= ((i < (NumArgs - 1)) &&
11752 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
11753 if (IsSwapped) {
11754 // Warn on this floating-point to bool conversion.
11755 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
11756 CurrA->getType(), CC,
11757 diag::warn_impcast_floating_point_to_bool);
11758 }
11759 }
11760 }
11761
DiagnoseNullConversion(Sema & S,Expr * E,QualType T,SourceLocation CC)11762 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
11763 SourceLocation CC) {
11764 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
11765 E->getExprLoc()))
11766 return;
11767
11768 // Don't warn on functions which have return type nullptr_t.
11769 if (isa<CallExpr>(E))
11770 return;
11771
11772 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
11773 const Expr::NullPointerConstantKind NullKind =
11774 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
11775 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
11776 return;
11777
11778 // Return if target type is a safe conversion.
11779 if (T->isAnyPointerType() || T->isBlockPointerType() ||
11780 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
11781 return;
11782
11783 SourceLocation Loc = E->getSourceRange().getBegin();
11784
11785 // Venture through the macro stacks to get to the source of macro arguments.
11786 // The new location is a better location than the complete location that was
11787 // passed in.
11788 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
11789 CC = S.SourceMgr.getTopMacroCallerLoc(CC);
11790
11791 // __null is usually wrapped in a macro. Go up a macro if that is the case.
11792 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
11793 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
11794 Loc, S.SourceMgr, S.getLangOpts());
11795 if (MacroName == "NULL")
11796 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
11797 }
11798
11799 // Only warn if the null and context location are in the same macro expansion.
11800 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
11801 return;
11802
11803 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
11804 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
11805 << FixItHint::CreateReplacement(Loc,
11806 S.getFixItZeroLiteralForType(T, Loc));
11807 }
11808
11809 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
11810 ObjCArrayLiteral *ArrayLiteral);
11811
11812 static void
11813 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
11814 ObjCDictionaryLiteral *DictionaryLiteral);
11815
11816 /// Check a single element within a collection literal against the
11817 /// target element type.
checkObjCCollectionLiteralElement(Sema & S,QualType TargetElementType,Expr * Element,unsigned ElementKind)11818 static void checkObjCCollectionLiteralElement(Sema &S,
11819 QualType TargetElementType,
11820 Expr *Element,
11821 unsigned ElementKind) {
11822 // Skip a bitcast to 'id' or qualified 'id'.
11823 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
11824 if (ICE->getCastKind() == CK_BitCast &&
11825 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
11826 Element = ICE->getSubExpr();
11827 }
11828
11829 QualType ElementType = Element->getType();
11830 ExprResult ElementResult(Element);
11831 if (ElementType->getAs<ObjCObjectPointerType>() &&
11832 S.CheckSingleAssignmentConstraints(TargetElementType,
11833 ElementResult,
11834 false, false)
11835 != Sema::Compatible) {
11836 S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
11837 << ElementType << ElementKind << TargetElementType
11838 << Element->getSourceRange();
11839 }
11840
11841 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
11842 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
11843 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
11844 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
11845 }
11846
11847 /// Check an Objective-C array literal being converted to the given
11848 /// target type.
checkObjCArrayLiteral(Sema & S,QualType TargetType,ObjCArrayLiteral * ArrayLiteral)11849 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
11850 ObjCArrayLiteral *ArrayLiteral) {
11851 if (!S.NSArrayDecl)
11852 return;
11853
11854 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
11855 if (!TargetObjCPtr)
11856 return;
11857
11858 if (TargetObjCPtr->isUnspecialized() ||
11859 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
11860 != S.NSArrayDecl->getCanonicalDecl())
11861 return;
11862
11863 auto TypeArgs = TargetObjCPtr->getTypeArgs();
11864 if (TypeArgs.size() != 1)
11865 return;
11866
11867 QualType TargetElementType = TypeArgs[0];
11868 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
11869 checkObjCCollectionLiteralElement(S, TargetElementType,
11870 ArrayLiteral->getElement(I),
11871 0);
11872 }
11873 }
11874
11875 /// Check an Objective-C dictionary literal being converted to the given
11876 /// target type.
11877 static void
checkObjCDictionaryLiteral(Sema & S,QualType TargetType,ObjCDictionaryLiteral * DictionaryLiteral)11878 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
11879 ObjCDictionaryLiteral *DictionaryLiteral) {
11880 if (!S.NSDictionaryDecl)
11881 return;
11882
11883 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
11884 if (!TargetObjCPtr)
11885 return;
11886
11887 if (TargetObjCPtr->isUnspecialized() ||
11888 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
11889 != S.NSDictionaryDecl->getCanonicalDecl())
11890 return;
11891
11892 auto TypeArgs = TargetObjCPtr->getTypeArgs();
11893 if (TypeArgs.size() != 2)
11894 return;
11895
11896 QualType TargetKeyType = TypeArgs[0];
11897 QualType TargetObjectType = TypeArgs[1];
11898 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
11899 auto Element = DictionaryLiteral->getKeyValueElement(I);
11900 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
11901 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
11902 }
11903 }
11904
11905 // Helper function to filter out cases for constant width constant conversion.
11906 // Don't warn on char array initialization or for non-decimal values.
isSameWidthConstantConversion(Sema & S,Expr * E,QualType T,SourceLocation CC)11907 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
11908 SourceLocation CC) {
11909 // If initializing from a constant, and the constant starts with '0',
11910 // then it is a binary, octal, or hexadecimal. Allow these constants
11911 // to fill all the bits, even if there is a sign change.
11912 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
11913 const char FirstLiteralCharacter =
11914 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
11915 if (FirstLiteralCharacter == '0')
11916 return false;
11917 }
11918
11919 // If the CC location points to a '{', and the type is char, then assume
11920 // assume it is an array initialization.
11921 if (CC.isValid() && T->isCharType()) {
11922 const char FirstContextCharacter =
11923 S.getSourceManager().getCharacterData(CC)[0];
11924 if (FirstContextCharacter == '{')
11925 return false;
11926 }
11927
11928 return true;
11929 }
11930
getIntegerLiteral(Expr * E)11931 static const IntegerLiteral *getIntegerLiteral(Expr *E) {
11932 const auto *IL = dyn_cast<IntegerLiteral>(E);
11933 if (!IL) {
11934 if (auto *UO = dyn_cast<UnaryOperator>(E)) {
11935 if (UO->getOpcode() == UO_Minus)
11936 return dyn_cast<IntegerLiteral>(UO->getSubExpr());
11937 }
11938 }
11939
11940 return IL;
11941 }
11942
DiagnoseIntInBoolContext(Sema & S,Expr * E)11943 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
11944 E = E->IgnoreParenImpCasts();
11945 SourceLocation ExprLoc = E->getExprLoc();
11946
11947 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11948 BinaryOperator::Opcode Opc = BO->getOpcode();
11949 Expr::EvalResult Result;
11950 // Do not diagnose unsigned shifts.
11951 if (Opc == BO_Shl) {
11952 const auto *LHS = getIntegerLiteral(BO->getLHS());
11953 const auto *RHS = getIntegerLiteral(BO->getRHS());
11954 if (LHS && LHS->getValue() == 0)
11955 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
11956 else if (!E->isValueDependent() && LHS && RHS &&
11957 RHS->getValue().isNonNegative() &&
11958 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
11959 S.Diag(ExprLoc, diag::warn_left_shift_always)
11960 << (Result.Val.getInt() != 0);
11961 else if (E->getType()->isSignedIntegerType())
11962 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
11963 }
11964 }
11965
11966 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
11967 const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
11968 const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
11969 if (!LHS || !RHS)
11970 return;
11971 if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
11972 (RHS->getValue() == 0 || RHS->getValue() == 1))
11973 // Do not diagnose common idioms.
11974 return;
11975 if (LHS->getValue() != 0 && RHS->getValue() != 0)
11976 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
11977 }
11978 }
11979
CheckImplicitConversion(Sema & S,Expr * E,QualType T,SourceLocation CC,bool * ICContext=nullptr,bool IsListInit=false)11980 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
11981 SourceLocation CC,
11982 bool *ICContext = nullptr,
11983 bool IsListInit = false) {
11984 if (E->isTypeDependent() || E->isValueDependent()) return;
11985
11986 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
11987 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
11988 if (Source == Target) return;
11989 if (Target->isDependentType()) return;
11990
11991 // If the conversion context location is invalid don't complain. We also
11992 // don't want to emit a warning if the issue occurs from the expansion of
11993 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
11994 // delay this check as long as possible. Once we detect we are in that
11995 // scenario, we just return.
11996 if (CC.isInvalid())
11997 return;
11998
11999 if (Source->isAtomicType())
12000 S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
12001
12002 // Diagnose implicit casts to bool.
12003 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
12004 if (isa<StringLiteral>(E))
12005 // Warn on string literal to bool. Checks for string literals in logical
12006 // and expressions, for instance, assert(0 && "error here"), are
12007 // prevented by a check in AnalyzeImplicitConversions().
12008 return DiagnoseImpCast(S, E, T, CC,
12009 diag::warn_impcast_string_literal_to_bool);
12010 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
12011 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
12012 // This covers the literal expressions that evaluate to Objective-C
12013 // objects.
12014 return DiagnoseImpCast(S, E, T, CC,
12015 diag::warn_impcast_objective_c_literal_to_bool);
12016 }
12017 if (Source->isPointerType() || Source->canDecayToPointerType()) {
12018 // Warn on pointer to bool conversion that is always true.
12019 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
12020 SourceRange(CC));
12021 }
12022 }
12023
12024 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
12025 // is a typedef for signed char (macOS), then that constant value has to be 1
12026 // or 0.
12027 if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
12028 Expr::EvalResult Result;
12029 if (E->EvaluateAsInt(Result, S.getASTContext(),
12030 Expr::SE_AllowSideEffects)) {
12031 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
12032 adornObjCBoolConversionDiagWithTernaryFixit(
12033 S, E,
12034 S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
12035 << Result.Val.getInt().toString(10));
12036 }
12037 return;
12038 }
12039 }
12040
12041 // Check implicit casts from Objective-C collection literals to specialized
12042 // collection types, e.g., NSArray<NSString *> *.
12043 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
12044 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
12045 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
12046 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
12047
12048 // Strip vector types.
12049 if (isa<VectorType>(Source)) {
12050 if (!isa<VectorType>(Target)) {
12051 if (S.SourceMgr.isInSystemMacro(CC))
12052 return;
12053 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
12054 }
12055
12056 // If the vector cast is cast between two vectors of the same size, it is
12057 // a bitcast, not a conversion.
12058 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
12059 return;
12060
12061 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
12062 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
12063 }
12064 if (auto VecTy = dyn_cast<VectorType>(Target))
12065 Target = VecTy->getElementType().getTypePtr();
12066
12067 // Strip complex types.
12068 if (isa<ComplexType>(Source)) {
12069 if (!isa<ComplexType>(Target)) {
12070 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
12071 return;
12072
12073 return DiagnoseImpCast(S, E, T, CC,
12074 S.getLangOpts().CPlusPlus
12075 ? diag::err_impcast_complex_scalar
12076 : diag::warn_impcast_complex_scalar);
12077 }
12078
12079 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
12080 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
12081 }
12082
12083 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
12084 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
12085
12086 // If the source is floating point...
12087 if (SourceBT && SourceBT->isFloatingPoint()) {
12088 // ...and the target is floating point...
12089 if (TargetBT && TargetBT->isFloatingPoint()) {
12090 // ...then warn if we're dropping FP rank.
12091
12092 int Order = S.getASTContext().getFloatingTypeSemanticOrder(
12093 QualType(SourceBT, 0), QualType(TargetBT, 0));
12094 if (Order > 0) {
12095 // Don't warn about float constants that are precisely
12096 // representable in the target type.
12097 Expr::EvalResult result;
12098 if (E->EvaluateAsRValue(result, S.Context)) {
12099 // Value might be a float, a float vector, or a float complex.
12100 if (IsSameFloatAfterCast(result.Val,
12101 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
12102 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
12103 return;
12104 }
12105
12106 if (S.SourceMgr.isInSystemMacro(CC))
12107 return;
12108
12109 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
12110 }
12111 // ... or possibly if we're increasing rank, too
12112 else if (Order < 0) {
12113 if (S.SourceMgr.isInSystemMacro(CC))
12114 return;
12115
12116 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
12117 }
12118 return;
12119 }
12120
12121 // If the target is integral, always warn.
12122 if (TargetBT && TargetBT->isInteger()) {
12123 if (S.SourceMgr.isInSystemMacro(CC))
12124 return;
12125
12126 DiagnoseFloatingImpCast(S, E, T, CC);
12127 }
12128
12129 // Detect the case where a call result is converted from floating-point to
12130 // to bool, and the final argument to the call is converted from bool, to
12131 // discover this typo:
12132 //
12133 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
12134 //
12135 // FIXME: This is an incredibly special case; is there some more general
12136 // way to detect this class of misplaced-parentheses bug?
12137 if (Target->isBooleanType() && isa<CallExpr>(E)) {
12138 // Check last argument of function call to see if it is an
12139 // implicit cast from a type matching the type the result
12140 // is being cast to.
12141 CallExpr *CEx = cast<CallExpr>(E);
12142 if (unsigned NumArgs = CEx->getNumArgs()) {
12143 Expr *LastA = CEx->getArg(NumArgs - 1);
12144 Expr *InnerE = LastA->IgnoreParenImpCasts();
12145 if (isa<ImplicitCastExpr>(LastA) &&
12146 InnerE->getType()->isBooleanType()) {
12147 // Warn on this floating-point to bool conversion
12148 DiagnoseImpCast(S, E, T, CC,
12149 diag::warn_impcast_floating_point_to_bool);
12150 }
12151 }
12152 }
12153 return;
12154 }
12155
12156 // Valid casts involving fixed point types should be accounted for here.
12157 if (Source->isFixedPointType()) {
12158 if (Target->isUnsaturatedFixedPointType()) {
12159 Expr::EvalResult Result;
12160 if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
12161 S.isConstantEvaluated())) {
12162 llvm::APFixedPoint Value = Result.Val.getFixedPoint();
12163 llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
12164 llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T);
12165 if (Value > MaxVal || Value < MinVal) {
12166 S.DiagRuntimeBehavior(E->getExprLoc(), E,
12167 S.PDiag(diag::warn_impcast_fixed_point_range)
12168 << Value.toString() << T
12169 << E->getSourceRange()
12170 << clang::SourceRange(CC));
12171 return;
12172 }
12173 }
12174 } else if (Target->isIntegerType()) {
12175 Expr::EvalResult Result;
12176 if (!S.isConstantEvaluated() &&
12177 E->EvaluateAsFixedPoint(Result, S.Context,
12178 Expr::SE_AllowSideEffects)) {
12179 llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
12180
12181 bool Overflowed;
12182 llvm::APSInt IntResult = FXResult.convertToInt(
12183 S.Context.getIntWidth(T),
12184 Target->isSignedIntegerOrEnumerationType(), &Overflowed);
12185
12186 if (Overflowed) {
12187 S.DiagRuntimeBehavior(E->getExprLoc(), E,
12188 S.PDiag(diag::warn_impcast_fixed_point_range)
12189 << FXResult.toString() << T
12190 << E->getSourceRange()
12191 << clang::SourceRange(CC));
12192 return;
12193 }
12194 }
12195 }
12196 } else if (Target->isUnsaturatedFixedPointType()) {
12197 if (Source->isIntegerType()) {
12198 Expr::EvalResult Result;
12199 if (!S.isConstantEvaluated() &&
12200 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
12201 llvm::APSInt Value = Result.Val.getInt();
12202
12203 bool Overflowed;
12204 llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
12205 Value, S.Context.getFixedPointSemantics(T), &Overflowed);
12206
12207 if (Overflowed) {
12208 S.DiagRuntimeBehavior(E->getExprLoc(), E,
12209 S.PDiag(diag::warn_impcast_fixed_point_range)
12210 << Value.toString(/*Radix=*/10) << T
12211 << E->getSourceRange()
12212 << clang::SourceRange(CC));
12213 return;
12214 }
12215 }
12216 }
12217 }
12218
12219 // If we are casting an integer type to a floating point type without
12220 // initialization-list syntax, we might lose accuracy if the floating
12221 // point type has a narrower significand than the integer type.
12222 if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
12223 TargetBT->isFloatingType() && !IsListInit) {
12224 // Determine the number of precision bits in the source integer type.
12225 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(),
12226 /*Approximate*/ true);
12227 unsigned int SourcePrecision = SourceRange.Width;
12228
12229 // Determine the number of precision bits in the
12230 // target floating point type.
12231 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
12232 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12233
12234 if (SourcePrecision > 0 && TargetPrecision > 0 &&
12235 SourcePrecision > TargetPrecision) {
12236
12237 if (Optional<llvm::APSInt> SourceInt =
12238 E->getIntegerConstantExpr(S.Context)) {
12239 // If the source integer is a constant, convert it to the target
12240 // floating point type. Issue a warning if the value changes
12241 // during the whole conversion.
12242 llvm::APFloat TargetFloatValue(
12243 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12244 llvm::APFloat::opStatus ConversionStatus =
12245 TargetFloatValue.convertFromAPInt(
12246 *SourceInt, SourceBT->isSignedInteger(),
12247 llvm::APFloat::rmNearestTiesToEven);
12248
12249 if (ConversionStatus != llvm::APFloat::opOK) {
12250 std::string PrettySourceValue = SourceInt->toString(10);
12251 SmallString<32> PrettyTargetValue;
12252 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
12253
12254 S.DiagRuntimeBehavior(
12255 E->getExprLoc(), E,
12256 S.PDiag(diag::warn_impcast_integer_float_precision_constant)
12257 << PrettySourceValue << PrettyTargetValue << E->getType() << T
12258 << E->getSourceRange() << clang::SourceRange(CC));
12259 }
12260 } else {
12261 // Otherwise, the implicit conversion may lose precision.
12262 DiagnoseImpCast(S, E, T, CC,
12263 diag::warn_impcast_integer_float_precision);
12264 }
12265 }
12266 }
12267
12268 DiagnoseNullConversion(S, E, T, CC);
12269
12270 S.DiscardMisalignedMemberAddress(Target, E);
12271
12272 if (Target->isBooleanType())
12273 DiagnoseIntInBoolContext(S, E);
12274
12275 if (!Source->isIntegerType() || !Target->isIntegerType())
12276 return;
12277
12278 // TODO: remove this early return once the false positives for constant->bool
12279 // in templates, macros, etc, are reduced or removed.
12280 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
12281 return;
12282
12283 if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
12284 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
12285 return adornObjCBoolConversionDiagWithTernaryFixit(
12286 S, E,
12287 S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
12288 << E->getType());
12289 }
12290
12291 IntRange SourceTypeRange =
12292 IntRange::forTargetOfCanonicalType(S.Context, Source);
12293 IntRange LikelySourceRange =
12294 GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true);
12295 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
12296
12297 if (LikelySourceRange.Width > TargetRange.Width) {
12298 // If the source is a constant, use a default-on diagnostic.
12299 // TODO: this should happen for bitfield stores, too.
12300 Expr::EvalResult Result;
12301 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
12302 S.isConstantEvaluated())) {
12303 llvm::APSInt Value(32);
12304 Value = Result.Val.getInt();
12305
12306 if (S.SourceMgr.isInSystemMacro(CC))
12307 return;
12308
12309 std::string PrettySourceValue = Value.toString(10);
12310 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
12311
12312 S.DiagRuntimeBehavior(
12313 E->getExprLoc(), E,
12314 S.PDiag(diag::warn_impcast_integer_precision_constant)
12315 << PrettySourceValue << PrettyTargetValue << E->getType() << T
12316 << E->getSourceRange() << SourceRange(CC));
12317 return;
12318 }
12319
12320 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
12321 if (S.SourceMgr.isInSystemMacro(CC))
12322 return;
12323
12324 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
12325 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
12326 /* pruneControlFlow */ true);
12327 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
12328 }
12329
12330 if (TargetRange.Width > SourceTypeRange.Width) {
12331 if (auto *UO = dyn_cast<UnaryOperator>(E))
12332 if (UO->getOpcode() == UO_Minus)
12333 if (Source->isUnsignedIntegerType()) {
12334 if (Target->isUnsignedIntegerType())
12335 return DiagnoseImpCast(S, E, T, CC,
12336 diag::warn_impcast_high_order_zero_bits);
12337 if (Target->isSignedIntegerType())
12338 return DiagnoseImpCast(S, E, T, CC,
12339 diag::warn_impcast_nonnegative_result);
12340 }
12341 }
12342
12343 if (TargetRange.Width == LikelySourceRange.Width &&
12344 !TargetRange.NonNegative && LikelySourceRange.NonNegative &&
12345 Source->isSignedIntegerType()) {
12346 // Warn when doing a signed to signed conversion, warn if the positive
12347 // source value is exactly the width of the target type, which will
12348 // cause a negative value to be stored.
12349
12350 Expr::EvalResult Result;
12351 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
12352 !S.SourceMgr.isInSystemMacro(CC)) {
12353 llvm::APSInt Value = Result.Val.getInt();
12354 if (isSameWidthConstantConversion(S, E, T, CC)) {
12355 std::string PrettySourceValue = Value.toString(10);
12356 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
12357
12358 S.DiagRuntimeBehavior(
12359 E->getExprLoc(), E,
12360 S.PDiag(diag::warn_impcast_integer_precision_constant)
12361 << PrettySourceValue << PrettyTargetValue << E->getType() << T
12362 << E->getSourceRange() << SourceRange(CC));
12363 return;
12364 }
12365 }
12366
12367 // Fall through for non-constants to give a sign conversion warning.
12368 }
12369
12370 if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) ||
12371 (!TargetRange.NonNegative && LikelySourceRange.NonNegative &&
12372 LikelySourceRange.Width == TargetRange.Width)) {
12373 if (S.SourceMgr.isInSystemMacro(CC))
12374 return;
12375
12376 unsigned DiagID = diag::warn_impcast_integer_sign;
12377
12378 // Traditionally, gcc has warned about this under -Wsign-compare.
12379 // We also want to warn about it in -Wconversion.
12380 // So if -Wconversion is off, use a completely identical diagnostic
12381 // in the sign-compare group.
12382 // The conditional-checking code will
12383 if (ICContext) {
12384 DiagID = diag::warn_impcast_integer_sign_conditional;
12385 *ICContext = true;
12386 }
12387
12388 return DiagnoseImpCast(S, E, T, CC, DiagID);
12389 }
12390
12391 // Diagnose conversions between different enumeration types.
12392 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
12393 // type, to give us better diagnostics.
12394 QualType SourceType = E->getType();
12395 if (!S.getLangOpts().CPlusPlus) {
12396 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12397 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
12398 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
12399 SourceType = S.Context.getTypeDeclType(Enum);
12400 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
12401 }
12402 }
12403
12404 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
12405 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
12406 if (SourceEnum->getDecl()->hasNameForLinkage() &&
12407 TargetEnum->getDecl()->hasNameForLinkage() &&
12408 SourceEnum != TargetEnum) {
12409 if (S.SourceMgr.isInSystemMacro(CC))
12410 return;
12411
12412 return DiagnoseImpCast(S, E, SourceType, T, CC,
12413 diag::warn_impcast_different_enum_types);
12414 }
12415 }
12416
12417 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
12418 SourceLocation CC, QualType T);
12419
CheckConditionalOperand(Sema & S,Expr * E,QualType T,SourceLocation CC,bool & ICContext)12420 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
12421 SourceLocation CC, bool &ICContext) {
12422 E = E->IgnoreParenImpCasts();
12423
12424 if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
12425 return CheckConditionalOperator(S, CO, CC, T);
12426
12427 AnalyzeImplicitConversions(S, E, CC);
12428 if (E->getType() != T)
12429 return CheckImplicitConversion(S, E, T, CC, &ICContext);
12430 }
12431
CheckConditionalOperator(Sema & S,AbstractConditionalOperator * E,SourceLocation CC,QualType T)12432 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
12433 SourceLocation CC, QualType T) {
12434 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
12435
12436 Expr *TrueExpr = E->getTrueExpr();
12437 if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
12438 TrueExpr = BCO->getCommon();
12439
12440 bool Suspicious = false;
12441 CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
12442 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
12443
12444 if (T->isBooleanType())
12445 DiagnoseIntInBoolContext(S, E);
12446
12447 // If -Wconversion would have warned about either of the candidates
12448 // for a signedness conversion to the context type...
12449 if (!Suspicious) return;
12450
12451 // ...but it's currently ignored...
12452 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
12453 return;
12454
12455 // ...then check whether it would have warned about either of the
12456 // candidates for a signedness conversion to the condition type.
12457 if (E->getType() == T) return;
12458
12459 Suspicious = false;
12460 CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(),
12461 E->getType(), CC, &Suspicious);
12462 if (!Suspicious)
12463 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
12464 E->getType(), CC, &Suspicious);
12465 }
12466
12467 /// Check conversion of given expression to boolean.
12468 /// Input argument E is a logical expression.
CheckBoolLikeConversion(Sema & S,Expr * E,SourceLocation CC)12469 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
12470 if (S.getLangOpts().Bool)
12471 return;
12472 if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
12473 return;
12474 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
12475 }
12476
12477 namespace {
12478 struct AnalyzeImplicitConversionsWorkItem {
12479 Expr *E;
12480 SourceLocation CC;
12481 bool IsListInit;
12482 };
12483 }
12484
12485 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
12486 /// that should be visited are added to WorkList.
AnalyzeImplicitConversions(Sema & S,AnalyzeImplicitConversionsWorkItem Item,llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> & WorkList)12487 static void AnalyzeImplicitConversions(
12488 Sema &S, AnalyzeImplicitConversionsWorkItem Item,
12489 llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
12490 Expr *OrigE = Item.E;
12491 SourceLocation CC = Item.CC;
12492
12493 QualType T = OrigE->getType();
12494 Expr *E = OrigE->IgnoreParenImpCasts();
12495
12496 // Propagate whether we are in a C++ list initialization expression.
12497 // If so, we do not issue warnings for implicit int-float conversion
12498 // precision loss, because C++11 narrowing already handles it.
12499 bool IsListInit = Item.IsListInit ||
12500 (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
12501
12502 if (E->isTypeDependent() || E->isValueDependent())
12503 return;
12504
12505 Expr *SourceExpr = E;
12506 // Examine, but don't traverse into the source expression of an
12507 // OpaqueValueExpr, since it may have multiple parents and we don't want to
12508 // emit duplicate diagnostics. Its fine to examine the form or attempt to
12509 // evaluate it in the context of checking the specific conversion to T though.
12510 if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
12511 if (auto *Src = OVE->getSourceExpr())
12512 SourceExpr = Src;
12513
12514 if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
12515 if (UO->getOpcode() == UO_Not &&
12516 UO->getSubExpr()->isKnownToHaveBooleanValue())
12517 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
12518 << OrigE->getSourceRange() << T->isBooleanType()
12519 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
12520
12521 // For conditional operators, we analyze the arguments as if they
12522 // were being fed directly into the output.
12523 if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
12524 CheckConditionalOperator(S, CO, CC, T);
12525 return;
12526 }
12527
12528 // Check implicit argument conversions for function calls.
12529 if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr))
12530 CheckImplicitArgumentConversions(S, Call, CC);
12531
12532 // Go ahead and check any implicit conversions we might have skipped.
12533 // The non-canonical typecheck is just an optimization;
12534 // CheckImplicitConversion will filter out dead implicit conversions.
12535 if (SourceExpr->getType() != T)
12536 CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit);
12537
12538 // Now continue drilling into this expression.
12539
12540 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
12541 // The bound subexpressions in a PseudoObjectExpr are not reachable
12542 // as transitive children.
12543 // FIXME: Use a more uniform representation for this.
12544 for (auto *SE : POE->semantics())
12545 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
12546 WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
12547 }
12548
12549 // Skip past explicit casts.
12550 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
12551 E = CE->getSubExpr()->IgnoreParenImpCasts();
12552 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
12553 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
12554 WorkList.push_back({E, CC, IsListInit});
12555 return;
12556 }
12557
12558 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12559 // Do a somewhat different check with comparison operators.
12560 if (BO->isComparisonOp())
12561 return AnalyzeComparison(S, BO);
12562
12563 // And with simple assignments.
12564 if (BO->getOpcode() == BO_Assign)
12565 return AnalyzeAssignment(S, BO);
12566 // And with compound assignments.
12567 if (BO->isAssignmentOp())
12568 return AnalyzeCompoundAssignment(S, BO);
12569 }
12570
12571 // These break the otherwise-useful invariant below. Fortunately,
12572 // we don't really need to recurse into them, because any internal
12573 // expressions should have been analyzed already when they were
12574 // built into statements.
12575 if (isa<StmtExpr>(E)) return;
12576
12577 // Don't descend into unevaluated contexts.
12578 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
12579
12580 // Now just recurse over the expression's children.
12581 CC = E->getExprLoc();
12582 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
12583 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
12584 for (Stmt *SubStmt : E->children()) {
12585 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
12586 if (!ChildExpr)
12587 continue;
12588
12589 if (IsLogicalAndOperator &&
12590 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
12591 // Ignore checking string literals that are in logical and operators.
12592 // This is a common pattern for asserts.
12593 continue;
12594 WorkList.push_back({ChildExpr, CC, IsListInit});
12595 }
12596
12597 if (BO && BO->isLogicalOp()) {
12598 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
12599 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
12600 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
12601
12602 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
12603 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
12604 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
12605 }
12606
12607 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
12608 if (U->getOpcode() == UO_LNot) {
12609 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
12610 } else if (U->getOpcode() != UO_AddrOf) {
12611 if (U->getSubExpr()->getType()->isAtomicType())
12612 S.Diag(U->getSubExpr()->getBeginLoc(),
12613 diag::warn_atomic_implicit_seq_cst);
12614 }
12615 }
12616 }
12617
12618 /// AnalyzeImplicitConversions - Find and report any interesting
12619 /// implicit conversions in the given expression. There are a couple
12620 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
AnalyzeImplicitConversions(Sema & S,Expr * OrigE,SourceLocation CC,bool IsListInit)12621 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
12622 bool IsListInit/*= false*/) {
12623 llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList;
12624 WorkList.push_back({OrigE, CC, IsListInit});
12625 while (!WorkList.empty())
12626 AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
12627 }
12628
12629 /// Diagnose integer type and any valid implicit conversion to it.
checkOpenCLEnqueueIntType(Sema & S,Expr * E,const QualType & IntT)12630 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
12631 // Taking into account implicit conversions,
12632 // allow any integer.
12633 if (!E->getType()->isIntegerType()) {
12634 S.Diag(E->getBeginLoc(),
12635 diag::err_opencl_enqueue_kernel_invalid_local_size_type);
12636 return true;
12637 }
12638 // Potentially emit standard warnings for implicit conversions if enabled
12639 // using -Wconversion.
12640 CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
12641 return false;
12642 }
12643
12644 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
12645 // Returns true when emitting a warning about taking the address of a reference.
CheckForReference(Sema & SemaRef,const Expr * E,const PartialDiagnostic & PD)12646 static bool CheckForReference(Sema &SemaRef, const Expr *E,
12647 const PartialDiagnostic &PD) {
12648 E = E->IgnoreParenImpCasts();
12649
12650 const FunctionDecl *FD = nullptr;
12651
12652 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12653 if (!DRE->getDecl()->getType()->isReferenceType())
12654 return false;
12655 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
12656 if (!M->getMemberDecl()->getType()->isReferenceType())
12657 return false;
12658 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
12659 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
12660 return false;
12661 FD = Call->getDirectCallee();
12662 } else {
12663 return false;
12664 }
12665
12666 SemaRef.Diag(E->getExprLoc(), PD);
12667
12668 // If possible, point to location of function.
12669 if (FD) {
12670 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
12671 }
12672
12673 return true;
12674 }
12675
12676 // Returns true if the SourceLocation is expanded from any macro body.
12677 // Returns false if the SourceLocation is invalid, is from not in a macro
12678 // expansion, or is from expanded from a top-level macro argument.
IsInAnyMacroBody(const SourceManager & SM,SourceLocation Loc)12679 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
12680 if (Loc.isInvalid())
12681 return false;
12682
12683 while (Loc.isMacroID()) {
12684 if (SM.isMacroBodyExpansion(Loc))
12685 return true;
12686 Loc = SM.getImmediateMacroCallerLoc(Loc);
12687 }
12688
12689 return false;
12690 }
12691
12692 /// Diagnose pointers that are always non-null.
12693 /// \param E the expression containing the pointer
12694 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
12695 /// compared to a null pointer
12696 /// \param IsEqual True when the comparison is equal to a null pointer
12697 /// \param Range Extra SourceRange to highlight in the diagnostic
DiagnoseAlwaysNonNullPointer(Expr * E,Expr::NullPointerConstantKind NullKind,bool IsEqual,SourceRange Range)12698 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
12699 Expr::NullPointerConstantKind NullKind,
12700 bool IsEqual, SourceRange Range) {
12701 if (!E)
12702 return;
12703
12704 // Don't warn inside macros.
12705 if (E->getExprLoc().isMacroID()) {
12706 const SourceManager &SM = getSourceManager();
12707 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
12708 IsInAnyMacroBody(SM, Range.getBegin()))
12709 return;
12710 }
12711 E = E->IgnoreImpCasts();
12712
12713 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
12714
12715 if (isa<CXXThisExpr>(E)) {
12716 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
12717 : diag::warn_this_bool_conversion;
12718 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
12719 return;
12720 }
12721
12722 bool IsAddressOf = false;
12723
12724 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
12725 if (UO->getOpcode() != UO_AddrOf)
12726 return;
12727 IsAddressOf = true;
12728 E = UO->getSubExpr();
12729 }
12730
12731 if (IsAddressOf) {
12732 unsigned DiagID = IsCompare
12733 ? diag::warn_address_of_reference_null_compare
12734 : diag::warn_address_of_reference_bool_conversion;
12735 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
12736 << IsEqual;
12737 if (CheckForReference(*this, E, PD)) {
12738 return;
12739 }
12740 }
12741
12742 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
12743 bool IsParam = isa<NonNullAttr>(NonnullAttr);
12744 std::string Str;
12745 llvm::raw_string_ostream S(Str);
12746 E->printPretty(S, nullptr, getPrintingPolicy());
12747 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
12748 : diag::warn_cast_nonnull_to_bool;
12749 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
12750 << E->getSourceRange() << Range << IsEqual;
12751 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
12752 };
12753
12754 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
12755 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
12756 if (auto *Callee = Call->getDirectCallee()) {
12757 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
12758 ComplainAboutNonnullParamOrCall(A);
12759 return;
12760 }
12761 }
12762 }
12763
12764 // Expect to find a single Decl. Skip anything more complicated.
12765 ValueDecl *D = nullptr;
12766 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
12767 D = R->getDecl();
12768 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
12769 D = M->getMemberDecl();
12770 }
12771
12772 // Weak Decls can be null.
12773 if (!D || D->isWeak())
12774 return;
12775
12776 // Check for parameter decl with nonnull attribute
12777 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
12778 if (getCurFunction() &&
12779 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
12780 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
12781 ComplainAboutNonnullParamOrCall(A);
12782 return;
12783 }
12784
12785 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
12786 // Skip function template not specialized yet.
12787 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
12788 return;
12789 auto ParamIter = llvm::find(FD->parameters(), PV);
12790 assert(ParamIter != FD->param_end());
12791 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
12792
12793 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
12794 if (!NonNull->args_size()) {
12795 ComplainAboutNonnullParamOrCall(NonNull);
12796 return;
12797 }
12798
12799 for (const ParamIdx &ArgNo : NonNull->args()) {
12800 if (ArgNo.getASTIndex() == ParamNo) {
12801 ComplainAboutNonnullParamOrCall(NonNull);
12802 return;
12803 }
12804 }
12805 }
12806 }
12807 }
12808 }
12809
12810 QualType T = D->getType();
12811 const bool IsArray = T->isArrayType();
12812 const bool IsFunction = T->isFunctionType();
12813
12814 // Address of function is used to silence the function warning.
12815 if (IsAddressOf && IsFunction) {
12816 return;
12817 }
12818
12819 // Found nothing.
12820 if (!IsAddressOf && !IsFunction && !IsArray)
12821 return;
12822
12823 // Pretty print the expression for the diagnostic.
12824 std::string Str;
12825 llvm::raw_string_ostream S(Str);
12826 E->printPretty(S, nullptr, getPrintingPolicy());
12827
12828 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
12829 : diag::warn_impcast_pointer_to_bool;
12830 enum {
12831 AddressOf,
12832 FunctionPointer,
12833 ArrayPointer
12834 } DiagType;
12835 if (IsAddressOf)
12836 DiagType = AddressOf;
12837 else if (IsFunction)
12838 DiagType = FunctionPointer;
12839 else if (IsArray)
12840 DiagType = ArrayPointer;
12841 else
12842 llvm_unreachable("Could not determine diagnostic.");
12843 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
12844 << Range << IsEqual;
12845
12846 if (!IsFunction)
12847 return;
12848
12849 // Suggest '&' to silence the function warning.
12850 Diag(E->getExprLoc(), diag::note_function_warning_silence)
12851 << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
12852
12853 // Check to see if '()' fixit should be emitted.
12854 QualType ReturnType;
12855 UnresolvedSet<4> NonTemplateOverloads;
12856 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
12857 if (ReturnType.isNull())
12858 return;
12859
12860 if (IsCompare) {
12861 // There are two cases here. If there is null constant, the only suggest
12862 // for a pointer return type. If the null is 0, then suggest if the return
12863 // type is a pointer or an integer type.
12864 if (!ReturnType->isPointerType()) {
12865 if (NullKind == Expr::NPCK_ZeroExpression ||
12866 NullKind == Expr::NPCK_ZeroLiteral) {
12867 if (!ReturnType->isIntegerType())
12868 return;
12869 } else {
12870 return;
12871 }
12872 }
12873 } else { // !IsCompare
12874 // For function to bool, only suggest if the function pointer has bool
12875 // return type.
12876 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
12877 return;
12878 }
12879 Diag(E->getExprLoc(), diag::note_function_to_function_call)
12880 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
12881 }
12882
12883 /// Diagnoses "dangerous" implicit conversions within the given
12884 /// expression (which is a full expression). Implements -Wconversion
12885 /// and -Wsign-compare.
12886 ///
12887 /// \param CC the "context" location of the implicit conversion, i.e.
12888 /// the most location of the syntactic entity requiring the implicit
12889 /// conversion
CheckImplicitConversions(Expr * E,SourceLocation CC)12890 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
12891 // Don't diagnose in unevaluated contexts.
12892 if (isUnevaluatedContext())
12893 return;
12894
12895 // Don't diagnose for value- or type-dependent expressions.
12896 if (E->isTypeDependent() || E->isValueDependent())
12897 return;
12898
12899 // Check for array bounds violations in cases where the check isn't triggered
12900 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
12901 // ArraySubscriptExpr is on the RHS of a variable initialization.
12902 CheckArrayAccess(E);
12903
12904 // This is not the right CC for (e.g.) a variable initialization.
12905 AnalyzeImplicitConversions(*this, E, CC);
12906 }
12907
12908 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
12909 /// Input argument E is a logical expression.
CheckBoolLikeConversion(Expr * E,SourceLocation CC)12910 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
12911 ::CheckBoolLikeConversion(*this, E, CC);
12912 }
12913
12914 /// Diagnose when expression is an integer constant expression and its evaluation
12915 /// results in integer overflow
CheckForIntOverflow(Expr * E)12916 void Sema::CheckForIntOverflow (Expr *E) {
12917 // Use a work list to deal with nested struct initializers.
12918 SmallVector<Expr *, 2> Exprs(1, E);
12919
12920 do {
12921 Expr *OriginalE = Exprs.pop_back_val();
12922 Expr *E = OriginalE->IgnoreParenCasts();
12923
12924 if (isa<BinaryOperator>(E)) {
12925 E->EvaluateForOverflow(Context);
12926 continue;
12927 }
12928
12929 if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
12930 Exprs.append(InitList->inits().begin(), InitList->inits().end());
12931 else if (isa<ObjCBoxedExpr>(OriginalE))
12932 E->EvaluateForOverflow(Context);
12933 else if (auto Call = dyn_cast<CallExpr>(E))
12934 Exprs.append(Call->arg_begin(), Call->arg_end());
12935 else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
12936 Exprs.append(Message->arg_begin(), Message->arg_end());
12937 } while (!Exprs.empty());
12938 }
12939
12940 namespace {
12941
12942 /// Visitor for expressions which looks for unsequenced operations on the
12943 /// same object.
12944 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
12945 using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
12946
12947 /// A tree of sequenced regions within an expression. Two regions are
12948 /// unsequenced if one is an ancestor or a descendent of the other. When we
12949 /// finish processing an expression with sequencing, such as a comma
12950 /// expression, we fold its tree nodes into its parent, since they are
12951 /// unsequenced with respect to nodes we will visit later.
12952 class SequenceTree {
12953 struct Value {
Value__anon33aba9e81e11::SequenceChecker::SequenceTree::Value12954 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
12955 unsigned Parent : 31;
12956 unsigned Merged : 1;
12957 };
12958 SmallVector<Value, 8> Values;
12959
12960 public:
12961 /// A region within an expression which may be sequenced with respect
12962 /// to some other region.
12963 class Seq {
12964 friend class SequenceTree;
12965
12966 unsigned Index;
12967
Seq(unsigned N)12968 explicit Seq(unsigned N) : Index(N) {}
12969
12970 public:
Seq()12971 Seq() : Index(0) {}
12972 };
12973
SequenceTree()12974 SequenceTree() { Values.push_back(Value(0)); }
root() const12975 Seq root() const { return Seq(0); }
12976
12977 /// Create a new sequence of operations, which is an unsequenced
12978 /// subset of \p Parent. This sequence of operations is sequenced with
12979 /// respect to other children of \p Parent.
allocate(Seq Parent)12980 Seq allocate(Seq Parent) {
12981 Values.push_back(Value(Parent.Index));
12982 return Seq(Values.size() - 1);
12983 }
12984
12985 /// Merge a sequence of operations into its parent.
merge(Seq S)12986 void merge(Seq S) {
12987 Values[S.Index].Merged = true;
12988 }
12989
12990 /// Determine whether two operations are unsequenced. This operation
12991 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
12992 /// should have been merged into its parent as appropriate.
isUnsequenced(Seq Cur,Seq Old)12993 bool isUnsequenced(Seq Cur, Seq Old) {
12994 unsigned C = representative(Cur.Index);
12995 unsigned Target = representative(Old.Index);
12996 while (C >= Target) {
12997 if (C == Target)
12998 return true;
12999 C = Values[C].Parent;
13000 }
13001 return false;
13002 }
13003
13004 private:
13005 /// Pick a representative for a sequence.
representative(unsigned K)13006 unsigned representative(unsigned K) {
13007 if (Values[K].Merged)
13008 // Perform path compression as we go.
13009 return Values[K].Parent = representative(Values[K].Parent);
13010 return K;
13011 }
13012 };
13013
13014 /// An object for which we can track unsequenced uses.
13015 using Object = const NamedDecl *;
13016
13017 /// Different flavors of object usage which we track. We only track the
13018 /// least-sequenced usage of each kind.
13019 enum UsageKind {
13020 /// A read of an object. Multiple unsequenced reads are OK.
13021 UK_Use,
13022
13023 /// A modification of an object which is sequenced before the value
13024 /// computation of the expression, such as ++n in C++.
13025 UK_ModAsValue,
13026
13027 /// A modification of an object which is not sequenced before the value
13028 /// computation of the expression, such as n++.
13029 UK_ModAsSideEffect,
13030
13031 UK_Count = UK_ModAsSideEffect + 1
13032 };
13033
13034 /// Bundle together a sequencing region and the expression corresponding
13035 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
13036 struct Usage {
13037 const Expr *UsageExpr;
13038 SequenceTree::Seq Seq;
13039
Usage__anon33aba9e81e11::SequenceChecker::Usage13040 Usage() : UsageExpr(nullptr), Seq() {}
13041 };
13042
13043 struct UsageInfo {
13044 Usage Uses[UK_Count];
13045
13046 /// Have we issued a diagnostic for this object already?
13047 bool Diagnosed;
13048
UsageInfo__anon33aba9e81e11::SequenceChecker::UsageInfo13049 UsageInfo() : Uses(), Diagnosed(false) {}
13050 };
13051 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
13052
13053 Sema &SemaRef;
13054
13055 /// Sequenced regions within the expression.
13056 SequenceTree Tree;
13057
13058 /// Declaration modifications and references which we have seen.
13059 UsageInfoMap UsageMap;
13060
13061 /// The region we are currently within.
13062 SequenceTree::Seq Region;
13063
13064 /// Filled in with declarations which were modified as a side-effect
13065 /// (that is, post-increment operations).
13066 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
13067
13068 /// Expressions to check later. We defer checking these to reduce
13069 /// stack usage.
13070 SmallVectorImpl<const Expr *> &WorkList;
13071
13072 /// RAII object wrapping the visitation of a sequenced subexpression of an
13073 /// expression. At the end of this process, the side-effects of the evaluation
13074 /// become sequenced with respect to the value computation of the result, so
13075 /// we downgrade any UK_ModAsSideEffect within the evaluation to
13076 /// UK_ModAsValue.
13077 struct SequencedSubexpression {
SequencedSubexpression__anon33aba9e81e11::SequenceChecker::SequencedSubexpression13078 SequencedSubexpression(SequenceChecker &Self)
13079 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
13080 Self.ModAsSideEffect = &ModAsSideEffect;
13081 }
13082
~SequencedSubexpression__anon33aba9e81e11::SequenceChecker::SequencedSubexpression13083 ~SequencedSubexpression() {
13084 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
13085 // Add a new usage with usage kind UK_ModAsValue, and then restore
13086 // the previous usage with UK_ModAsSideEffect (thus clearing it if
13087 // the previous one was empty).
13088 UsageInfo &UI = Self.UsageMap[M.first];
13089 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
13090 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
13091 SideEffectUsage = M.second;
13092 }
13093 Self.ModAsSideEffect = OldModAsSideEffect;
13094 }
13095
13096 SequenceChecker &Self;
13097 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
13098 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
13099 };
13100
13101 /// RAII object wrapping the visitation of a subexpression which we might
13102 /// choose to evaluate as a constant. If any subexpression is evaluated and
13103 /// found to be non-constant, this allows us to suppress the evaluation of
13104 /// the outer expression.
13105 class EvaluationTracker {
13106 public:
EvaluationTracker(SequenceChecker & Self)13107 EvaluationTracker(SequenceChecker &Self)
13108 : Self(Self), Prev(Self.EvalTracker) {
13109 Self.EvalTracker = this;
13110 }
13111
~EvaluationTracker()13112 ~EvaluationTracker() {
13113 Self.EvalTracker = Prev;
13114 if (Prev)
13115 Prev->EvalOK &= EvalOK;
13116 }
13117
evaluate(const Expr * E,bool & Result)13118 bool evaluate(const Expr *E, bool &Result) {
13119 if (!EvalOK || E->isValueDependent())
13120 return false;
13121 EvalOK = E->EvaluateAsBooleanCondition(
13122 Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
13123 return EvalOK;
13124 }
13125
13126 private:
13127 SequenceChecker &Self;
13128 EvaluationTracker *Prev;
13129 bool EvalOK = true;
13130 } *EvalTracker = nullptr;
13131
13132 /// Find the object which is produced by the specified expression,
13133 /// if any.
getObject(const Expr * E,bool Mod) const13134 Object getObject(const Expr *E, bool Mod) const {
13135 E = E->IgnoreParenCasts();
13136 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
13137 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
13138 return getObject(UO->getSubExpr(), Mod);
13139 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13140 if (BO->getOpcode() == BO_Comma)
13141 return getObject(BO->getRHS(), Mod);
13142 if (Mod && BO->isAssignmentOp())
13143 return getObject(BO->getLHS(), Mod);
13144 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13145 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
13146 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
13147 return ME->getMemberDecl();
13148 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13149 // FIXME: If this is a reference, map through to its value.
13150 return DRE->getDecl();
13151 return nullptr;
13152 }
13153
13154 /// Note that an object \p O was modified or used by an expression
13155 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
13156 /// the object \p O as obtained via the \p UsageMap.
addUsage(Object O,UsageInfo & UI,const Expr * UsageExpr,UsageKind UK)13157 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
13158 // Get the old usage for the given object and usage kind.
13159 Usage &U = UI.Uses[UK];
13160 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
13161 // If we have a modification as side effect and are in a sequenced
13162 // subexpression, save the old Usage so that we can restore it later
13163 // in SequencedSubexpression::~SequencedSubexpression.
13164 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
13165 ModAsSideEffect->push_back(std::make_pair(O, U));
13166 // Then record the new usage with the current sequencing region.
13167 U.UsageExpr = UsageExpr;
13168 U.Seq = Region;
13169 }
13170 }
13171
13172 /// Check whether a modification or use of an object \p O in an expression
13173 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
13174 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
13175 /// \p IsModMod is true when we are checking for a mod-mod unsequenced
13176 /// usage and false we are checking for a mod-use unsequenced usage.
checkUsage(Object O,UsageInfo & UI,const Expr * UsageExpr,UsageKind OtherKind,bool IsModMod)13177 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
13178 UsageKind OtherKind, bool IsModMod) {
13179 if (UI.Diagnosed)
13180 return;
13181
13182 const Usage &U = UI.Uses[OtherKind];
13183 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
13184 return;
13185
13186 const Expr *Mod = U.UsageExpr;
13187 const Expr *ModOrUse = UsageExpr;
13188 if (OtherKind == UK_Use)
13189 std::swap(Mod, ModOrUse);
13190
13191 SemaRef.DiagRuntimeBehavior(
13192 Mod->getExprLoc(), {Mod, ModOrUse},
13193 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
13194 : diag::warn_unsequenced_mod_use)
13195 << O << SourceRange(ModOrUse->getExprLoc()));
13196 UI.Diagnosed = true;
13197 }
13198
13199 // A note on note{Pre, Post}{Use, Mod}:
13200 //
13201 // (It helps to follow the algorithm with an expression such as
13202 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
13203 // operations before C++17 and both are well-defined in C++17).
13204 //
13205 // When visiting a node which uses/modify an object we first call notePreUse
13206 // or notePreMod before visiting its sub-expression(s). At this point the
13207 // children of the current node have not yet been visited and so the eventual
13208 // uses/modifications resulting from the children of the current node have not
13209 // been recorded yet.
13210 //
13211 // We then visit the children of the current node. After that notePostUse or
13212 // notePostMod is called. These will 1) detect an unsequenced modification
13213 // as side effect (as in "k++ + k") and 2) add a new usage with the
13214 // appropriate usage kind.
13215 //
13216 // We also have to be careful that some operation sequences modification as
13217 // side effect as well (for example: || or ,). To account for this we wrap
13218 // the visitation of such a sub-expression (for example: the LHS of || or ,)
13219 // with SequencedSubexpression. SequencedSubexpression is an RAII object
13220 // which record usages which are modifications as side effect, and then
13221 // downgrade them (or more accurately restore the previous usage which was a
13222 // modification as side effect) when exiting the scope of the sequenced
13223 // subexpression.
13224
notePreUse(Object O,const Expr * UseExpr)13225 void notePreUse(Object O, const Expr *UseExpr) {
13226 UsageInfo &UI = UsageMap[O];
13227 // Uses conflict with other modifications.
13228 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
13229 }
13230
notePostUse(Object O,const Expr * UseExpr)13231 void notePostUse(Object O, const Expr *UseExpr) {
13232 UsageInfo &UI = UsageMap[O];
13233 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
13234 /*IsModMod=*/false);
13235 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
13236 }
13237
notePreMod(Object O,const Expr * ModExpr)13238 void notePreMod(Object O, const Expr *ModExpr) {
13239 UsageInfo &UI = UsageMap[O];
13240 // Modifications conflict with other modifications and with uses.
13241 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
13242 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
13243 }
13244
notePostMod(Object O,const Expr * ModExpr,UsageKind UK)13245 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
13246 UsageInfo &UI = UsageMap[O];
13247 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
13248 /*IsModMod=*/true);
13249 addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
13250 }
13251
13252 public:
SequenceChecker(Sema & S,const Expr * E,SmallVectorImpl<const Expr * > & WorkList)13253 SequenceChecker(Sema &S, const Expr *E,
13254 SmallVectorImpl<const Expr *> &WorkList)
13255 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
13256 Visit(E);
13257 // Silence a -Wunused-private-field since WorkList is now unused.
13258 // TODO: Evaluate if it can be used, and if not remove it.
13259 (void)this->WorkList;
13260 }
13261
VisitStmt(const Stmt * S)13262 void VisitStmt(const Stmt *S) {
13263 // Skip all statements which aren't expressions for now.
13264 }
13265
VisitExpr(const Expr * E)13266 void VisitExpr(const Expr *E) {
13267 // By default, just recurse to evaluated subexpressions.
13268 Base::VisitStmt(E);
13269 }
13270
VisitCastExpr(const CastExpr * E)13271 void VisitCastExpr(const CastExpr *E) {
13272 Object O = Object();
13273 if (E->getCastKind() == CK_LValueToRValue)
13274 O = getObject(E->getSubExpr(), false);
13275
13276 if (O)
13277 notePreUse(O, E);
13278 VisitExpr(E);
13279 if (O)
13280 notePostUse(O, E);
13281 }
13282
VisitSequencedExpressions(const Expr * SequencedBefore,const Expr * SequencedAfter)13283 void VisitSequencedExpressions(const Expr *SequencedBefore,
13284 const Expr *SequencedAfter) {
13285 SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
13286 SequenceTree::Seq AfterRegion = Tree.allocate(Region);
13287 SequenceTree::Seq OldRegion = Region;
13288
13289 {
13290 SequencedSubexpression SeqBefore(*this);
13291 Region = BeforeRegion;
13292 Visit(SequencedBefore);
13293 }
13294
13295 Region = AfterRegion;
13296 Visit(SequencedAfter);
13297
13298 Region = OldRegion;
13299
13300 Tree.merge(BeforeRegion);
13301 Tree.merge(AfterRegion);
13302 }
13303
VisitArraySubscriptExpr(const ArraySubscriptExpr * ASE)13304 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
13305 // C++17 [expr.sub]p1:
13306 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
13307 // expression E1 is sequenced before the expression E2.
13308 if (SemaRef.getLangOpts().CPlusPlus17)
13309 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
13310 else {
13311 Visit(ASE->getLHS());
13312 Visit(ASE->getRHS());
13313 }
13314 }
13315
VisitBinPtrMemD(const BinaryOperator * BO)13316 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
VisitBinPtrMemI(const BinaryOperator * BO)13317 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
VisitBinPtrMem(const BinaryOperator * BO)13318 void VisitBinPtrMem(const BinaryOperator *BO) {
13319 // C++17 [expr.mptr.oper]p4:
13320 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
13321 // the expression E1 is sequenced before the expression E2.
13322 if (SemaRef.getLangOpts().CPlusPlus17)
13323 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13324 else {
13325 Visit(BO->getLHS());
13326 Visit(BO->getRHS());
13327 }
13328 }
13329
VisitBinShl(const BinaryOperator * BO)13330 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
VisitBinShr(const BinaryOperator * BO)13331 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
VisitBinShlShr(const BinaryOperator * BO)13332 void VisitBinShlShr(const BinaryOperator *BO) {
13333 // C++17 [expr.shift]p4:
13334 // The expression E1 is sequenced before the expression E2.
13335 if (SemaRef.getLangOpts().CPlusPlus17)
13336 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13337 else {
13338 Visit(BO->getLHS());
13339 Visit(BO->getRHS());
13340 }
13341 }
13342
VisitBinComma(const BinaryOperator * BO)13343 void VisitBinComma(const BinaryOperator *BO) {
13344 // C++11 [expr.comma]p1:
13345 // Every value computation and side effect associated with the left
13346 // expression is sequenced before every value computation and side
13347 // effect associated with the right expression.
13348 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13349 }
13350
VisitBinAssign(const BinaryOperator * BO)13351 void VisitBinAssign(const BinaryOperator *BO) {
13352 SequenceTree::Seq RHSRegion;
13353 SequenceTree::Seq LHSRegion;
13354 if (SemaRef.getLangOpts().CPlusPlus17) {
13355 RHSRegion = Tree.allocate(Region);
13356 LHSRegion = Tree.allocate(Region);
13357 } else {
13358 RHSRegion = Region;
13359 LHSRegion = Region;
13360 }
13361 SequenceTree::Seq OldRegion = Region;
13362
13363 // C++11 [expr.ass]p1:
13364 // [...] the assignment is sequenced after the value computation
13365 // of the right and left operands, [...]
13366 //
13367 // so check it before inspecting the operands and update the
13368 // map afterwards.
13369 Object O = getObject(BO->getLHS(), /*Mod=*/true);
13370 if (O)
13371 notePreMod(O, BO);
13372
13373 if (SemaRef.getLangOpts().CPlusPlus17) {
13374 // C++17 [expr.ass]p1:
13375 // [...] The right operand is sequenced before the left operand. [...]
13376 {
13377 SequencedSubexpression SeqBefore(*this);
13378 Region = RHSRegion;
13379 Visit(BO->getRHS());
13380 }
13381
13382 Region = LHSRegion;
13383 Visit(BO->getLHS());
13384
13385 if (O && isa<CompoundAssignOperator>(BO))
13386 notePostUse(O, BO);
13387
13388 } else {
13389 // C++11 does not specify any sequencing between the LHS and RHS.
13390 Region = LHSRegion;
13391 Visit(BO->getLHS());
13392
13393 if (O && isa<CompoundAssignOperator>(BO))
13394 notePostUse(O, BO);
13395
13396 Region = RHSRegion;
13397 Visit(BO->getRHS());
13398 }
13399
13400 // C++11 [expr.ass]p1:
13401 // the assignment is sequenced [...] before the value computation of the
13402 // assignment expression.
13403 // C11 6.5.16/3 has no such rule.
13404 Region = OldRegion;
13405 if (O)
13406 notePostMod(O, BO,
13407 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
13408 : UK_ModAsSideEffect);
13409 if (SemaRef.getLangOpts().CPlusPlus17) {
13410 Tree.merge(RHSRegion);
13411 Tree.merge(LHSRegion);
13412 }
13413 }
13414
VisitCompoundAssignOperator(const CompoundAssignOperator * CAO)13415 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
13416 VisitBinAssign(CAO);
13417 }
13418
VisitUnaryPreInc(const UnaryOperator * UO)13419 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
VisitUnaryPreDec(const UnaryOperator * UO)13420 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
VisitUnaryPreIncDec(const UnaryOperator * UO)13421 void VisitUnaryPreIncDec(const UnaryOperator *UO) {
13422 Object O = getObject(UO->getSubExpr(), true);
13423 if (!O)
13424 return VisitExpr(UO);
13425
13426 notePreMod(O, UO);
13427 Visit(UO->getSubExpr());
13428 // C++11 [expr.pre.incr]p1:
13429 // the expression ++x is equivalent to x+=1
13430 notePostMod(O, UO,
13431 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
13432 : UK_ModAsSideEffect);
13433 }
13434
VisitUnaryPostInc(const UnaryOperator * UO)13435 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
VisitUnaryPostDec(const UnaryOperator * UO)13436 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
VisitUnaryPostIncDec(const UnaryOperator * UO)13437 void VisitUnaryPostIncDec(const UnaryOperator *UO) {
13438 Object O = getObject(UO->getSubExpr(), true);
13439 if (!O)
13440 return VisitExpr(UO);
13441
13442 notePreMod(O, UO);
13443 Visit(UO->getSubExpr());
13444 notePostMod(O, UO, UK_ModAsSideEffect);
13445 }
13446
VisitBinLOr(const BinaryOperator * BO)13447 void VisitBinLOr(const BinaryOperator *BO) {
13448 // C++11 [expr.log.or]p2:
13449 // If the second expression is evaluated, every value computation and
13450 // side effect associated with the first expression is sequenced before
13451 // every value computation and side effect associated with the
13452 // second expression.
13453 SequenceTree::Seq LHSRegion = Tree.allocate(Region);
13454 SequenceTree::Seq RHSRegion = Tree.allocate(Region);
13455 SequenceTree::Seq OldRegion = Region;
13456
13457 EvaluationTracker Eval(*this);
13458 {
13459 SequencedSubexpression Sequenced(*this);
13460 Region = LHSRegion;
13461 Visit(BO->getLHS());
13462 }
13463
13464 // C++11 [expr.log.or]p1:
13465 // [...] the second operand is not evaluated if the first operand
13466 // evaluates to true.
13467 bool EvalResult = false;
13468 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
13469 bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult);
13470 if (ShouldVisitRHS) {
13471 Region = RHSRegion;
13472 Visit(BO->getRHS());
13473 }
13474
13475 Region = OldRegion;
13476 Tree.merge(LHSRegion);
13477 Tree.merge(RHSRegion);
13478 }
13479
VisitBinLAnd(const BinaryOperator * BO)13480 void VisitBinLAnd(const BinaryOperator *BO) {
13481 // C++11 [expr.log.and]p2:
13482 // If the second expression is evaluated, every value computation and
13483 // side effect associated with the first expression is sequenced before
13484 // every value computation and side effect associated with the
13485 // second expression.
13486 SequenceTree::Seq LHSRegion = Tree.allocate(Region);
13487 SequenceTree::Seq RHSRegion = Tree.allocate(Region);
13488 SequenceTree::Seq OldRegion = Region;
13489
13490 EvaluationTracker Eval(*this);
13491 {
13492 SequencedSubexpression Sequenced(*this);
13493 Region = LHSRegion;
13494 Visit(BO->getLHS());
13495 }
13496
13497 // C++11 [expr.log.and]p1:
13498 // [...] the second operand is not evaluated if the first operand is false.
13499 bool EvalResult = false;
13500 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
13501 bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult);
13502 if (ShouldVisitRHS) {
13503 Region = RHSRegion;
13504 Visit(BO->getRHS());
13505 }
13506
13507 Region = OldRegion;
13508 Tree.merge(LHSRegion);
13509 Tree.merge(RHSRegion);
13510 }
13511
VisitAbstractConditionalOperator(const AbstractConditionalOperator * CO)13512 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
13513 // C++11 [expr.cond]p1:
13514 // [...] Every value computation and side effect associated with the first
13515 // expression is sequenced before every value computation and side effect
13516 // associated with the second or third expression.
13517 SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
13518
13519 // No sequencing is specified between the true and false expression.
13520 // However since exactly one of both is going to be evaluated we can
13521 // consider them to be sequenced. This is needed to avoid warning on
13522 // something like "x ? y+= 1 : y += 2;" in the case where we will visit
13523 // both the true and false expressions because we can't evaluate x.
13524 // This will still allow us to detect an expression like (pre C++17)
13525 // "(x ? y += 1 : y += 2) = y".
13526 //
13527 // We don't wrap the visitation of the true and false expression with
13528 // SequencedSubexpression because we don't want to downgrade modifications
13529 // as side effect in the true and false expressions after the visition
13530 // is done. (for example in the expression "(x ? y++ : y++) + y" we should
13531 // not warn between the two "y++", but we should warn between the "y++"
13532 // and the "y".
13533 SequenceTree::Seq TrueRegion = Tree.allocate(Region);
13534 SequenceTree::Seq FalseRegion = Tree.allocate(Region);
13535 SequenceTree::Seq OldRegion = Region;
13536
13537 EvaluationTracker Eval(*this);
13538 {
13539 SequencedSubexpression Sequenced(*this);
13540 Region = ConditionRegion;
13541 Visit(CO->getCond());
13542 }
13543
13544 // C++11 [expr.cond]p1:
13545 // [...] The first expression is contextually converted to bool (Clause 4).
13546 // It is evaluated and if it is true, the result of the conditional
13547 // expression is the value of the second expression, otherwise that of the
13548 // third expression. Only one of the second and third expressions is
13549 // evaluated. [...]
13550 bool EvalResult = false;
13551 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
13552 bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult);
13553 bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult);
13554 if (ShouldVisitTrueExpr) {
13555 Region = TrueRegion;
13556 Visit(CO->getTrueExpr());
13557 }
13558 if (ShouldVisitFalseExpr) {
13559 Region = FalseRegion;
13560 Visit(CO->getFalseExpr());
13561 }
13562
13563 Region = OldRegion;
13564 Tree.merge(ConditionRegion);
13565 Tree.merge(TrueRegion);
13566 Tree.merge(FalseRegion);
13567 }
13568
VisitCallExpr(const CallExpr * CE)13569 void VisitCallExpr(const CallExpr *CE) {
13570 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
13571
13572 if (CE->isUnevaluatedBuiltinCall(Context))
13573 return;
13574
13575 // C++11 [intro.execution]p15:
13576 // When calling a function [...], every value computation and side effect
13577 // associated with any argument expression, or with the postfix expression
13578 // designating the called function, is sequenced before execution of every
13579 // expression or statement in the body of the function [and thus before
13580 // the value computation of its result].
13581 SequencedSubexpression Sequenced(*this);
13582 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
13583 // C++17 [expr.call]p5
13584 // The postfix-expression is sequenced before each expression in the
13585 // expression-list and any default argument. [...]
13586 SequenceTree::Seq CalleeRegion;
13587 SequenceTree::Seq OtherRegion;
13588 if (SemaRef.getLangOpts().CPlusPlus17) {
13589 CalleeRegion = Tree.allocate(Region);
13590 OtherRegion = Tree.allocate(Region);
13591 } else {
13592 CalleeRegion = Region;
13593 OtherRegion = Region;
13594 }
13595 SequenceTree::Seq OldRegion = Region;
13596
13597 // Visit the callee expression first.
13598 Region = CalleeRegion;
13599 if (SemaRef.getLangOpts().CPlusPlus17) {
13600 SequencedSubexpression Sequenced(*this);
13601 Visit(CE->getCallee());
13602 } else {
13603 Visit(CE->getCallee());
13604 }
13605
13606 // Then visit the argument expressions.
13607 Region = OtherRegion;
13608 for (const Expr *Argument : CE->arguments())
13609 Visit(Argument);
13610
13611 Region = OldRegion;
13612 if (SemaRef.getLangOpts().CPlusPlus17) {
13613 Tree.merge(CalleeRegion);
13614 Tree.merge(OtherRegion);
13615 }
13616 });
13617 }
13618
VisitCXXOperatorCallExpr(const CXXOperatorCallExpr * CXXOCE)13619 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
13620 // C++17 [over.match.oper]p2:
13621 // [...] the operator notation is first transformed to the equivalent
13622 // function-call notation as summarized in Table 12 (where @ denotes one
13623 // of the operators covered in the specified subclause). However, the
13624 // operands are sequenced in the order prescribed for the built-in
13625 // operator (Clause 8).
13626 //
13627 // From the above only overloaded binary operators and overloaded call
13628 // operators have sequencing rules in C++17 that we need to handle
13629 // separately.
13630 if (!SemaRef.getLangOpts().CPlusPlus17 ||
13631 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
13632 return VisitCallExpr(CXXOCE);
13633
13634 enum {
13635 NoSequencing,
13636 LHSBeforeRHS,
13637 RHSBeforeLHS,
13638 LHSBeforeRest
13639 } SequencingKind;
13640 switch (CXXOCE->getOperator()) {
13641 case OO_Equal:
13642 case OO_PlusEqual:
13643 case OO_MinusEqual:
13644 case OO_StarEqual:
13645 case OO_SlashEqual:
13646 case OO_PercentEqual:
13647 case OO_CaretEqual:
13648 case OO_AmpEqual:
13649 case OO_PipeEqual:
13650 case OO_LessLessEqual:
13651 case OO_GreaterGreaterEqual:
13652 SequencingKind = RHSBeforeLHS;
13653 break;
13654
13655 case OO_LessLess:
13656 case OO_GreaterGreater:
13657 case OO_AmpAmp:
13658 case OO_PipePipe:
13659 case OO_Comma:
13660 case OO_ArrowStar:
13661 case OO_Subscript:
13662 SequencingKind = LHSBeforeRHS;
13663 break;
13664
13665 case OO_Call:
13666 SequencingKind = LHSBeforeRest;
13667 break;
13668
13669 default:
13670 SequencingKind = NoSequencing;
13671 break;
13672 }
13673
13674 if (SequencingKind == NoSequencing)
13675 return VisitCallExpr(CXXOCE);
13676
13677 // This is a call, so all subexpressions are sequenced before the result.
13678 SequencedSubexpression Sequenced(*this);
13679
13680 SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
13681 assert(SemaRef.getLangOpts().CPlusPlus17 &&
13682 "Should only get there with C++17 and above!");
13683 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
13684 "Should only get there with an overloaded binary operator"
13685 " or an overloaded call operator!");
13686
13687 if (SequencingKind == LHSBeforeRest) {
13688 assert(CXXOCE->getOperator() == OO_Call &&
13689 "We should only have an overloaded call operator here!");
13690
13691 // This is very similar to VisitCallExpr, except that we only have the
13692 // C++17 case. The postfix-expression is the first argument of the
13693 // CXXOperatorCallExpr. The expressions in the expression-list, if any,
13694 // are in the following arguments.
13695 //
13696 // Note that we intentionally do not visit the callee expression since
13697 // it is just a decayed reference to a function.
13698 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
13699 SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
13700 SequenceTree::Seq OldRegion = Region;
13701
13702 assert(CXXOCE->getNumArgs() >= 1 &&
13703 "An overloaded call operator must have at least one argument"
13704 " for the postfix-expression!");
13705 const Expr *PostfixExpr = CXXOCE->getArgs()[0];
13706 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
13707 CXXOCE->getNumArgs() - 1);
13708
13709 // Visit the postfix-expression first.
13710 {
13711 Region = PostfixExprRegion;
13712 SequencedSubexpression Sequenced(*this);
13713 Visit(PostfixExpr);
13714 }
13715
13716 // Then visit the argument expressions.
13717 Region = ArgsRegion;
13718 for (const Expr *Arg : Args)
13719 Visit(Arg);
13720
13721 Region = OldRegion;
13722 Tree.merge(PostfixExprRegion);
13723 Tree.merge(ArgsRegion);
13724 } else {
13725 assert(CXXOCE->getNumArgs() == 2 &&
13726 "Should only have two arguments here!");
13727 assert((SequencingKind == LHSBeforeRHS ||
13728 SequencingKind == RHSBeforeLHS) &&
13729 "Unexpected sequencing kind!");
13730
13731 // We do not visit the callee expression since it is just a decayed
13732 // reference to a function.
13733 const Expr *E1 = CXXOCE->getArg(0);
13734 const Expr *E2 = CXXOCE->getArg(1);
13735 if (SequencingKind == RHSBeforeLHS)
13736 std::swap(E1, E2);
13737
13738 return VisitSequencedExpressions(E1, E2);
13739 }
13740 });
13741 }
13742
VisitCXXConstructExpr(const CXXConstructExpr * CCE)13743 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
13744 // This is a call, so all subexpressions are sequenced before the result.
13745 SequencedSubexpression Sequenced(*this);
13746
13747 if (!CCE->isListInitialization())
13748 return VisitExpr(CCE);
13749
13750 // In C++11, list initializations are sequenced.
13751 SmallVector<SequenceTree::Seq, 32> Elts;
13752 SequenceTree::Seq Parent = Region;
13753 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
13754 E = CCE->arg_end();
13755 I != E; ++I) {
13756 Region = Tree.allocate(Parent);
13757 Elts.push_back(Region);
13758 Visit(*I);
13759 }
13760
13761 // Forget that the initializers are sequenced.
13762 Region = Parent;
13763 for (unsigned I = 0; I < Elts.size(); ++I)
13764 Tree.merge(Elts[I]);
13765 }
13766
VisitInitListExpr(const InitListExpr * ILE)13767 void VisitInitListExpr(const InitListExpr *ILE) {
13768 if (!SemaRef.getLangOpts().CPlusPlus11)
13769 return VisitExpr(ILE);
13770
13771 // In C++11, list initializations are sequenced.
13772 SmallVector<SequenceTree::Seq, 32> Elts;
13773 SequenceTree::Seq Parent = Region;
13774 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
13775 const Expr *E = ILE->getInit(I);
13776 if (!E)
13777 continue;
13778 Region = Tree.allocate(Parent);
13779 Elts.push_back(Region);
13780 Visit(E);
13781 }
13782
13783 // Forget that the initializers are sequenced.
13784 Region = Parent;
13785 for (unsigned I = 0; I < Elts.size(); ++I)
13786 Tree.merge(Elts[I]);
13787 }
13788 };
13789
13790 } // namespace
13791
CheckUnsequencedOperations(const Expr * E)13792 void Sema::CheckUnsequencedOperations(const Expr *E) {
13793 SmallVector<const Expr *, 8> WorkList;
13794 WorkList.push_back(E);
13795 while (!WorkList.empty()) {
13796 const Expr *Item = WorkList.pop_back_val();
13797 SequenceChecker(*this, Item, WorkList);
13798 }
13799 }
13800
CheckCompletedExpr(Expr * E,SourceLocation CheckLoc,bool IsConstexpr)13801 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
13802 bool IsConstexpr) {
13803 llvm::SaveAndRestore<bool> ConstantContext(
13804 isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
13805 CheckImplicitConversions(E, CheckLoc);
13806 if (!E->isInstantiationDependent())
13807 CheckUnsequencedOperations(E);
13808 if (!IsConstexpr && !E->isValueDependent())
13809 CheckForIntOverflow(E);
13810 DiagnoseMisalignedMembers();
13811 }
13812
CheckBitFieldInitialization(SourceLocation InitLoc,FieldDecl * BitField,Expr * Init)13813 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
13814 FieldDecl *BitField,
13815 Expr *Init) {
13816 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
13817 }
13818
diagnoseArrayStarInParamType(Sema & S,QualType PType,SourceLocation Loc)13819 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
13820 SourceLocation Loc) {
13821 if (!PType->isVariablyModifiedType())
13822 return;
13823 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
13824 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
13825 return;
13826 }
13827 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
13828 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
13829 return;
13830 }
13831 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
13832 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
13833 return;
13834 }
13835
13836 const ArrayType *AT = S.Context.getAsArrayType(PType);
13837 if (!AT)
13838 return;
13839
13840 if (AT->getSizeModifier() != ArrayType::Star) {
13841 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
13842 return;
13843 }
13844
13845 S.Diag(Loc, diag::err_array_star_in_function_definition);
13846 }
13847
13848 /// CheckParmsForFunctionDef - Check that the parameters of the given
13849 /// function are appropriate for the definition of a function. This
13850 /// takes care of any checks that cannot be performed on the
13851 /// declaration itself, e.g., that the types of each of the function
13852 /// parameters are complete.
CheckParmsForFunctionDef(ArrayRef<ParmVarDecl * > Parameters,bool CheckParameterNames)13853 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
13854 bool CheckParameterNames) {
13855 bool HasInvalidParm = false;
13856 for (ParmVarDecl *Param : Parameters) {
13857 // C99 6.7.5.3p4: the parameters in a parameter type list in a
13858 // function declarator that is part of a function definition of
13859 // that function shall not have incomplete type.
13860 //
13861 // This is also C++ [dcl.fct]p6.
13862 if (!Param->isInvalidDecl() &&
13863 RequireCompleteType(Param->getLocation(), Param->getType(),
13864 diag::err_typecheck_decl_incomplete_type)) {
13865 Param->setInvalidDecl();
13866 HasInvalidParm = true;
13867 }
13868
13869 // C99 6.9.1p5: If the declarator includes a parameter type list, the
13870 // declaration of each parameter shall include an identifier.
13871 if (CheckParameterNames && Param->getIdentifier() == nullptr &&
13872 !Param->isImplicit() && !getLangOpts().CPlusPlus) {
13873 // Diagnose this as an extension in C17 and earlier.
13874 if (!getLangOpts().C2x)
13875 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
13876 }
13877
13878 // C99 6.7.5.3p12:
13879 // If the function declarator is not part of a definition of that
13880 // function, parameters may have incomplete type and may use the [*]
13881 // notation in their sequences of declarator specifiers to specify
13882 // variable length array types.
13883 QualType PType = Param->getOriginalType();
13884 // FIXME: This diagnostic should point the '[*]' if source-location
13885 // information is added for it.
13886 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
13887
13888 // If the parameter is a c++ class type and it has to be destructed in the
13889 // callee function, declare the destructor so that it can be called by the
13890 // callee function. Do not perform any direct access check on the dtor here.
13891 if (!Param->isInvalidDecl()) {
13892 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
13893 if (!ClassDecl->isInvalidDecl() &&
13894 !ClassDecl->hasIrrelevantDestructor() &&
13895 !ClassDecl->isDependentContext() &&
13896 ClassDecl->isParamDestroyedInCallee()) {
13897 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
13898 MarkFunctionReferenced(Param->getLocation(), Destructor);
13899 DiagnoseUseOfDecl(Destructor, Param->getLocation());
13900 }
13901 }
13902 }
13903
13904 // Parameters with the pass_object_size attribute only need to be marked
13905 // constant at function definitions. Because we lack information about
13906 // whether we're on a declaration or definition when we're instantiating the
13907 // attribute, we need to check for constness here.
13908 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
13909 if (!Param->getType().isConstQualified())
13910 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
13911 << Attr->getSpelling() << 1;
13912
13913 // Check for parameter names shadowing fields from the class.
13914 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
13915 // The owning context for the parameter should be the function, but we
13916 // want to see if this function's declaration context is a record.
13917 DeclContext *DC = Param->getDeclContext();
13918 if (DC && DC->isFunctionOrMethod()) {
13919 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
13920 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
13921 RD, /*DeclIsField*/ false);
13922 }
13923 }
13924 }
13925
13926 return HasInvalidParm;
13927 }
13928
13929 Optional<std::pair<CharUnits, CharUnits>>
13930 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx);
13931
13932 /// Compute the alignment and offset of the base class object given the
13933 /// derived-to-base cast expression and the alignment and offset of the derived
13934 /// class object.
13935 static std::pair<CharUnits, CharUnits>
getDerivedToBaseAlignmentAndOffset(const CastExpr * CE,QualType DerivedType,CharUnits BaseAlignment,CharUnits Offset,ASTContext & Ctx)13936 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType,
13937 CharUnits BaseAlignment, CharUnits Offset,
13938 ASTContext &Ctx) {
13939 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
13940 ++PathI) {
13941 const CXXBaseSpecifier *Base = *PathI;
13942 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
13943 if (Base->isVirtual()) {
13944 // The complete object may have a lower alignment than the non-virtual
13945 // alignment of the base, in which case the base may be misaligned. Choose
13946 // the smaller of the non-virtual alignment and BaseAlignment, which is a
13947 // conservative lower bound of the complete object alignment.
13948 CharUnits NonVirtualAlignment =
13949 Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment();
13950 BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
13951 Offset = CharUnits::Zero();
13952 } else {
13953 const ASTRecordLayout &RL =
13954 Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
13955 Offset += RL.getBaseClassOffset(BaseDecl);
13956 }
13957 DerivedType = Base->getType();
13958 }
13959
13960 return std::make_pair(BaseAlignment, Offset);
13961 }
13962
13963 /// Compute the alignment and offset of a binary additive operator.
13964 static Optional<std::pair<CharUnits, CharUnits>>
getAlignmentAndOffsetFromBinAddOrSub(const Expr * PtrE,const Expr * IntE,bool IsSub,ASTContext & Ctx)13965 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE,
13966 bool IsSub, ASTContext &Ctx) {
13967 QualType PointeeType = PtrE->getType()->getPointeeType();
13968
13969 if (!PointeeType->isConstantSizeType())
13970 return llvm::None;
13971
13972 auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
13973
13974 if (!P)
13975 return llvm::None;
13976
13977 CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
13978 if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
13979 CharUnits Offset = EltSize * IdxRes->getExtValue();
13980 if (IsSub)
13981 Offset = -Offset;
13982 return std::make_pair(P->first, P->second + Offset);
13983 }
13984
13985 // If the integer expression isn't a constant expression, compute the lower
13986 // bound of the alignment using the alignment and offset of the pointer
13987 // expression and the element size.
13988 return std::make_pair(
13989 P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
13990 CharUnits::Zero());
13991 }
13992
13993 /// This helper function takes an lvalue expression and returns the alignment of
13994 /// a VarDecl and a constant offset from the VarDecl.
13995 Optional<std::pair<CharUnits, CharUnits>>
getBaseAlignmentAndOffsetFromLValue(const Expr * E,ASTContext & Ctx)13996 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) {
13997 E = E->IgnoreParens();
13998 switch (E->getStmtClass()) {
13999 default:
14000 break;
14001 case Stmt::CStyleCastExprClass:
14002 case Stmt::CXXStaticCastExprClass:
14003 case Stmt::ImplicitCastExprClass: {
14004 auto *CE = cast<CastExpr>(E);
14005 const Expr *From = CE->getSubExpr();
14006 switch (CE->getCastKind()) {
14007 default:
14008 break;
14009 case CK_NoOp:
14010 return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14011 case CK_UncheckedDerivedToBase:
14012 case CK_DerivedToBase: {
14013 auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14014 if (!P)
14015 break;
14016 return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
14017 P->second, Ctx);
14018 }
14019 }
14020 break;
14021 }
14022 case Stmt::ArraySubscriptExprClass: {
14023 auto *ASE = cast<ArraySubscriptExpr>(E);
14024 return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(),
14025 false, Ctx);
14026 }
14027 case Stmt::DeclRefExprClass: {
14028 if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
14029 // FIXME: If VD is captured by copy or is an escaping __block variable,
14030 // use the alignment of VD's type.
14031 if (!VD->getType()->isReferenceType())
14032 return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
14033 if (VD->hasInit())
14034 return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
14035 }
14036 break;
14037 }
14038 case Stmt::MemberExprClass: {
14039 auto *ME = cast<MemberExpr>(E);
14040 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
14041 if (!FD || FD->getType()->isReferenceType())
14042 break;
14043 Optional<std::pair<CharUnits, CharUnits>> P;
14044 if (ME->isArrow())
14045 P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
14046 else
14047 P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
14048 if (!P)
14049 break;
14050 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
14051 uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
14052 return std::make_pair(P->first,
14053 P->second + CharUnits::fromQuantity(Offset));
14054 }
14055 case Stmt::UnaryOperatorClass: {
14056 auto *UO = cast<UnaryOperator>(E);
14057 switch (UO->getOpcode()) {
14058 default:
14059 break;
14060 case UO_Deref:
14061 return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx);
14062 }
14063 break;
14064 }
14065 case Stmt::BinaryOperatorClass: {
14066 auto *BO = cast<BinaryOperator>(E);
14067 auto Opcode = BO->getOpcode();
14068 switch (Opcode) {
14069 default:
14070 break;
14071 case BO_Comma:
14072 return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx);
14073 }
14074 break;
14075 }
14076 }
14077 return llvm::None;
14078 }
14079
14080 /// This helper function takes a pointer expression and returns the alignment of
14081 /// a VarDecl and a constant offset from the VarDecl.
14082 Optional<std::pair<CharUnits, CharUnits>>
getBaseAlignmentAndOffsetFromPtr(const Expr * E,ASTContext & Ctx)14083 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) {
14084 E = E->IgnoreParens();
14085 switch (E->getStmtClass()) {
14086 default:
14087 break;
14088 case Stmt::CStyleCastExprClass:
14089 case Stmt::CXXStaticCastExprClass:
14090 case Stmt::ImplicitCastExprClass: {
14091 auto *CE = cast<CastExpr>(E);
14092 const Expr *From = CE->getSubExpr();
14093 switch (CE->getCastKind()) {
14094 default:
14095 break;
14096 case CK_NoOp:
14097 return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14098 case CK_ArrayToPointerDecay:
14099 return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14100 case CK_UncheckedDerivedToBase:
14101 case CK_DerivedToBase: {
14102 auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14103 if (!P)
14104 break;
14105 return getDerivedToBaseAlignmentAndOffset(
14106 CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
14107 }
14108 }
14109 break;
14110 }
14111 case Stmt::CXXThisExprClass: {
14112 auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
14113 CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment();
14114 return std::make_pair(Alignment, CharUnits::Zero());
14115 }
14116 case Stmt::UnaryOperatorClass: {
14117 auto *UO = cast<UnaryOperator>(E);
14118 if (UO->getOpcode() == UO_AddrOf)
14119 return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx);
14120 break;
14121 }
14122 case Stmt::BinaryOperatorClass: {
14123 auto *BO = cast<BinaryOperator>(E);
14124 auto Opcode = BO->getOpcode();
14125 switch (Opcode) {
14126 default:
14127 break;
14128 case BO_Add:
14129 case BO_Sub: {
14130 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
14131 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
14132 std::swap(LHS, RHS);
14133 return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
14134 Ctx);
14135 }
14136 case BO_Comma:
14137 return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
14138 }
14139 break;
14140 }
14141 }
14142 return llvm::None;
14143 }
14144
getPresumedAlignmentOfPointer(const Expr * E,Sema & S)14145 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) {
14146 // See if we can compute the alignment of a VarDecl and an offset from it.
14147 Optional<std::pair<CharUnits, CharUnits>> P =
14148 getBaseAlignmentAndOffsetFromPtr(E, S.Context);
14149
14150 if (P)
14151 return P->first.alignmentAtOffset(P->second);
14152
14153 // If that failed, return the type's alignment.
14154 return S.Context.getTypeAlignInChars(E->getType()->getPointeeType());
14155 }
14156
14157 /// CheckCastAlign - Implements -Wcast-align, which warns when a
14158 /// pointer cast increases the alignment requirements.
CheckCastAlign(Expr * Op,QualType T,SourceRange TRange)14159 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
14160 // This is actually a lot of work to potentially be doing on every
14161 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
14162 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
14163 return;
14164
14165 // Ignore dependent types.
14166 if (T->isDependentType() || Op->getType()->isDependentType())
14167 return;
14168
14169 // Require that the destination be a pointer type.
14170 const PointerType *DestPtr = T->getAs<PointerType>();
14171 if (!DestPtr) return;
14172
14173 // If the destination has alignment 1, we're done.
14174 QualType DestPointee = DestPtr->getPointeeType();
14175 if (DestPointee->isIncompleteType()) return;
14176 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
14177 if (DestAlign.isOne()) return;
14178
14179 // Require that the source be a pointer type.
14180 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
14181 if (!SrcPtr) return;
14182 QualType SrcPointee = SrcPtr->getPointeeType();
14183
14184 // Explicitly allow casts from cv void*. We already implicitly
14185 // allowed casts to cv void*, since they have alignment 1.
14186 // Also allow casts involving incomplete types, which implicitly
14187 // includes 'void'.
14188 if (SrcPointee->isIncompleteType()) return;
14189
14190 CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
14191
14192 if (SrcAlign >= DestAlign) return;
14193
14194 Diag(TRange.getBegin(), diag::warn_cast_align)
14195 << Op->getType() << T
14196 << static_cast<unsigned>(SrcAlign.getQuantity())
14197 << static_cast<unsigned>(DestAlign.getQuantity())
14198 << TRange << Op->getSourceRange();
14199 }
14200
14201 /// Check whether this array fits the idiom of a size-one tail padded
14202 /// array member of a struct.
14203 ///
14204 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
14205 /// commonly used to emulate flexible arrays in C89 code.
IsTailPaddedMemberArray(Sema & S,const llvm::APInt & Size,const NamedDecl * ND)14206 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
14207 const NamedDecl *ND) {
14208 if (Size != 1 || !ND) return false;
14209
14210 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
14211 if (!FD) return false;
14212
14213 // Don't consider sizes resulting from macro expansions or template argument
14214 // substitution to form C89 tail-padded arrays.
14215
14216 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
14217 while (TInfo) {
14218 TypeLoc TL = TInfo->getTypeLoc();
14219 // Look through typedefs.
14220 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
14221 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
14222 TInfo = TDL->getTypeSourceInfo();
14223 continue;
14224 }
14225 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
14226 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
14227 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
14228 return false;
14229 }
14230 break;
14231 }
14232
14233 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
14234 if (!RD) return false;
14235 if (RD->isUnion()) return false;
14236 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
14237 if (!CRD->isStandardLayout()) return false;
14238 }
14239
14240 // See if this is the last field decl in the record.
14241 const Decl *D = FD;
14242 while ((D = D->getNextDeclInContext()))
14243 if (isa<FieldDecl>(D))
14244 return false;
14245 return true;
14246 }
14247
CheckArrayAccess(const Expr * BaseExpr,const Expr * IndexExpr,const ArraySubscriptExpr * ASE,bool AllowOnePastEnd,bool IndexNegated)14248 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
14249 const ArraySubscriptExpr *ASE,
14250 bool AllowOnePastEnd, bool IndexNegated) {
14251 // Already diagnosed by the constant evaluator.
14252 if (isConstantEvaluated())
14253 return;
14254
14255 IndexExpr = IndexExpr->IgnoreParenImpCasts();
14256 if (IndexExpr->isValueDependent())
14257 return;
14258
14259 const Type *EffectiveType =
14260 BaseExpr->getType()->getPointeeOrArrayElementType();
14261 BaseExpr = BaseExpr->IgnoreParenCasts();
14262 const ConstantArrayType *ArrayTy =
14263 Context.getAsConstantArrayType(BaseExpr->getType());
14264
14265 if (!ArrayTy)
14266 return;
14267
14268 const Type *BaseType = ArrayTy->getElementType().getTypePtr();
14269 if (EffectiveType->isDependentType() || BaseType->isDependentType())
14270 return;
14271
14272 Expr::EvalResult Result;
14273 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
14274 return;
14275
14276 llvm::APSInt index = Result.Val.getInt();
14277 if (IndexNegated)
14278 index = -index;
14279
14280 const NamedDecl *ND = nullptr;
14281 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
14282 ND = DRE->getDecl();
14283 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
14284 ND = ME->getMemberDecl();
14285
14286 if (index.isUnsigned() || !index.isNegative()) {
14287 // It is possible that the type of the base expression after
14288 // IgnoreParenCasts is incomplete, even though the type of the base
14289 // expression before IgnoreParenCasts is complete (see PR39746 for an
14290 // example). In this case we have no information about whether the array
14291 // access exceeds the array bounds. However we can still diagnose an array
14292 // access which precedes the array bounds.
14293 if (BaseType->isIncompleteType())
14294 return;
14295
14296 llvm::APInt size = ArrayTy->getSize();
14297 if (!size.isStrictlyPositive())
14298 return;
14299
14300 if (BaseType != EffectiveType) {
14301 // Make sure we're comparing apples to apples when comparing index to size
14302 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
14303 uint64_t array_typesize = Context.getTypeSize(BaseType);
14304 // Handle ptrarith_typesize being zero, such as when casting to void*
14305 if (!ptrarith_typesize) ptrarith_typesize = 1;
14306 if (ptrarith_typesize != array_typesize) {
14307 // There's a cast to a different size type involved
14308 uint64_t ratio = array_typesize / ptrarith_typesize;
14309 // TODO: Be smarter about handling cases where array_typesize is not a
14310 // multiple of ptrarith_typesize
14311 if (ptrarith_typesize * ratio == array_typesize)
14312 size *= llvm::APInt(size.getBitWidth(), ratio);
14313 }
14314 }
14315
14316 if (size.getBitWidth() > index.getBitWidth())
14317 index = index.zext(size.getBitWidth());
14318 else if (size.getBitWidth() < index.getBitWidth())
14319 size = size.zext(index.getBitWidth());
14320
14321 // For array subscripting the index must be less than size, but for pointer
14322 // arithmetic also allow the index (offset) to be equal to size since
14323 // computing the next address after the end of the array is legal and
14324 // commonly done e.g. in C++ iterators and range-based for loops.
14325 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
14326 return;
14327
14328 // Also don't warn for arrays of size 1 which are members of some
14329 // structure. These are often used to approximate flexible arrays in C89
14330 // code.
14331 if (IsTailPaddedMemberArray(*this, size, ND))
14332 return;
14333
14334 // Suppress the warning if the subscript expression (as identified by the
14335 // ']' location) and the index expression are both from macro expansions
14336 // within a system header.
14337 if (ASE) {
14338 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
14339 ASE->getRBracketLoc());
14340 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
14341 SourceLocation IndexLoc =
14342 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
14343 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
14344 return;
14345 }
14346 }
14347
14348 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
14349 if (ASE)
14350 DiagID = diag::warn_array_index_exceeds_bounds;
14351
14352 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
14353 PDiag(DiagID) << index.toString(10, true)
14354 << size.toString(10, true)
14355 << (unsigned)size.getLimitedValue(~0U)
14356 << IndexExpr->getSourceRange());
14357 } else {
14358 unsigned DiagID = diag::warn_array_index_precedes_bounds;
14359 if (!ASE) {
14360 DiagID = diag::warn_ptr_arith_precedes_bounds;
14361 if (index.isNegative()) index = -index;
14362 }
14363
14364 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
14365 PDiag(DiagID) << index.toString(10, true)
14366 << IndexExpr->getSourceRange());
14367 }
14368
14369 if (!ND) {
14370 // Try harder to find a NamedDecl to point at in the note.
14371 while (const ArraySubscriptExpr *ASE =
14372 dyn_cast<ArraySubscriptExpr>(BaseExpr))
14373 BaseExpr = ASE->getBase()->IgnoreParenCasts();
14374 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
14375 ND = DRE->getDecl();
14376 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
14377 ND = ME->getMemberDecl();
14378 }
14379
14380 if (ND)
14381 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
14382 PDiag(diag::note_array_declared_here) << ND);
14383 }
14384
CheckArrayAccess(const Expr * expr)14385 void Sema::CheckArrayAccess(const Expr *expr) {
14386 int AllowOnePastEnd = 0;
14387 while (expr) {
14388 expr = expr->IgnoreParenImpCasts();
14389 switch (expr->getStmtClass()) {
14390 case Stmt::ArraySubscriptExprClass: {
14391 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
14392 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
14393 AllowOnePastEnd > 0);
14394 expr = ASE->getBase();
14395 break;
14396 }
14397 case Stmt::MemberExprClass: {
14398 expr = cast<MemberExpr>(expr)->getBase();
14399 break;
14400 }
14401 case Stmt::OMPArraySectionExprClass: {
14402 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
14403 if (ASE->getLowerBound())
14404 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
14405 /*ASE=*/nullptr, AllowOnePastEnd > 0);
14406 return;
14407 }
14408 case Stmt::UnaryOperatorClass: {
14409 // Only unwrap the * and & unary operators
14410 const UnaryOperator *UO = cast<UnaryOperator>(expr);
14411 expr = UO->getSubExpr();
14412 switch (UO->getOpcode()) {
14413 case UO_AddrOf:
14414 AllowOnePastEnd++;
14415 break;
14416 case UO_Deref:
14417 AllowOnePastEnd--;
14418 break;
14419 default:
14420 return;
14421 }
14422 break;
14423 }
14424 case Stmt::ConditionalOperatorClass: {
14425 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
14426 if (const Expr *lhs = cond->getLHS())
14427 CheckArrayAccess(lhs);
14428 if (const Expr *rhs = cond->getRHS())
14429 CheckArrayAccess(rhs);
14430 return;
14431 }
14432 case Stmt::CXXOperatorCallExprClass: {
14433 const auto *OCE = cast<CXXOperatorCallExpr>(expr);
14434 for (const auto *Arg : OCE->arguments())
14435 CheckArrayAccess(Arg);
14436 return;
14437 }
14438 default:
14439 return;
14440 }
14441 }
14442 }
14443
14444 //===--- CHECK: Objective-C retain cycles ----------------------------------//
14445
14446 namespace {
14447
14448 struct RetainCycleOwner {
14449 VarDecl *Variable = nullptr;
14450 SourceRange Range;
14451 SourceLocation Loc;
14452 bool Indirect = false;
14453
14454 RetainCycleOwner() = default;
14455
setLocsFrom__anon33aba9e82211::RetainCycleOwner14456 void setLocsFrom(Expr *e) {
14457 Loc = e->getExprLoc();
14458 Range = e->getSourceRange();
14459 }
14460 };
14461
14462 } // namespace
14463
14464 /// Consider whether capturing the given variable can possibly lead to
14465 /// a retain cycle.
considerVariable(VarDecl * var,Expr * ref,RetainCycleOwner & owner)14466 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
14467 // In ARC, it's captured strongly iff the variable has __strong
14468 // lifetime. In MRR, it's captured strongly if the variable is
14469 // __block and has an appropriate type.
14470 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
14471 return false;
14472
14473 owner.Variable = var;
14474 if (ref)
14475 owner.setLocsFrom(ref);
14476 return true;
14477 }
14478
findRetainCycleOwner(Sema & S,Expr * e,RetainCycleOwner & owner)14479 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
14480 while (true) {
14481 e = e->IgnoreParens();
14482 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
14483 switch (cast->getCastKind()) {
14484 case CK_BitCast:
14485 case CK_LValueBitCast:
14486 case CK_LValueToRValue:
14487 case CK_ARCReclaimReturnedObject:
14488 e = cast->getSubExpr();
14489 continue;
14490
14491 default:
14492 return false;
14493 }
14494 }
14495
14496 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
14497 ObjCIvarDecl *ivar = ref->getDecl();
14498 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
14499 return false;
14500
14501 // Try to find a retain cycle in the base.
14502 if (!findRetainCycleOwner(S, ref->getBase(), owner))
14503 return false;
14504
14505 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
14506 owner.Indirect = true;
14507 return true;
14508 }
14509
14510 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
14511 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
14512 if (!var) return false;
14513 return considerVariable(var, ref, owner);
14514 }
14515
14516 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
14517 if (member->isArrow()) return false;
14518
14519 // Don't count this as an indirect ownership.
14520 e = member->getBase();
14521 continue;
14522 }
14523
14524 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
14525 // Only pay attention to pseudo-objects on property references.
14526 ObjCPropertyRefExpr *pre
14527 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
14528 ->IgnoreParens());
14529 if (!pre) return false;
14530 if (pre->isImplicitProperty()) return false;
14531 ObjCPropertyDecl *property = pre->getExplicitProperty();
14532 if (!property->isRetaining() &&
14533 !(property->getPropertyIvarDecl() &&
14534 property->getPropertyIvarDecl()->getType()
14535 .getObjCLifetime() == Qualifiers::OCL_Strong))
14536 return false;
14537
14538 owner.Indirect = true;
14539 if (pre->isSuperReceiver()) {
14540 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
14541 if (!owner.Variable)
14542 return false;
14543 owner.Loc = pre->getLocation();
14544 owner.Range = pre->getSourceRange();
14545 return true;
14546 }
14547 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
14548 ->getSourceExpr());
14549 continue;
14550 }
14551
14552 // Array ivars?
14553
14554 return false;
14555 }
14556 }
14557
14558 namespace {
14559
14560 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
14561 ASTContext &Context;
14562 VarDecl *Variable;
14563 Expr *Capturer = nullptr;
14564 bool VarWillBeReased = false;
14565
FindCaptureVisitor__anon33aba9e82311::FindCaptureVisitor14566 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
14567 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
14568 Context(Context), Variable(variable) {}
14569
VisitDeclRefExpr__anon33aba9e82311::FindCaptureVisitor14570 void VisitDeclRefExpr(DeclRefExpr *ref) {
14571 if (ref->getDecl() == Variable && !Capturer)
14572 Capturer = ref;
14573 }
14574
VisitObjCIvarRefExpr__anon33aba9e82311::FindCaptureVisitor14575 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
14576 if (Capturer) return;
14577 Visit(ref->getBase());
14578 if (Capturer && ref->isFreeIvar())
14579 Capturer = ref;
14580 }
14581
VisitBlockExpr__anon33aba9e82311::FindCaptureVisitor14582 void VisitBlockExpr(BlockExpr *block) {
14583 // Look inside nested blocks
14584 if (block->getBlockDecl()->capturesVariable(Variable))
14585 Visit(block->getBlockDecl()->getBody());
14586 }
14587
VisitOpaqueValueExpr__anon33aba9e82311::FindCaptureVisitor14588 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
14589 if (Capturer) return;
14590 if (OVE->getSourceExpr())
14591 Visit(OVE->getSourceExpr());
14592 }
14593
VisitBinaryOperator__anon33aba9e82311::FindCaptureVisitor14594 void VisitBinaryOperator(BinaryOperator *BinOp) {
14595 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
14596 return;
14597 Expr *LHS = BinOp->getLHS();
14598 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
14599 if (DRE->getDecl() != Variable)
14600 return;
14601 if (Expr *RHS = BinOp->getRHS()) {
14602 RHS = RHS->IgnoreParenCasts();
14603 Optional<llvm::APSInt> Value;
14604 VarWillBeReased =
14605 (RHS && (Value = RHS->getIntegerConstantExpr(Context)) &&
14606 *Value == 0);
14607 }
14608 }
14609 }
14610 };
14611
14612 } // namespace
14613
14614 /// Check whether the given argument is a block which captures a
14615 /// variable.
findCapturingExpr(Sema & S,Expr * e,RetainCycleOwner & owner)14616 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
14617 assert(owner.Variable && owner.Loc.isValid());
14618
14619 e = e->IgnoreParenCasts();
14620
14621 // Look through [^{...} copy] and Block_copy(^{...}).
14622 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
14623 Selector Cmd = ME->getSelector();
14624 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
14625 e = ME->getInstanceReceiver();
14626 if (!e)
14627 return nullptr;
14628 e = e->IgnoreParenCasts();
14629 }
14630 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
14631 if (CE->getNumArgs() == 1) {
14632 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
14633 if (Fn) {
14634 const IdentifierInfo *FnI = Fn->getIdentifier();
14635 if (FnI && FnI->isStr("_Block_copy")) {
14636 e = CE->getArg(0)->IgnoreParenCasts();
14637 }
14638 }
14639 }
14640 }
14641
14642 BlockExpr *block = dyn_cast<BlockExpr>(e);
14643 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
14644 return nullptr;
14645
14646 FindCaptureVisitor visitor(S.Context, owner.Variable);
14647 visitor.Visit(block->getBlockDecl()->getBody());
14648 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
14649 }
14650
diagnoseRetainCycle(Sema & S,Expr * capturer,RetainCycleOwner & owner)14651 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
14652 RetainCycleOwner &owner) {
14653 assert(capturer);
14654 assert(owner.Variable && owner.Loc.isValid());
14655
14656 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
14657 << owner.Variable << capturer->getSourceRange();
14658 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
14659 << owner.Indirect << owner.Range;
14660 }
14661
14662 /// Check for a keyword selector that starts with the word 'add' or
14663 /// 'set'.
isSetterLikeSelector(Selector sel)14664 static bool isSetterLikeSelector(Selector sel) {
14665 if (sel.isUnarySelector()) return false;
14666
14667 StringRef str = sel.getNameForSlot(0);
14668 while (!str.empty() && str.front() == '_') str = str.substr(1);
14669 if (str.startswith("set"))
14670 str = str.substr(3);
14671 else if (str.startswith("add")) {
14672 // Specially allow 'addOperationWithBlock:'.
14673 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
14674 return false;
14675 str = str.substr(3);
14676 }
14677 else
14678 return false;
14679
14680 if (str.empty()) return true;
14681 return !isLowercase(str.front());
14682 }
14683
GetNSMutableArrayArgumentIndex(Sema & S,ObjCMessageExpr * Message)14684 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
14685 ObjCMessageExpr *Message) {
14686 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
14687 Message->getReceiverInterface(),
14688 NSAPI::ClassId_NSMutableArray);
14689 if (!IsMutableArray) {
14690 return None;
14691 }
14692
14693 Selector Sel = Message->getSelector();
14694
14695 Optional<NSAPI::NSArrayMethodKind> MKOpt =
14696 S.NSAPIObj->getNSArrayMethodKind(Sel);
14697 if (!MKOpt) {
14698 return None;
14699 }
14700
14701 NSAPI::NSArrayMethodKind MK = *MKOpt;
14702
14703 switch (MK) {
14704 case NSAPI::NSMutableArr_addObject:
14705 case NSAPI::NSMutableArr_insertObjectAtIndex:
14706 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
14707 return 0;
14708 case NSAPI::NSMutableArr_replaceObjectAtIndex:
14709 return 1;
14710
14711 default:
14712 return None;
14713 }
14714
14715 return None;
14716 }
14717
14718 static
GetNSMutableDictionaryArgumentIndex(Sema & S,ObjCMessageExpr * Message)14719 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
14720 ObjCMessageExpr *Message) {
14721 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
14722 Message->getReceiverInterface(),
14723 NSAPI::ClassId_NSMutableDictionary);
14724 if (!IsMutableDictionary) {
14725 return None;
14726 }
14727
14728 Selector Sel = Message->getSelector();
14729
14730 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
14731 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
14732 if (!MKOpt) {
14733 return None;
14734 }
14735
14736 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
14737
14738 switch (MK) {
14739 case NSAPI::NSMutableDict_setObjectForKey:
14740 case NSAPI::NSMutableDict_setValueForKey:
14741 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
14742 return 0;
14743
14744 default:
14745 return None;
14746 }
14747
14748 return None;
14749 }
14750
GetNSSetArgumentIndex(Sema & S,ObjCMessageExpr * Message)14751 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
14752 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
14753 Message->getReceiverInterface(),
14754 NSAPI::ClassId_NSMutableSet);
14755
14756 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
14757 Message->getReceiverInterface(),
14758 NSAPI::ClassId_NSMutableOrderedSet);
14759 if (!IsMutableSet && !IsMutableOrderedSet) {
14760 return None;
14761 }
14762
14763 Selector Sel = Message->getSelector();
14764
14765 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
14766 if (!MKOpt) {
14767 return None;
14768 }
14769
14770 NSAPI::NSSetMethodKind MK = *MKOpt;
14771
14772 switch (MK) {
14773 case NSAPI::NSMutableSet_addObject:
14774 case NSAPI::NSOrderedSet_setObjectAtIndex:
14775 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
14776 case NSAPI::NSOrderedSet_insertObjectAtIndex:
14777 return 0;
14778 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
14779 return 1;
14780 }
14781
14782 return None;
14783 }
14784
CheckObjCCircularContainer(ObjCMessageExpr * Message)14785 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
14786 if (!Message->isInstanceMessage()) {
14787 return;
14788 }
14789
14790 Optional<int> ArgOpt;
14791
14792 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
14793 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
14794 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
14795 return;
14796 }
14797
14798 int ArgIndex = *ArgOpt;
14799
14800 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
14801 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
14802 Arg = OE->getSourceExpr()->IgnoreImpCasts();
14803 }
14804
14805 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
14806 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
14807 if (ArgRE->isObjCSelfExpr()) {
14808 Diag(Message->getSourceRange().getBegin(),
14809 diag::warn_objc_circular_container)
14810 << ArgRE->getDecl() << StringRef("'super'");
14811 }
14812 }
14813 } else {
14814 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
14815
14816 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
14817 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
14818 }
14819
14820 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
14821 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
14822 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
14823 ValueDecl *Decl = ReceiverRE->getDecl();
14824 Diag(Message->getSourceRange().getBegin(),
14825 diag::warn_objc_circular_container)
14826 << Decl << Decl;
14827 if (!ArgRE->isObjCSelfExpr()) {
14828 Diag(Decl->getLocation(),
14829 diag::note_objc_circular_container_declared_here)
14830 << Decl;
14831 }
14832 }
14833 }
14834 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
14835 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
14836 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
14837 ObjCIvarDecl *Decl = IvarRE->getDecl();
14838 Diag(Message->getSourceRange().getBegin(),
14839 diag::warn_objc_circular_container)
14840 << Decl << Decl;
14841 Diag(Decl->getLocation(),
14842 diag::note_objc_circular_container_declared_here)
14843 << Decl;
14844 }
14845 }
14846 }
14847 }
14848 }
14849
14850 /// Check a message send to see if it's likely to cause a retain cycle.
checkRetainCycles(ObjCMessageExpr * msg)14851 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
14852 // Only check instance methods whose selector looks like a setter.
14853 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
14854 return;
14855
14856 // Try to find a variable that the receiver is strongly owned by.
14857 RetainCycleOwner owner;
14858 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
14859 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
14860 return;
14861 } else {
14862 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
14863 owner.Variable = getCurMethodDecl()->getSelfDecl();
14864 owner.Loc = msg->getSuperLoc();
14865 owner.Range = msg->getSuperLoc();
14866 }
14867
14868 // Check whether the receiver is captured by any of the arguments.
14869 const ObjCMethodDecl *MD = msg->getMethodDecl();
14870 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
14871 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
14872 // noescape blocks should not be retained by the method.
14873 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
14874 continue;
14875 return diagnoseRetainCycle(*this, capturer, owner);
14876 }
14877 }
14878 }
14879
14880 /// Check a property assign to see if it's likely to cause a retain cycle.
checkRetainCycles(Expr * receiver,Expr * argument)14881 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
14882 RetainCycleOwner owner;
14883 if (!findRetainCycleOwner(*this, receiver, owner))
14884 return;
14885
14886 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
14887 diagnoseRetainCycle(*this, capturer, owner);
14888 }
14889
checkRetainCycles(VarDecl * Var,Expr * Init)14890 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
14891 RetainCycleOwner Owner;
14892 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
14893 return;
14894
14895 // Because we don't have an expression for the variable, we have to set the
14896 // location explicitly here.
14897 Owner.Loc = Var->getLocation();
14898 Owner.Range = Var->getSourceRange();
14899
14900 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
14901 diagnoseRetainCycle(*this, Capturer, Owner);
14902 }
14903
checkUnsafeAssignLiteral(Sema & S,SourceLocation Loc,Expr * RHS,bool isProperty)14904 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
14905 Expr *RHS, bool isProperty) {
14906 // Check if RHS is an Objective-C object literal, which also can get
14907 // immediately zapped in a weak reference. Note that we explicitly
14908 // allow ObjCStringLiterals, since those are designed to never really die.
14909 RHS = RHS->IgnoreParenImpCasts();
14910
14911 // This enum needs to match with the 'select' in
14912 // warn_objc_arc_literal_assign (off-by-1).
14913 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
14914 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
14915 return false;
14916
14917 S.Diag(Loc, diag::warn_arc_literal_assign)
14918 << (unsigned) Kind
14919 << (isProperty ? 0 : 1)
14920 << RHS->getSourceRange();
14921
14922 return true;
14923 }
14924
checkUnsafeAssignObject(Sema & S,SourceLocation Loc,Qualifiers::ObjCLifetime LT,Expr * RHS,bool isProperty)14925 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
14926 Qualifiers::ObjCLifetime LT,
14927 Expr *RHS, bool isProperty) {
14928 // Strip off any implicit cast added to get to the one ARC-specific.
14929 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
14930 if (cast->getCastKind() == CK_ARCConsumeObject) {
14931 S.Diag(Loc, diag::warn_arc_retained_assign)
14932 << (LT == Qualifiers::OCL_ExplicitNone)
14933 << (isProperty ? 0 : 1)
14934 << RHS->getSourceRange();
14935 return true;
14936 }
14937 RHS = cast->getSubExpr();
14938 }
14939
14940 if (LT == Qualifiers::OCL_Weak &&
14941 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
14942 return true;
14943
14944 return false;
14945 }
14946
checkUnsafeAssigns(SourceLocation Loc,QualType LHS,Expr * RHS)14947 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
14948 QualType LHS, Expr *RHS) {
14949 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
14950
14951 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
14952 return false;
14953
14954 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
14955 return true;
14956
14957 return false;
14958 }
14959
checkUnsafeExprAssigns(SourceLocation Loc,Expr * LHS,Expr * RHS)14960 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
14961 Expr *LHS, Expr *RHS) {
14962 QualType LHSType;
14963 // PropertyRef on LHS type need be directly obtained from
14964 // its declaration as it has a PseudoType.
14965 ObjCPropertyRefExpr *PRE
14966 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
14967 if (PRE && !PRE->isImplicitProperty()) {
14968 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
14969 if (PD)
14970 LHSType = PD->getType();
14971 }
14972
14973 if (LHSType.isNull())
14974 LHSType = LHS->getType();
14975
14976 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
14977
14978 if (LT == Qualifiers::OCL_Weak) {
14979 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
14980 getCurFunction()->markSafeWeakUse(LHS);
14981 }
14982
14983 if (checkUnsafeAssigns(Loc, LHSType, RHS))
14984 return;
14985
14986 // FIXME. Check for other life times.
14987 if (LT != Qualifiers::OCL_None)
14988 return;
14989
14990 if (PRE) {
14991 if (PRE->isImplicitProperty())
14992 return;
14993 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
14994 if (!PD)
14995 return;
14996
14997 unsigned Attributes = PD->getPropertyAttributes();
14998 if (Attributes & ObjCPropertyAttribute::kind_assign) {
14999 // when 'assign' attribute was not explicitly specified
15000 // by user, ignore it and rely on property type itself
15001 // for lifetime info.
15002 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
15003 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
15004 LHSType->isObjCRetainableType())
15005 return;
15006
15007 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15008 if (cast->getCastKind() == CK_ARCConsumeObject) {
15009 Diag(Loc, diag::warn_arc_retained_property_assign)
15010 << RHS->getSourceRange();
15011 return;
15012 }
15013 RHS = cast->getSubExpr();
15014 }
15015 } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
15016 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
15017 return;
15018 }
15019 }
15020 }
15021
15022 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
15023
ShouldDiagnoseEmptyStmtBody(const SourceManager & SourceMgr,SourceLocation StmtLoc,const NullStmt * Body)15024 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
15025 SourceLocation StmtLoc,
15026 const NullStmt *Body) {
15027 // Do not warn if the body is a macro that expands to nothing, e.g:
15028 //
15029 // #define CALL(x)
15030 // if (condition)
15031 // CALL(0);
15032 if (Body->hasLeadingEmptyMacro())
15033 return false;
15034
15035 // Get line numbers of statement and body.
15036 bool StmtLineInvalid;
15037 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
15038 &StmtLineInvalid);
15039 if (StmtLineInvalid)
15040 return false;
15041
15042 bool BodyLineInvalid;
15043 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
15044 &BodyLineInvalid);
15045 if (BodyLineInvalid)
15046 return false;
15047
15048 // Warn if null statement and body are on the same line.
15049 if (StmtLine != BodyLine)
15050 return false;
15051
15052 return true;
15053 }
15054
DiagnoseEmptyStmtBody(SourceLocation StmtLoc,const Stmt * Body,unsigned DiagID)15055 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
15056 const Stmt *Body,
15057 unsigned DiagID) {
15058 // Since this is a syntactic check, don't emit diagnostic for template
15059 // instantiations, this just adds noise.
15060 if (CurrentInstantiationScope)
15061 return;
15062
15063 // The body should be a null statement.
15064 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15065 if (!NBody)
15066 return;
15067
15068 // Do the usual checks.
15069 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15070 return;
15071
15072 Diag(NBody->getSemiLoc(), DiagID);
15073 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15074 }
15075
DiagnoseEmptyLoopBody(const Stmt * S,const Stmt * PossibleBody)15076 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
15077 const Stmt *PossibleBody) {
15078 assert(!CurrentInstantiationScope); // Ensured by caller
15079
15080 SourceLocation StmtLoc;
15081 const Stmt *Body;
15082 unsigned DiagID;
15083 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
15084 StmtLoc = FS->getRParenLoc();
15085 Body = FS->getBody();
15086 DiagID = diag::warn_empty_for_body;
15087 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
15088 StmtLoc = WS->getCond()->getSourceRange().getEnd();
15089 Body = WS->getBody();
15090 DiagID = diag::warn_empty_while_body;
15091 } else
15092 return; // Neither `for' nor `while'.
15093
15094 // The body should be a null statement.
15095 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15096 if (!NBody)
15097 return;
15098
15099 // Skip expensive checks if diagnostic is disabled.
15100 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
15101 return;
15102
15103 // Do the usual checks.
15104 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15105 return;
15106
15107 // `for(...);' and `while(...);' are popular idioms, so in order to keep
15108 // noise level low, emit diagnostics only if for/while is followed by a
15109 // CompoundStmt, e.g.:
15110 // for (int i = 0; i < n; i++);
15111 // {
15112 // a(i);
15113 // }
15114 // or if for/while is followed by a statement with more indentation
15115 // than for/while itself:
15116 // for (int i = 0; i < n; i++);
15117 // a(i);
15118 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
15119 if (!ProbableTypo) {
15120 bool BodyColInvalid;
15121 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
15122 PossibleBody->getBeginLoc(), &BodyColInvalid);
15123 if (BodyColInvalid)
15124 return;
15125
15126 bool StmtColInvalid;
15127 unsigned StmtCol =
15128 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
15129 if (StmtColInvalid)
15130 return;
15131
15132 if (BodyCol > StmtCol)
15133 ProbableTypo = true;
15134 }
15135
15136 if (ProbableTypo) {
15137 Diag(NBody->getSemiLoc(), DiagID);
15138 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15139 }
15140 }
15141
15142 //===--- CHECK: Warn on self move with std::move. -------------------------===//
15143
15144 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
DiagnoseSelfMove(const Expr * LHSExpr,const Expr * RHSExpr,SourceLocation OpLoc)15145 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
15146 SourceLocation OpLoc) {
15147 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
15148 return;
15149
15150 if (inTemplateInstantiation())
15151 return;
15152
15153 // Strip parens and casts away.
15154 LHSExpr = LHSExpr->IgnoreParenImpCasts();
15155 RHSExpr = RHSExpr->IgnoreParenImpCasts();
15156
15157 // Check for a call expression
15158 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
15159 if (!CE || CE->getNumArgs() != 1)
15160 return;
15161
15162 // Check for a call to std::move
15163 if (!CE->isCallToStdMove())
15164 return;
15165
15166 // Get argument from std::move
15167 RHSExpr = CE->getArg(0);
15168
15169 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
15170 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
15171
15172 // Two DeclRefExpr's, check that the decls are the same.
15173 if (LHSDeclRef && RHSDeclRef) {
15174 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15175 return;
15176 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15177 RHSDeclRef->getDecl()->getCanonicalDecl())
15178 return;
15179
15180 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15181 << LHSExpr->getSourceRange()
15182 << RHSExpr->getSourceRange();
15183 return;
15184 }
15185
15186 // Member variables require a different approach to check for self moves.
15187 // MemberExpr's are the same if every nested MemberExpr refers to the same
15188 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
15189 // the base Expr's are CXXThisExpr's.
15190 const Expr *LHSBase = LHSExpr;
15191 const Expr *RHSBase = RHSExpr;
15192 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
15193 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
15194 if (!LHSME || !RHSME)
15195 return;
15196
15197 while (LHSME && RHSME) {
15198 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
15199 RHSME->getMemberDecl()->getCanonicalDecl())
15200 return;
15201
15202 LHSBase = LHSME->getBase();
15203 RHSBase = RHSME->getBase();
15204 LHSME = dyn_cast<MemberExpr>(LHSBase);
15205 RHSME = dyn_cast<MemberExpr>(RHSBase);
15206 }
15207
15208 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
15209 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
15210 if (LHSDeclRef && RHSDeclRef) {
15211 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15212 return;
15213 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15214 RHSDeclRef->getDecl()->getCanonicalDecl())
15215 return;
15216
15217 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15218 << LHSExpr->getSourceRange()
15219 << RHSExpr->getSourceRange();
15220 return;
15221 }
15222
15223 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
15224 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15225 << LHSExpr->getSourceRange()
15226 << RHSExpr->getSourceRange();
15227 }
15228
15229 //===--- Layout compatibility ----------------------------------------------//
15230
15231 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
15232
15233 /// Check if two enumeration types are layout-compatible.
isLayoutCompatible(ASTContext & C,EnumDecl * ED1,EnumDecl * ED2)15234 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
15235 // C++11 [dcl.enum] p8:
15236 // Two enumeration types are layout-compatible if they have the same
15237 // underlying type.
15238 return ED1->isComplete() && ED2->isComplete() &&
15239 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
15240 }
15241
15242 /// Check if two fields are layout-compatible.
isLayoutCompatible(ASTContext & C,FieldDecl * Field1,FieldDecl * Field2)15243 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
15244 FieldDecl *Field2) {
15245 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
15246 return false;
15247
15248 if (Field1->isBitField() != Field2->isBitField())
15249 return false;
15250
15251 if (Field1->isBitField()) {
15252 // Make sure that the bit-fields are the same length.
15253 unsigned Bits1 = Field1->getBitWidthValue(C);
15254 unsigned Bits2 = Field2->getBitWidthValue(C);
15255
15256 if (Bits1 != Bits2)
15257 return false;
15258 }
15259
15260 return true;
15261 }
15262
15263 /// Check if two standard-layout structs are layout-compatible.
15264 /// (C++11 [class.mem] p17)
isLayoutCompatibleStruct(ASTContext & C,RecordDecl * RD1,RecordDecl * RD2)15265 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
15266 RecordDecl *RD2) {
15267 // If both records are C++ classes, check that base classes match.
15268 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
15269 // If one of records is a CXXRecordDecl we are in C++ mode,
15270 // thus the other one is a CXXRecordDecl, too.
15271 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
15272 // Check number of base classes.
15273 if (D1CXX->getNumBases() != D2CXX->getNumBases())
15274 return false;
15275
15276 // Check the base classes.
15277 for (CXXRecordDecl::base_class_const_iterator
15278 Base1 = D1CXX->bases_begin(),
15279 BaseEnd1 = D1CXX->bases_end(),
15280 Base2 = D2CXX->bases_begin();
15281 Base1 != BaseEnd1;
15282 ++Base1, ++Base2) {
15283 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
15284 return false;
15285 }
15286 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
15287 // If only RD2 is a C++ class, it should have zero base classes.
15288 if (D2CXX->getNumBases() > 0)
15289 return false;
15290 }
15291
15292 // Check the fields.
15293 RecordDecl::field_iterator Field2 = RD2->field_begin(),
15294 Field2End = RD2->field_end(),
15295 Field1 = RD1->field_begin(),
15296 Field1End = RD1->field_end();
15297 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
15298 if (!isLayoutCompatible(C, *Field1, *Field2))
15299 return false;
15300 }
15301 if (Field1 != Field1End || Field2 != Field2End)
15302 return false;
15303
15304 return true;
15305 }
15306
15307 /// Check if two standard-layout unions are layout-compatible.
15308 /// (C++11 [class.mem] p18)
isLayoutCompatibleUnion(ASTContext & C,RecordDecl * RD1,RecordDecl * RD2)15309 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
15310 RecordDecl *RD2) {
15311 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
15312 for (auto *Field2 : RD2->fields())
15313 UnmatchedFields.insert(Field2);
15314
15315 for (auto *Field1 : RD1->fields()) {
15316 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
15317 I = UnmatchedFields.begin(),
15318 E = UnmatchedFields.end();
15319
15320 for ( ; I != E; ++I) {
15321 if (isLayoutCompatible(C, Field1, *I)) {
15322 bool Result = UnmatchedFields.erase(*I);
15323 (void) Result;
15324 assert(Result);
15325 break;
15326 }
15327 }
15328 if (I == E)
15329 return false;
15330 }
15331
15332 return UnmatchedFields.empty();
15333 }
15334
isLayoutCompatible(ASTContext & C,RecordDecl * RD1,RecordDecl * RD2)15335 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
15336 RecordDecl *RD2) {
15337 if (RD1->isUnion() != RD2->isUnion())
15338 return false;
15339
15340 if (RD1->isUnion())
15341 return isLayoutCompatibleUnion(C, RD1, RD2);
15342 else
15343 return isLayoutCompatibleStruct(C, RD1, RD2);
15344 }
15345
15346 /// Check if two types are layout-compatible in C++11 sense.
isLayoutCompatible(ASTContext & C,QualType T1,QualType T2)15347 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
15348 if (T1.isNull() || T2.isNull())
15349 return false;
15350
15351 // C++11 [basic.types] p11:
15352 // If two types T1 and T2 are the same type, then T1 and T2 are
15353 // layout-compatible types.
15354 if (C.hasSameType(T1, T2))
15355 return true;
15356
15357 T1 = T1.getCanonicalType().getUnqualifiedType();
15358 T2 = T2.getCanonicalType().getUnqualifiedType();
15359
15360 const Type::TypeClass TC1 = T1->getTypeClass();
15361 const Type::TypeClass TC2 = T2->getTypeClass();
15362
15363 if (TC1 != TC2)
15364 return false;
15365
15366 if (TC1 == Type::Enum) {
15367 return isLayoutCompatible(C,
15368 cast<EnumType>(T1)->getDecl(),
15369 cast<EnumType>(T2)->getDecl());
15370 } else if (TC1 == Type::Record) {
15371 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
15372 return false;
15373
15374 return isLayoutCompatible(C,
15375 cast<RecordType>(T1)->getDecl(),
15376 cast<RecordType>(T2)->getDecl());
15377 }
15378
15379 return false;
15380 }
15381
15382 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
15383
15384 /// Given a type tag expression find the type tag itself.
15385 ///
15386 /// \param TypeExpr Type tag expression, as it appears in user's code.
15387 ///
15388 /// \param VD Declaration of an identifier that appears in a type tag.
15389 ///
15390 /// \param MagicValue Type tag magic value.
15391 ///
15392 /// \param isConstantEvaluated wether the evalaution should be performed in
15393
15394 /// constant context.
FindTypeTagExpr(const Expr * TypeExpr,const ASTContext & Ctx,const ValueDecl ** VD,uint64_t * MagicValue,bool isConstantEvaluated)15395 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
15396 const ValueDecl **VD, uint64_t *MagicValue,
15397 bool isConstantEvaluated) {
15398 while(true) {
15399 if (!TypeExpr)
15400 return false;
15401
15402 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
15403
15404 switch (TypeExpr->getStmtClass()) {
15405 case Stmt::UnaryOperatorClass: {
15406 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
15407 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
15408 TypeExpr = UO->getSubExpr();
15409 continue;
15410 }
15411 return false;
15412 }
15413
15414 case Stmt::DeclRefExprClass: {
15415 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
15416 *VD = DRE->getDecl();
15417 return true;
15418 }
15419
15420 case Stmt::IntegerLiteralClass: {
15421 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
15422 llvm::APInt MagicValueAPInt = IL->getValue();
15423 if (MagicValueAPInt.getActiveBits() <= 64) {
15424 *MagicValue = MagicValueAPInt.getZExtValue();
15425 return true;
15426 } else
15427 return false;
15428 }
15429
15430 case Stmt::BinaryConditionalOperatorClass:
15431 case Stmt::ConditionalOperatorClass: {
15432 const AbstractConditionalOperator *ACO =
15433 cast<AbstractConditionalOperator>(TypeExpr);
15434 bool Result;
15435 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
15436 isConstantEvaluated)) {
15437 if (Result)
15438 TypeExpr = ACO->getTrueExpr();
15439 else
15440 TypeExpr = ACO->getFalseExpr();
15441 continue;
15442 }
15443 return false;
15444 }
15445
15446 case Stmt::BinaryOperatorClass: {
15447 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
15448 if (BO->getOpcode() == BO_Comma) {
15449 TypeExpr = BO->getRHS();
15450 continue;
15451 }
15452 return false;
15453 }
15454
15455 default:
15456 return false;
15457 }
15458 }
15459 }
15460
15461 /// Retrieve the C type corresponding to type tag TypeExpr.
15462 ///
15463 /// \param TypeExpr Expression that specifies a type tag.
15464 ///
15465 /// \param MagicValues Registered magic values.
15466 ///
15467 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
15468 /// kind.
15469 ///
15470 /// \param TypeInfo Information about the corresponding C type.
15471 ///
15472 /// \param isConstantEvaluated wether the evalaution should be performed in
15473 /// constant context.
15474 ///
15475 /// \returns true if the corresponding C type was found.
GetMatchingCType(const IdentifierInfo * ArgumentKind,const Expr * TypeExpr,const ASTContext & Ctx,const llvm::DenseMap<Sema::TypeTagMagicValue,Sema::TypeTagData> * MagicValues,bool & FoundWrongKind,Sema::TypeTagData & TypeInfo,bool isConstantEvaluated)15476 static bool GetMatchingCType(
15477 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
15478 const ASTContext &Ctx,
15479 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
15480 *MagicValues,
15481 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
15482 bool isConstantEvaluated) {
15483 FoundWrongKind = false;
15484
15485 // Variable declaration that has type_tag_for_datatype attribute.
15486 const ValueDecl *VD = nullptr;
15487
15488 uint64_t MagicValue;
15489
15490 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
15491 return false;
15492
15493 if (VD) {
15494 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
15495 if (I->getArgumentKind() != ArgumentKind) {
15496 FoundWrongKind = true;
15497 return false;
15498 }
15499 TypeInfo.Type = I->getMatchingCType();
15500 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
15501 TypeInfo.MustBeNull = I->getMustBeNull();
15502 return true;
15503 }
15504 return false;
15505 }
15506
15507 if (!MagicValues)
15508 return false;
15509
15510 llvm::DenseMap<Sema::TypeTagMagicValue,
15511 Sema::TypeTagData>::const_iterator I =
15512 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
15513 if (I == MagicValues->end())
15514 return false;
15515
15516 TypeInfo = I->second;
15517 return true;
15518 }
15519
RegisterTypeTagForDatatype(const IdentifierInfo * ArgumentKind,uint64_t MagicValue,QualType Type,bool LayoutCompatible,bool MustBeNull)15520 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
15521 uint64_t MagicValue, QualType Type,
15522 bool LayoutCompatible,
15523 bool MustBeNull) {
15524 if (!TypeTagForDatatypeMagicValues)
15525 TypeTagForDatatypeMagicValues.reset(
15526 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
15527
15528 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
15529 (*TypeTagForDatatypeMagicValues)[Magic] =
15530 TypeTagData(Type, LayoutCompatible, MustBeNull);
15531 }
15532
IsSameCharType(QualType T1,QualType T2)15533 static bool IsSameCharType(QualType T1, QualType T2) {
15534 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
15535 if (!BT1)
15536 return false;
15537
15538 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
15539 if (!BT2)
15540 return false;
15541
15542 BuiltinType::Kind T1Kind = BT1->getKind();
15543 BuiltinType::Kind T2Kind = BT2->getKind();
15544
15545 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
15546 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
15547 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
15548 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
15549 }
15550
CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr * Attr,const ArrayRef<const Expr * > ExprArgs,SourceLocation CallSiteLoc)15551 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
15552 const ArrayRef<const Expr *> ExprArgs,
15553 SourceLocation CallSiteLoc) {
15554 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
15555 bool IsPointerAttr = Attr->getIsPointer();
15556
15557 // Retrieve the argument representing the 'type_tag'.
15558 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
15559 if (TypeTagIdxAST >= ExprArgs.size()) {
15560 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
15561 << 0 << Attr->getTypeTagIdx().getSourceIndex();
15562 return;
15563 }
15564 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
15565 bool FoundWrongKind;
15566 TypeTagData TypeInfo;
15567 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
15568 TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
15569 TypeInfo, isConstantEvaluated())) {
15570 if (FoundWrongKind)
15571 Diag(TypeTagExpr->getExprLoc(),
15572 diag::warn_type_tag_for_datatype_wrong_kind)
15573 << TypeTagExpr->getSourceRange();
15574 return;
15575 }
15576
15577 // Retrieve the argument representing the 'arg_idx'.
15578 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
15579 if (ArgumentIdxAST >= ExprArgs.size()) {
15580 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
15581 << 1 << Attr->getArgumentIdx().getSourceIndex();
15582 return;
15583 }
15584 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
15585 if (IsPointerAttr) {
15586 // Skip implicit cast of pointer to `void *' (as a function argument).
15587 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
15588 if (ICE->getType()->isVoidPointerType() &&
15589 ICE->getCastKind() == CK_BitCast)
15590 ArgumentExpr = ICE->getSubExpr();
15591 }
15592 QualType ArgumentType = ArgumentExpr->getType();
15593
15594 // Passing a `void*' pointer shouldn't trigger a warning.
15595 if (IsPointerAttr && ArgumentType->isVoidPointerType())
15596 return;
15597
15598 if (TypeInfo.MustBeNull) {
15599 // Type tag with matching void type requires a null pointer.
15600 if (!ArgumentExpr->isNullPointerConstant(Context,
15601 Expr::NPC_ValueDependentIsNotNull)) {
15602 Diag(ArgumentExpr->getExprLoc(),
15603 diag::warn_type_safety_null_pointer_required)
15604 << ArgumentKind->getName()
15605 << ArgumentExpr->getSourceRange()
15606 << TypeTagExpr->getSourceRange();
15607 }
15608 return;
15609 }
15610
15611 QualType RequiredType = TypeInfo.Type;
15612 if (IsPointerAttr)
15613 RequiredType = Context.getPointerType(RequiredType);
15614
15615 bool mismatch = false;
15616 if (!TypeInfo.LayoutCompatible) {
15617 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
15618
15619 // C++11 [basic.fundamental] p1:
15620 // Plain char, signed char, and unsigned char are three distinct types.
15621 //
15622 // But we treat plain `char' as equivalent to `signed char' or `unsigned
15623 // char' depending on the current char signedness mode.
15624 if (mismatch)
15625 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
15626 RequiredType->getPointeeType())) ||
15627 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
15628 mismatch = false;
15629 } else
15630 if (IsPointerAttr)
15631 mismatch = !isLayoutCompatible(Context,
15632 ArgumentType->getPointeeType(),
15633 RequiredType->getPointeeType());
15634 else
15635 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
15636
15637 if (mismatch)
15638 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
15639 << ArgumentType << ArgumentKind
15640 << TypeInfo.LayoutCompatible << RequiredType
15641 << ArgumentExpr->getSourceRange()
15642 << TypeTagExpr->getSourceRange();
15643 }
15644
AddPotentialMisalignedMembers(Expr * E,RecordDecl * RD,ValueDecl * MD,CharUnits Alignment)15645 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
15646 CharUnits Alignment) {
15647 MisalignedMembers.emplace_back(E, RD, MD, Alignment);
15648 }
15649
DiagnoseMisalignedMembers()15650 void Sema::DiagnoseMisalignedMembers() {
15651 for (MisalignedMember &m : MisalignedMembers) {
15652 const NamedDecl *ND = m.RD;
15653 if (ND->getName().empty()) {
15654 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
15655 ND = TD;
15656 }
15657 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
15658 << m.MD << ND << m.E->getSourceRange();
15659 }
15660 MisalignedMembers.clear();
15661 }
15662
DiscardMisalignedMemberAddress(const Type * T,Expr * E)15663 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
15664 E = E->IgnoreParens();
15665 if (!T->isPointerType() && !T->isIntegerType())
15666 return;
15667 if (isa<UnaryOperator>(E) &&
15668 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
15669 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
15670 if (isa<MemberExpr>(Op)) {
15671 auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
15672 if (MA != MisalignedMembers.end() &&
15673 (T->isIntegerType() ||
15674 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
15675 Context.getTypeAlignInChars(
15676 T->getPointeeType()) <= MA->Alignment))))
15677 MisalignedMembers.erase(MA);
15678 }
15679 }
15680 }
15681
RefersToMemberWithReducedAlignment(Expr * E,llvm::function_ref<void (Expr *,RecordDecl *,FieldDecl *,CharUnits)> Action)15682 void Sema::RefersToMemberWithReducedAlignment(
15683 Expr *E,
15684 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
15685 Action) {
15686 const auto *ME = dyn_cast<MemberExpr>(E);
15687 if (!ME)
15688 return;
15689
15690 // No need to check expressions with an __unaligned-qualified type.
15691 if (E->getType().getQualifiers().hasUnaligned())
15692 return;
15693
15694 // For a chain of MemberExpr like "a.b.c.d" this list
15695 // will keep FieldDecl's like [d, c, b].
15696 SmallVector<FieldDecl *, 4> ReverseMemberChain;
15697 const MemberExpr *TopME = nullptr;
15698 bool AnyIsPacked = false;
15699 do {
15700 QualType BaseType = ME->getBase()->getType();
15701 if (BaseType->isDependentType())
15702 return;
15703 if (ME->isArrow())
15704 BaseType = BaseType->getPointeeType();
15705 RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
15706 if (RD->isInvalidDecl())
15707 return;
15708
15709 ValueDecl *MD = ME->getMemberDecl();
15710 auto *FD = dyn_cast<FieldDecl>(MD);
15711 // We do not care about non-data members.
15712 if (!FD || FD->isInvalidDecl())
15713 return;
15714
15715 AnyIsPacked =
15716 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
15717 ReverseMemberChain.push_back(FD);
15718
15719 TopME = ME;
15720 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
15721 } while (ME);
15722 assert(TopME && "We did not compute a topmost MemberExpr!");
15723
15724 // Not the scope of this diagnostic.
15725 if (!AnyIsPacked)
15726 return;
15727
15728 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
15729 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
15730 // TODO: The innermost base of the member expression may be too complicated.
15731 // For now, just disregard these cases. This is left for future
15732 // improvement.
15733 if (!DRE && !isa<CXXThisExpr>(TopBase))
15734 return;
15735
15736 // Alignment expected by the whole expression.
15737 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
15738
15739 // No need to do anything else with this case.
15740 if (ExpectedAlignment.isOne())
15741 return;
15742
15743 // Synthesize offset of the whole access.
15744 CharUnits Offset;
15745 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
15746 I++) {
15747 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
15748 }
15749
15750 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
15751 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
15752 ReverseMemberChain.back()->getParent()->getTypeForDecl());
15753
15754 // The base expression of the innermost MemberExpr may give
15755 // stronger guarantees than the class containing the member.
15756 if (DRE && !TopME->isArrow()) {
15757 const ValueDecl *VD = DRE->getDecl();
15758 if (!VD->getType()->isReferenceType())
15759 CompleteObjectAlignment =
15760 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
15761 }
15762
15763 // Check if the synthesized offset fulfills the alignment.
15764 if (Offset % ExpectedAlignment != 0 ||
15765 // It may fulfill the offset it but the effective alignment may still be
15766 // lower than the expected expression alignment.
15767 CompleteObjectAlignment < ExpectedAlignment) {
15768 // If this happens, we want to determine a sensible culprit of this.
15769 // Intuitively, watching the chain of member expressions from right to
15770 // left, we start with the required alignment (as required by the field
15771 // type) but some packed attribute in that chain has reduced the alignment.
15772 // It may happen that another packed structure increases it again. But if
15773 // we are here such increase has not been enough. So pointing the first
15774 // FieldDecl that either is packed or else its RecordDecl is,
15775 // seems reasonable.
15776 FieldDecl *FD = nullptr;
15777 CharUnits Alignment;
15778 for (FieldDecl *FDI : ReverseMemberChain) {
15779 if (FDI->hasAttr<PackedAttr>() ||
15780 FDI->getParent()->hasAttr<PackedAttr>()) {
15781 FD = FDI;
15782 Alignment = std::min(
15783 Context.getTypeAlignInChars(FD->getType()),
15784 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
15785 break;
15786 }
15787 }
15788 assert(FD && "We did not find a packed FieldDecl!");
15789 Action(E, FD->getParent(), FD, Alignment);
15790 }
15791 }
15792
CheckAddressOfPackedMember(Expr * rhs)15793 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
15794 using namespace std::placeholders;
15795
15796 RefersToMemberWithReducedAlignment(
15797 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
15798 _2, _3, _4));
15799 }
15800
SemaBuiltinMatrixTranspose(CallExpr * TheCall,ExprResult CallResult)15801 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall,
15802 ExprResult CallResult) {
15803 if (checkArgCount(*this, TheCall, 1))
15804 return ExprError();
15805
15806 ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
15807 if (MatrixArg.isInvalid())
15808 return MatrixArg;
15809 Expr *Matrix = MatrixArg.get();
15810
15811 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
15812 if (!MType) {
15813 Diag(Matrix->getBeginLoc(), diag::err_builtin_matrix_arg);
15814 return ExprError();
15815 }
15816
15817 // Create returned matrix type by swapping rows and columns of the argument
15818 // matrix type.
15819 QualType ResultType = Context.getConstantMatrixType(
15820 MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
15821
15822 // Change the return type to the type of the returned matrix.
15823 TheCall->setType(ResultType);
15824
15825 // Update call argument to use the possibly converted matrix argument.
15826 TheCall->setArg(0, Matrix);
15827 return CallResult;
15828 }
15829
15830 // Get and verify the matrix dimensions.
15831 static llvm::Optional<unsigned>
getAndVerifyMatrixDimension(Expr * Expr,StringRef Name,Sema & S)15832 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) {
15833 SourceLocation ErrorPos;
15834 Optional<llvm::APSInt> Value =
15835 Expr->getIntegerConstantExpr(S.Context, &ErrorPos);
15836 if (!Value) {
15837 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
15838 << Name;
15839 return {};
15840 }
15841 uint64_t Dim = Value->getZExtValue();
15842 if (!ConstantMatrixType::isDimensionValid(Dim)) {
15843 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
15844 << Name << ConstantMatrixType::getMaxElementsPerDimension();
15845 return {};
15846 }
15847 return Dim;
15848 }
15849
SemaBuiltinMatrixColumnMajorLoad(CallExpr * TheCall,ExprResult CallResult)15850 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
15851 ExprResult CallResult) {
15852 if (!getLangOpts().MatrixTypes) {
15853 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
15854 return ExprError();
15855 }
15856
15857 if (checkArgCount(*this, TheCall, 4))
15858 return ExprError();
15859
15860 unsigned PtrArgIdx = 0;
15861 Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
15862 Expr *RowsExpr = TheCall->getArg(1);
15863 Expr *ColumnsExpr = TheCall->getArg(2);
15864 Expr *StrideExpr = TheCall->getArg(3);
15865
15866 bool ArgError = false;
15867
15868 // Check pointer argument.
15869 {
15870 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
15871 if (PtrConv.isInvalid())
15872 return PtrConv;
15873 PtrExpr = PtrConv.get();
15874 TheCall->setArg(0, PtrExpr);
15875 if (PtrExpr->isTypeDependent()) {
15876 TheCall->setType(Context.DependentTy);
15877 return TheCall;
15878 }
15879 }
15880
15881 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
15882 QualType ElementTy;
15883 if (!PtrTy) {
15884 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
15885 << PtrArgIdx + 1;
15886 ArgError = true;
15887 } else {
15888 ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
15889
15890 if (!ConstantMatrixType::isValidElementType(ElementTy)) {
15891 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
15892 << PtrArgIdx + 1;
15893 ArgError = true;
15894 }
15895 }
15896
15897 // Apply default Lvalue conversions and convert the expression to size_t.
15898 auto ApplyArgumentConversions = [this](Expr *E) {
15899 ExprResult Conv = DefaultLvalueConversion(E);
15900 if (Conv.isInvalid())
15901 return Conv;
15902
15903 return tryConvertExprToType(Conv.get(), Context.getSizeType());
15904 };
15905
15906 // Apply conversion to row and column expressions.
15907 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
15908 if (!RowsConv.isInvalid()) {
15909 RowsExpr = RowsConv.get();
15910 TheCall->setArg(1, RowsExpr);
15911 } else
15912 RowsExpr = nullptr;
15913
15914 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
15915 if (!ColumnsConv.isInvalid()) {
15916 ColumnsExpr = ColumnsConv.get();
15917 TheCall->setArg(2, ColumnsExpr);
15918 } else
15919 ColumnsExpr = nullptr;
15920
15921 // If any any part of the result matrix type is still pending, just use
15922 // Context.DependentTy, until all parts are resolved.
15923 if ((RowsExpr && RowsExpr->isTypeDependent()) ||
15924 (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
15925 TheCall->setType(Context.DependentTy);
15926 return CallResult;
15927 }
15928
15929 // Check row and column dimenions.
15930 llvm::Optional<unsigned> MaybeRows;
15931 if (RowsExpr)
15932 MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
15933
15934 llvm::Optional<unsigned> MaybeColumns;
15935 if (ColumnsExpr)
15936 MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
15937
15938 // Check stride argument.
15939 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
15940 if (StrideConv.isInvalid())
15941 return ExprError();
15942 StrideExpr = StrideConv.get();
15943 TheCall->setArg(3, StrideExpr);
15944
15945 if (MaybeRows) {
15946 if (Optional<llvm::APSInt> Value =
15947 StrideExpr->getIntegerConstantExpr(Context)) {
15948 uint64_t Stride = Value->getZExtValue();
15949 if (Stride < *MaybeRows) {
15950 Diag(StrideExpr->getBeginLoc(),
15951 diag::err_builtin_matrix_stride_too_small);
15952 ArgError = true;
15953 }
15954 }
15955 }
15956
15957 if (ArgError || !MaybeRows || !MaybeColumns)
15958 return ExprError();
15959
15960 TheCall->setType(
15961 Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
15962 return CallResult;
15963 }
15964
SemaBuiltinMatrixColumnMajorStore(CallExpr * TheCall,ExprResult CallResult)15965 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall,
15966 ExprResult CallResult) {
15967 if (checkArgCount(*this, TheCall, 3))
15968 return ExprError();
15969
15970 unsigned PtrArgIdx = 1;
15971 Expr *MatrixExpr = TheCall->getArg(0);
15972 Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
15973 Expr *StrideExpr = TheCall->getArg(2);
15974
15975 bool ArgError = false;
15976
15977 {
15978 ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
15979 if (MatrixConv.isInvalid())
15980 return MatrixConv;
15981 MatrixExpr = MatrixConv.get();
15982 TheCall->setArg(0, MatrixExpr);
15983 }
15984 if (MatrixExpr->isTypeDependent()) {
15985 TheCall->setType(Context.DependentTy);
15986 return TheCall;
15987 }
15988
15989 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
15990 if (!MatrixTy) {
15991 Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_matrix_arg) << 0;
15992 ArgError = true;
15993 }
15994
15995 {
15996 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
15997 if (PtrConv.isInvalid())
15998 return PtrConv;
15999 PtrExpr = PtrConv.get();
16000 TheCall->setArg(1, PtrExpr);
16001 if (PtrExpr->isTypeDependent()) {
16002 TheCall->setType(Context.DependentTy);
16003 return TheCall;
16004 }
16005 }
16006
16007 // Check pointer argument.
16008 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16009 if (!PtrTy) {
16010 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
16011 << PtrArgIdx + 1;
16012 ArgError = true;
16013 } else {
16014 QualType ElementTy = PtrTy->getPointeeType();
16015 if (ElementTy.isConstQualified()) {
16016 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
16017 ArgError = true;
16018 }
16019 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
16020 if (MatrixTy &&
16021 !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
16022 Diag(PtrExpr->getBeginLoc(),
16023 diag::err_builtin_matrix_pointer_arg_mismatch)
16024 << ElementTy << MatrixTy->getElementType();
16025 ArgError = true;
16026 }
16027 }
16028
16029 // Apply default Lvalue conversions and convert the stride expression to
16030 // size_t.
16031 {
16032 ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
16033 if (StrideConv.isInvalid())
16034 return StrideConv;
16035
16036 StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
16037 if (StrideConv.isInvalid())
16038 return StrideConv;
16039 StrideExpr = StrideConv.get();
16040 TheCall->setArg(2, StrideExpr);
16041 }
16042
16043 // Check stride argument.
16044 if (MatrixTy) {
16045 if (Optional<llvm::APSInt> Value =
16046 StrideExpr->getIntegerConstantExpr(Context)) {
16047 uint64_t Stride = Value->getZExtValue();
16048 if (Stride < MatrixTy->getNumRows()) {
16049 Diag(StrideExpr->getBeginLoc(),
16050 diag::err_builtin_matrix_stride_too_small);
16051 ArgError = true;
16052 }
16053 }
16054 }
16055
16056 if (ArgError)
16057 return ExprError();
16058
16059 return CallResult;
16060 }
16061