63 #include "llvm/ADT/APFloat.h" 64 #include "llvm/ADT/APInt.h" 65 #include "llvm/ADT/APSInt.h" 66 #include "llvm/ADT/ArrayRef.h" 67 #include "llvm/ADT/DenseMap.h" 68 #include "llvm/ADT/FoldingSet.h" 69 #include "llvm/ADT/None.h" 70 #include "llvm/ADT/Optional.h" 71 #include "llvm/ADT/STLExtras.h" 72 #include "llvm/ADT/SmallBitVector.h" 73 #include "llvm/ADT/SmallPtrSet.h" 74 #include "llvm/ADT/SmallString.h" 75 #include "llvm/ADT/SmallVector.h" 76 #include "llvm/ADT/StringRef.h" 77 #include "llvm/ADT/StringSwitch.h" 78 #include "llvm/ADT/Triple.h" 79 #include "llvm/Support/AtomicOrdering.h" 80 #include "llvm/Support/Casting.h" 81 #include "llvm/Support/Compiler.h" 82 #include "llvm/Support/ConvertUTF.h" 83 #include "llvm/Support/ErrorHandling.h" 84 #include "llvm/Support/Format.h" 85 #include "llvm/Support/Locale.h" 86 #include "llvm/Support/MathExtras.h" 87 #include "llvm/Support/raw_ostream.h" 98 using namespace clang;
102 unsigned ByteNo)
const {
111 if (argCount == desiredArgCount)
return false;
113 if (argCount < desiredArgCount)
114 return S.
Diag(call->
getLocEnd(), diag::err_typecheck_call_too_few_args)
115 << 0 << desiredArgCount << argCount
122 return S.
Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
123 << 0 << desiredArgCount << argCount
145 if (!Literal || !Literal->
isAscii()) {
158 S.
Diag(TheCall->
getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
166 auto *Literal = dyn_cast<
StringLiteral>(Arg->IgnoreParenCasts());
167 if (!Literal || !Literal->isWide()) {
168 S.
Diag(Arg->getLocStart(), diag::err_msvc_annotation_wide_str)
169 << Arg->getSourceRange();
185 if (ResultType.isNull())
188 TheCall->
setArg(0, Arg.get());
198 for (
unsigned I = 0; I < 2; ++I) {
215 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
216 !PtrTy->getPointeeType().isConstQualified())) {
227 CallExpr *TheCall,
unsigned SizeIdx,
228 unsigned DstSizeIdx) {
233 const Expr *SizeArg = TheCall->
getArg(SizeIdx);
234 const Expr *DstSizeArg = TheCall->
getArg(DstSizeIdx);
236 llvm::APSInt Size, DstSize;
243 if (Size.ule(DstSize))
251 S.
Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
264 S.
Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
269 auto CE = cast<CallExpr>(Call);
270 if (CE->getCallee()->getType()->isBlockPointerType()) {
271 S.
Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
276 const Decl *TargetDecl = CE->getCalleeDecl();
277 if (
const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
278 if (FD->getBuiltinID()) {
279 S.
Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
284 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
285 S.
Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
293 if (!ChainResult.
get()->getType()->isPointerType()) {
294 S.
Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
300 QualType ArgTys[2] = { ReturnTy, ChainResult.
get()->getType() };
308 BuiltinCall->
setType(CE->getType());
312 BuiltinCall->
setArg(1, ChainResult.
get());
329 if (!S || !(S->
getFlags() & NeededScopeFlags)) {
332 << DRE->getDecl()->getIdentifier();
348 ArrayRef<QualType> Params =
350 unsigned ArgCounter = 0;
351 bool IllegalParams =
false;
354 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
355 I != E; ++I, ++ArgCounter) {
356 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
357 (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
363 if (isa<BlockExpr>(BlockArg)) {
364 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
366 }
else if (isa<DeclRefExpr>(BlockArg)) {
367 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getLocStart();
370 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
371 IllegalParams =
true;
375 return IllegalParams;
398 diag::err_opencl_builtin_expected_type)
406 diag::err_opencl_builtin_expected_type)
423 diag::err_opencl_builtin_expected_type)
435 unsigned Start,
unsigned End) {
436 bool IllegalParams =
false;
437 for (
unsigned I = Start; I <=
End; ++I)
440 return IllegalParams;
447 unsigned NumNonVarArgs) {
450 unsigned NumBlockParams =
452 unsigned TotalNumArgs = TheCall->
getNumArgs();
456 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
458 diag::err_opencl_enqueue_kernel_local_size_args);
509 diag::err_opencl_builtin_expected_type)
517 diag::err_opencl_builtin_expected_type)
518 << TheCall->
getDirectCallee() <<
"'kernel_enqueue_flags_t' (i.e. uint)";
525 diag::err_opencl_builtin_expected_type)
544 diag::err_opencl_enqueue_kernel_blocks_no_args);
568 diag::err_opencl_builtin_expected_type)
581 diag::err_opencl_builtin_expected_type)
593 diag::err_opencl_builtin_expected_type)
607 diag::err_opencl_enqueue_kernel_incorrect_args);
613 return D->
getAttr<OpenCLAccessAttr>();
625 OpenCLAccessAttr *AccessQual =
632 case Builtin::BIread_pipe:
633 case Builtin::BIreserve_read_pipe:
634 case Builtin::BIcommit_read_pipe:
635 case Builtin::BIwork_group_reserve_read_pipe:
636 case Builtin::BIsub_group_reserve_read_pipe:
637 case Builtin::BIwork_group_commit_read_pipe:
638 case Builtin::BIsub_group_commit_read_pipe:
639 if (!(!AccessQual || AccessQual->isReadOnly())) {
641 diag::err_opencl_builtin_pipe_invalid_access_modifier)
646 case Builtin::BIwrite_pipe:
647 case Builtin::BIreserve_write_pipe:
648 case Builtin::BIcommit_write_pipe:
649 case Builtin::BIwork_group_reserve_write_pipe:
650 case Builtin::BIsub_group_reserve_write_pipe:
651 case Builtin::BIwork_group_commit_write_pipe:
652 case Builtin::BIsub_group_commit_write_pipe:
653 if (!(AccessQual && AccessQual->isWriteOnly())) {
655 diag::err_opencl_builtin_pipe_invalid_access_modifier)
825 if (!RT->isPointerType() || RT->getPointeeType()
827 S.
Diag(Call->
getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg)
832 RT = RT->getPointeeType();
833 auto Qual = RT.getQualifiers();
835 case Builtin::BIto_global:
838 case Builtin::BIto_local:
841 case Builtin::BIto_private:
845 llvm_unreachable(
"Invalid builtin function");
848 RT.getUnqualifiedType(), Qual)));
854 Sema::CheckBuiltinFunctionCall(
FunctionDecl *FDecl,
unsigned BuiltinID,
859 unsigned ICEArguments = 0;
866 for (
unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
868 if ((ICEArguments & (1 << ArgNo)) == 0)
continue;
871 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
873 ICEArguments &= ~(1 << ArgNo);
877 case Builtin::BI__builtin___CFStringMakeConstantString:
879 "Wrong # arguments to builtin CFStringMakeConstantString");
880 if (CheckObjCString(TheCall->
getArg(0)))
883 case Builtin::BI__builtin_ms_va_start:
884 case Builtin::BI__builtin_stdarg_start:
885 case Builtin::BI__builtin_va_start:
886 if (SemaBuiltinVAStart(BuiltinID, TheCall))
889 case Builtin::BI__va_start: {
891 case llvm::Triple::arm:
892 case llvm::Triple::thumb:
893 if (SemaBuiltinVAStartARMMicrosoft(TheCall))
897 if (SemaBuiltinVAStart(BuiltinID, TheCall))
903 case Builtin::BI__builtin_isgreater:
904 case Builtin::BI__builtin_isgreaterequal:
905 case Builtin::BI__builtin_isless:
906 case Builtin::BI__builtin_islessequal:
907 case Builtin::BI__builtin_islessgreater:
908 case Builtin::BI__builtin_isunordered:
909 if (SemaBuiltinUnorderedCompare(TheCall))
912 case Builtin::BI__builtin_fpclassify:
913 if (SemaBuiltinFPClassification(TheCall, 6))
916 case Builtin::BI__builtin_isfinite:
917 case Builtin::BI__builtin_isinf:
918 case Builtin::BI__builtin_isinf_sign:
919 case Builtin::BI__builtin_isnan:
920 case Builtin::BI__builtin_isnormal:
921 if (SemaBuiltinFPClassification(TheCall, 1))
924 case Builtin::BI__builtin_shufflevector:
925 return SemaBuiltinShuffleVector(TheCall);
928 case Builtin::BI__builtin_prefetch:
929 if (SemaBuiltinPrefetch(TheCall))
932 case Builtin::BI__builtin_alloca_with_align:
933 if (SemaBuiltinAllocaWithAlign(TheCall))
936 case Builtin::BI__assume:
937 case Builtin::BI__builtin_assume:
938 if (SemaBuiltinAssume(TheCall))
941 case Builtin::BI__builtin_assume_aligned:
942 if (SemaBuiltinAssumeAligned(TheCall))
945 case Builtin::BI__builtin_object_size:
946 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
949 case Builtin::BI__builtin_longjmp:
950 if (SemaBuiltinLongjmp(TheCall))
953 case Builtin::BI__builtin_setjmp:
954 if (SemaBuiltinSetjmp(TheCall))
957 case Builtin::BI_setjmp:
958 case Builtin::BI_setjmpex:
962 case Builtin::BI__builtin_classify_type:
966 case Builtin::BI__builtin_constant_p:
970 case Builtin::BI__sync_fetch_and_add:
971 case Builtin::BI__sync_fetch_and_add_1:
972 case Builtin::BI__sync_fetch_and_add_2:
973 case Builtin::BI__sync_fetch_and_add_4:
974 case Builtin::BI__sync_fetch_and_add_8:
975 case Builtin::BI__sync_fetch_and_add_16:
976 case Builtin::BI__sync_fetch_and_sub:
977 case Builtin::BI__sync_fetch_and_sub_1:
978 case Builtin::BI__sync_fetch_and_sub_2:
979 case Builtin::BI__sync_fetch_and_sub_4:
980 case Builtin::BI__sync_fetch_and_sub_8:
981 case Builtin::BI__sync_fetch_and_sub_16:
982 case Builtin::BI__sync_fetch_and_or:
983 case Builtin::BI__sync_fetch_and_or_1:
984 case Builtin::BI__sync_fetch_and_or_2:
985 case Builtin::BI__sync_fetch_and_or_4:
986 case Builtin::BI__sync_fetch_and_or_8:
987 case Builtin::BI__sync_fetch_and_or_16:
988 case Builtin::BI__sync_fetch_and_and:
989 case Builtin::BI__sync_fetch_and_and_1:
990 case Builtin::BI__sync_fetch_and_and_2:
991 case Builtin::BI__sync_fetch_and_and_4:
992 case Builtin::BI__sync_fetch_and_and_8:
993 case Builtin::BI__sync_fetch_and_and_16:
994 case Builtin::BI__sync_fetch_and_xor:
995 case Builtin::BI__sync_fetch_and_xor_1:
996 case Builtin::BI__sync_fetch_and_xor_2:
997 case Builtin::BI__sync_fetch_and_xor_4:
998 case Builtin::BI__sync_fetch_and_xor_8:
999 case Builtin::BI__sync_fetch_and_xor_16:
1000 case Builtin::BI__sync_fetch_and_nand:
1001 case Builtin::BI__sync_fetch_and_nand_1:
1002 case Builtin::BI__sync_fetch_and_nand_2:
1003 case Builtin::BI__sync_fetch_and_nand_4:
1004 case Builtin::BI__sync_fetch_and_nand_8:
1005 case Builtin::BI__sync_fetch_and_nand_16:
1006 case Builtin::BI__sync_add_and_fetch:
1007 case Builtin::BI__sync_add_and_fetch_1:
1008 case Builtin::BI__sync_add_and_fetch_2:
1009 case Builtin::BI__sync_add_and_fetch_4:
1010 case Builtin::BI__sync_add_and_fetch_8:
1011 case Builtin::BI__sync_add_and_fetch_16:
1012 case Builtin::BI__sync_sub_and_fetch:
1013 case Builtin::BI__sync_sub_and_fetch_1:
1014 case Builtin::BI__sync_sub_and_fetch_2:
1015 case Builtin::BI__sync_sub_and_fetch_4:
1016 case Builtin::BI__sync_sub_and_fetch_8:
1017 case Builtin::BI__sync_sub_and_fetch_16:
1018 case Builtin::BI__sync_and_and_fetch:
1019 case Builtin::BI__sync_and_and_fetch_1:
1020 case Builtin::BI__sync_and_and_fetch_2:
1021 case Builtin::BI__sync_and_and_fetch_4:
1022 case Builtin::BI__sync_and_and_fetch_8:
1023 case Builtin::BI__sync_and_and_fetch_16:
1024 case Builtin::BI__sync_or_and_fetch:
1025 case Builtin::BI__sync_or_and_fetch_1:
1026 case Builtin::BI__sync_or_and_fetch_2:
1027 case Builtin::BI__sync_or_and_fetch_4:
1028 case Builtin::BI__sync_or_and_fetch_8:
1029 case Builtin::BI__sync_or_and_fetch_16:
1030 case Builtin::BI__sync_xor_and_fetch:
1031 case Builtin::BI__sync_xor_and_fetch_1:
1032 case Builtin::BI__sync_xor_and_fetch_2:
1033 case Builtin::BI__sync_xor_and_fetch_4:
1034 case Builtin::BI__sync_xor_and_fetch_8:
1035 case Builtin::BI__sync_xor_and_fetch_16:
1036 case Builtin::BI__sync_nand_and_fetch:
1037 case Builtin::BI__sync_nand_and_fetch_1:
1038 case Builtin::BI__sync_nand_and_fetch_2:
1039 case Builtin::BI__sync_nand_and_fetch_4:
1040 case Builtin::BI__sync_nand_and_fetch_8:
1041 case Builtin::BI__sync_nand_and_fetch_16:
1042 case Builtin::BI__sync_val_compare_and_swap:
1043 case Builtin::BI__sync_val_compare_and_swap_1:
1044 case Builtin::BI__sync_val_compare_and_swap_2:
1045 case Builtin::BI__sync_val_compare_and_swap_4:
1046 case Builtin::BI__sync_val_compare_and_swap_8:
1047 case Builtin::BI__sync_val_compare_and_swap_16:
1048 case Builtin::BI__sync_bool_compare_and_swap:
1049 case Builtin::BI__sync_bool_compare_and_swap_1:
1050 case Builtin::BI__sync_bool_compare_and_swap_2:
1051 case Builtin::BI__sync_bool_compare_and_swap_4:
1052 case Builtin::BI__sync_bool_compare_and_swap_8:
1053 case Builtin::BI__sync_bool_compare_and_swap_16:
1054 case Builtin::BI__sync_lock_test_and_set:
1055 case Builtin::BI__sync_lock_test_and_set_1:
1056 case Builtin::BI__sync_lock_test_and_set_2:
1057 case Builtin::BI__sync_lock_test_and_set_4:
1058 case Builtin::BI__sync_lock_test_and_set_8:
1059 case Builtin::BI__sync_lock_test_and_set_16:
1060 case Builtin::BI__sync_lock_release:
1061 case Builtin::BI__sync_lock_release_1:
1062 case Builtin::BI__sync_lock_release_2:
1063 case Builtin::BI__sync_lock_release_4:
1064 case Builtin::BI__sync_lock_release_8:
1065 case Builtin::BI__sync_lock_release_16:
1066 case Builtin::BI__sync_swap:
1067 case Builtin::BI__sync_swap_1:
1068 case Builtin::BI__sync_swap_2:
1069 case Builtin::BI__sync_swap_4:
1070 case Builtin::BI__sync_swap_8:
1071 case Builtin::BI__sync_swap_16:
1072 return SemaBuiltinAtomicOverloaded(TheCallResult);
1073 case Builtin::BI__builtin_nontemporal_load:
1074 case Builtin::BI__builtin_nontemporal_store:
1075 return SemaBuiltinNontemporalOverloaded(TheCallResult);
1076 #define BUILTIN(ID, TYPE, ATTRS) 1077 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 1078 case Builtin::BI##ID: \ 1079 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 1080 #include "clang/Basic/Builtins.def" 1081 case Builtin::BI__annotation:
1085 case Builtin::BI__builtin_annotation:
1089 case Builtin::BI__builtin_addressof:
1093 case Builtin::BI__builtin_add_overflow:
1094 case Builtin::BI__builtin_sub_overflow:
1095 case Builtin::BI__builtin_mul_overflow:
1099 case Builtin::BI__builtin_operator_new:
1100 case Builtin::BI__builtin_operator_delete:
1103 << (BuiltinID == Builtin::BI__builtin_operator_new
1104 ?
"__builtin_operator_new" 1105 :
"__builtin_operator_delete")
1111 DeclareGlobalNewDelete();
1116 case Builtin::BI__builtin___memcpy_chk:
1117 case Builtin::BI__builtin___memmove_chk:
1118 case Builtin::BI__builtin___memset_chk:
1119 case Builtin::BI__builtin___strlcat_chk:
1120 case Builtin::BI__builtin___strlcpy_chk:
1121 case Builtin::BI__builtin___strncat_chk:
1122 case Builtin::BI__builtin___strncpy_chk:
1123 case Builtin::BI__builtin___stpncpy_chk:
1126 case Builtin::BI__builtin___memccpy_chk:
1129 case Builtin::BI__builtin___snprintf_chk:
1130 case Builtin::BI__builtin___vsnprintf_chk:
1133 case Builtin::BI__builtin_call_with_static_chain:
1137 case Builtin::BI__exception_code:
1138 case Builtin::BI_exception_code:
1140 diag::err_seh___except_block))
1143 case Builtin::BI__exception_info:
1144 case Builtin::BI_exception_info:
1146 diag::err_seh___except_filter))
1149 case Builtin::BI__GetExceptionInfo:
1153 if (CheckCXXThrowOperand(
1162 case Builtin::BIread_pipe:
1163 case Builtin::BIwrite_pipe:
1170 case Builtin::BIreserve_read_pipe:
1171 case Builtin::BIreserve_write_pipe:
1172 case Builtin::BIwork_group_reserve_read_pipe:
1173 case Builtin::BIwork_group_reserve_write_pipe:
1177 case Builtin::BIsub_group_reserve_read_pipe:
1178 case Builtin::BIsub_group_reserve_write_pipe:
1183 case Builtin::BIcommit_read_pipe:
1184 case Builtin::BIcommit_write_pipe:
1185 case Builtin::BIwork_group_commit_read_pipe:
1186 case Builtin::BIwork_group_commit_write_pipe:
1190 case Builtin::BIsub_group_commit_read_pipe:
1191 case Builtin::BIsub_group_commit_write_pipe:
1196 case Builtin::BIget_pipe_num_packets:
1197 case Builtin::BIget_pipe_max_packets:
1202 case Builtin::BIto_global:
1203 case Builtin::BIto_local:
1204 case Builtin::BIto_private:
1209 case Builtin::BIenqueue_kernel:
1213 case Builtin::BIget_kernel_work_group_size:
1214 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1219 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1220 case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1224 case Builtin::BI__builtin_os_log_format:
1225 case Builtin::BI__builtin_os_log_format_buffer_size:
1226 if (SemaBuiltinOSLogFormat(TheCall))
1235 case llvm::Triple::arm:
1236 case llvm::Triple::armeb:
1237 case llvm::Triple::thumb:
1238 case llvm::Triple::thumbeb:
1239 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1242 case llvm::Triple::aarch64:
1243 case llvm::Triple::aarch64_be:
1244 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
1247 case llvm::Triple::mips:
1248 case llvm::Triple::mipsel:
1249 case llvm::Triple::mips64:
1250 case llvm::Triple::mips64el:
1251 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1254 case llvm::Triple::systemz:
1255 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1258 case llvm::Triple::x86:
1259 case llvm::Triple::x86_64:
1260 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1263 case llvm::Triple::ppc:
1264 case llvm::Triple::ppc64:
1265 case llvm::Triple::ppc64le:
1266 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1274 return TheCallResult;
1278 static unsigned RFT(
unsigned t,
bool shift =
false,
bool ForceQuad =
false) {
1280 int IsQuad = ForceQuad ?
true : Type.
isQuad();
1284 return shift ? 7 : (8 << IsQuad) - 1;
1287 return shift ? 15 : (4 << IsQuad) - 1;
1289 return shift ? 31 : (2 << IsQuad) - 1;
1292 return shift ? 63 : (1 << IsQuad) - 1;
1294 return shift ? 127 : (1 << IsQuad) - 1;
1296 assert(!shift &&
"cannot shift float types!");
1297 return (4 << IsQuad) - 1;
1299 assert(!shift &&
"cannot shift float types!");
1300 return (2 << IsQuad) - 1;
1302 assert(!shift &&
"cannot shift float types!");
1303 return (1 << IsQuad) - 1;
1305 llvm_unreachable(
"Invalid NeonTypeFlag!");
1312 bool IsPolyUnsigned,
bool IsInt64Long) {
1344 llvm_unreachable(
"Invalid NeonTypeFlag!");
1347 bool Sema::CheckNeonBuiltinFunctionCall(
unsigned BuiltinID,
CallExpr *TheCall) {
1348 llvm::APSInt Result;
1352 bool HasConstPtr =
false;
1353 switch (BuiltinID) {
1354 #define GET_NEON_OVERLOAD_CHECK 1355 #include "clang/Basic/arm_neon.inc" 1356 #undef GET_NEON_OVERLOAD_CHECK 1363 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1366 TV = Result.getLimitedValue(64);
1367 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1372 if (PtrArgNum >= 0) {
1376 Arg = ICE->getSubExpr();
1377 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1381 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
1382 Arch == llvm::Triple::aarch64_be;
1390 AssignConvertType ConvTy;
1391 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1394 if (DiagnoseAssignmentResult(ConvTy, Arg->
getLocStart(), LHSTy, RHSTy,
1395 RHS.
get(), AA_Assigning))
1401 unsigned i = 0, l = 0, u = 0;
1402 switch (BuiltinID) {
1405 #define GET_NEON_IMMEDIATE_CHECK 1406 #include "clang/Basic/arm_neon.inc" 1407 #undef GET_NEON_IMMEDIATE_CHECK 1410 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1413 bool Sema::CheckARMBuiltinExclusiveCall(
unsigned BuiltinID,
CallExpr *TheCall,
1414 unsigned MaxWidth) {
1415 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
1416 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1417 BuiltinID == ARM::BI__builtin_arm_strex ||
1418 BuiltinID == ARM::BI__builtin_arm_stlex ||
1419 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1420 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1421 BuiltinID == AArch64::BI__builtin_arm_strex ||
1422 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
1423 "unexpected ARM builtin");
1424 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
1425 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1426 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1427 BuiltinID == AArch64::BI__builtin_arm_ldaex;
1439 Expr *PointerArg = TheCall->
getArg(IsLdrex ? 0 : 1);
1440 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1443 PointerArg = PointerArgRes.
get();
1463 CastNeeded = CK_BitCast;
1464 Diag(DRE->
getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1472 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1475 PointerArg = PointerArgRes.
get();
1477 TheCall->
setArg(IsLdrex ? 0 : 1, PointerArg);
1482 Diag(DRE->
getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1489 assert(MaxWidth == 64 &&
"Diagnostic unexpectedly inaccurate");
1490 Diag(DRE->
getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1517 Context, ValType,
false);
1518 ValArg = PerformCopyInitialization(Entity,
SourceLocation(), ValArg);
1529 bool Sema::CheckARMBuiltinFunctionCall(
unsigned BuiltinID,
CallExpr *TheCall) {
1530 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
1531 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1532 BuiltinID == ARM::BI__builtin_arm_strex ||
1533 BuiltinID == ARM::BI__builtin_arm_stlex) {
1534 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
1537 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1538 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1539 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1542 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1543 BuiltinID == ARM::BI__builtin_arm_wsr64)
1544 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3,
false);
1546 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1547 BuiltinID == ARM::BI__builtin_arm_rsrp ||
1548 BuiltinID == ARM::BI__builtin_arm_wsr ||
1549 BuiltinID == ARM::BI__builtin_arm_wsrp)
1550 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5,
true);
1552 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1558 switch (BuiltinID) {
1559 default:
return false;
1560 case ARM::BI__builtin_arm_ssat:
1561 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
1562 case ARM::BI__builtin_arm_usat:
1563 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
1564 case ARM::BI__builtin_arm_ssat16:
1565 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
1566 case ARM::BI__builtin_arm_usat16:
1567 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
1568 case ARM::BI__builtin_arm_vcvtr_f:
1569 case ARM::BI__builtin_arm_vcvtr_d:
1570 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
1571 case ARM::BI__builtin_arm_dmb:
1572 case ARM::BI__builtin_arm_dsb:
1573 case ARM::BI__builtin_arm_isb:
1574 case ARM::BI__builtin_arm_dbg:
1575 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
1579 bool Sema::CheckAArch64BuiltinFunctionCall(
unsigned BuiltinID,
1581 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1582 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1583 BuiltinID == AArch64::BI__builtin_arm_strex ||
1584 BuiltinID == AArch64::BI__builtin_arm_stlex) {
1585 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1588 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1589 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1590 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1591 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1592 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1595 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1596 BuiltinID == AArch64::BI__builtin_arm_wsr64)
1597 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5,
true);
1599 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1600 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1601 BuiltinID == AArch64::BI__builtin_arm_wsr ||
1602 BuiltinID == AArch64::BI__builtin_arm_wsrp)
1603 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5,
true);
1605 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1610 unsigned i = 0, l = 0, u = 0;
1611 switch (BuiltinID) {
1612 default:
return false;
1613 case AArch64::BI__builtin_arm_dmb:
1614 case AArch64::BI__builtin_arm_dsb:
1615 case AArch64::BI__builtin_arm_isb: l = 0; u = 15;
break;
1618 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1630 bool Sema::CheckMipsBuiltinFunctionCall(
unsigned BuiltinID,
CallExpr *TheCall) {
1631 unsigned i = 0, l = 0, u = 0, m = 0;
1632 switch (BuiltinID) {
1633 default:
return false;
1634 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63;
break;
1635 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63;
break;
1636 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31;
break;
1637 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3;
break;
1638 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31;
break;
1639 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31;
break;
1640 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31;
break;
1644 case Mips::BI__builtin_msa_bclri_b:
1645 case Mips::BI__builtin_msa_bnegi_b:
1646 case Mips::BI__builtin_msa_bseti_b:
1647 case Mips::BI__builtin_msa_sat_s_b:
1648 case Mips::BI__builtin_msa_sat_u_b:
1649 case Mips::BI__builtin_msa_slli_b:
1650 case Mips::BI__builtin_msa_srai_b:
1651 case Mips::BI__builtin_msa_srari_b:
1652 case Mips::BI__builtin_msa_srli_b:
1653 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7;
break;
1654 case Mips::BI__builtin_msa_binsli_b:
1655 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7;
break;
1657 case Mips::BI__builtin_msa_bclri_h:
1658 case Mips::BI__builtin_msa_bnegi_h:
1659 case Mips::BI__builtin_msa_bseti_h:
1660 case Mips::BI__builtin_msa_sat_s_h:
1661 case Mips::BI__builtin_msa_sat_u_h:
1662 case Mips::BI__builtin_msa_slli_h:
1663 case Mips::BI__builtin_msa_srai_h:
1664 case Mips::BI__builtin_msa_srari_h:
1665 case Mips::BI__builtin_msa_srli_h:
1666 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15;
break;
1667 case Mips::BI__builtin_msa_binsli_h:
1668 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15;
break;
1672 case Mips::BI__builtin_msa_clei_u_b:
1673 case Mips::BI__builtin_msa_clei_u_h:
1674 case Mips::BI__builtin_msa_clei_u_w:
1675 case Mips::BI__builtin_msa_clei_u_d:
1676 case Mips::BI__builtin_msa_clti_u_b:
1677 case Mips::BI__builtin_msa_clti_u_h:
1678 case Mips::BI__builtin_msa_clti_u_w:
1679 case Mips::BI__builtin_msa_clti_u_d:
1680 case Mips::BI__builtin_msa_maxi_u_b:
1681 case Mips::BI__builtin_msa_maxi_u_h:
1682 case Mips::BI__builtin_msa_maxi_u_w:
1683 case Mips::BI__builtin_msa_maxi_u_d:
1684 case Mips::BI__builtin_msa_mini_u_b:
1685 case Mips::BI__builtin_msa_mini_u_h:
1686 case Mips::BI__builtin_msa_mini_u_w:
1687 case Mips::BI__builtin_msa_mini_u_d:
1688 case Mips::BI__builtin_msa_addvi_b:
1689 case Mips::BI__builtin_msa_addvi_h:
1690 case Mips::BI__builtin_msa_addvi_w:
1691 case Mips::BI__builtin_msa_addvi_d:
1692 case Mips::BI__builtin_msa_bclri_w:
1693 case Mips::BI__builtin_msa_bnegi_w:
1694 case Mips::BI__builtin_msa_bseti_w:
1695 case Mips::BI__builtin_msa_sat_s_w:
1696 case Mips::BI__builtin_msa_sat_u_w:
1697 case Mips::BI__builtin_msa_slli_w:
1698 case Mips::BI__builtin_msa_srai_w:
1699 case Mips::BI__builtin_msa_srari_w:
1700 case Mips::BI__builtin_msa_srli_w:
1701 case Mips::BI__builtin_msa_srlri_w:
1702 case Mips::BI__builtin_msa_subvi_b:
1703 case Mips::BI__builtin_msa_subvi_h:
1704 case Mips::BI__builtin_msa_subvi_w:
1705 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31;
break;
1706 case Mips::BI__builtin_msa_binsli_w:
1707 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31;
break;
1709 case Mips::BI__builtin_msa_bclri_d:
1710 case Mips::BI__builtin_msa_bnegi_d:
1711 case Mips::BI__builtin_msa_bseti_d:
1712 case Mips::BI__builtin_msa_sat_s_d:
1713 case Mips::BI__builtin_msa_sat_u_d:
1714 case Mips::BI__builtin_msa_slli_d:
1715 case Mips::BI__builtin_msa_srai_d:
1716 case Mips::BI__builtin_msa_srari_d:
1717 case Mips::BI__builtin_msa_srli_d:
1718 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63;
break;
1719 case Mips::BI__builtin_msa_binsli_d:
1720 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63;
break;
1722 case Mips::BI__builtin_msa_ceqi_b:
1723 case Mips::BI__builtin_msa_ceqi_h:
1724 case Mips::BI__builtin_msa_ceqi_w:
1725 case Mips::BI__builtin_msa_ceqi_d:
1726 case Mips::BI__builtin_msa_clti_s_b:
1727 case Mips::BI__builtin_msa_clti_s_h:
1728 case Mips::BI__builtin_msa_clti_s_w:
1729 case Mips::BI__builtin_msa_clti_s_d:
1730 case Mips::BI__builtin_msa_clei_s_b:
1731 case Mips::BI__builtin_msa_clei_s_h:
1732 case Mips::BI__builtin_msa_clei_s_w:
1733 case Mips::BI__builtin_msa_clei_s_d:
1734 case Mips::BI__builtin_msa_maxi_s_b:
1735 case Mips::BI__builtin_msa_maxi_s_h:
1736 case Mips::BI__builtin_msa_maxi_s_w:
1737 case Mips::BI__builtin_msa_maxi_s_d:
1738 case Mips::BI__builtin_msa_mini_s_b:
1739 case Mips::BI__builtin_msa_mini_s_h:
1740 case Mips::BI__builtin_msa_mini_s_w:
1741 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15;
break;
1743 case Mips::BI__builtin_msa_andi_b:
1744 case Mips::BI__builtin_msa_nori_b:
1745 case Mips::BI__builtin_msa_ori_b:
1746 case Mips::BI__builtin_msa_shf_b:
1747 case Mips::BI__builtin_msa_shf_h:
1748 case Mips::BI__builtin_msa_shf_w:
1749 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255;
break;
1750 case Mips::BI__builtin_msa_bseli_b:
1751 case Mips::BI__builtin_msa_bmnzi_b:
1752 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255;
break;
1755 case Mips::BI__builtin_msa_copy_s_b:
1756 case Mips::BI__builtin_msa_copy_u_b:
1757 case Mips::BI__builtin_msa_insve_b:
1758 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15;
break;
1759 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15;
break;
1761 case Mips::BI__builtin_msa_copy_s_h:
1762 case Mips::BI__builtin_msa_copy_u_h:
1763 case Mips::BI__builtin_msa_insve_h:
1764 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7;
break;
1765 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7;
break;
1767 case Mips::BI__builtin_msa_copy_s_w:
1768 case Mips::BI__builtin_msa_copy_u_w:
1769 case Mips::BI__builtin_msa_insve_w:
1770 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3;
break;
1771 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3;
break;
1773 case Mips::BI__builtin_msa_copy_s_d:
1774 case Mips::BI__builtin_msa_copy_u_d:
1775 case Mips::BI__builtin_msa_insve_d:
1776 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1;
break;
1777 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1;
break;
1780 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255;
break;
1781 case Mips::BI__builtin_msa_ldi_h:
1782 case Mips::BI__builtin_msa_ldi_w:
1783 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511;
break;
1784 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16;
break;
1785 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16;
break;
1786 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16;
break;
1787 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16;
break;
1788 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16;
break;
1789 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16;
break;
1790 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16;
break;
1791 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16;
break;
1795 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1797 return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
1798 SemaBuiltinConstantArgMultiple(TheCall, i, m);
1801 bool Sema::CheckPPCBuiltinFunctionCall(
unsigned BuiltinID,
CallExpr *TheCall) {
1802 unsigned i = 0, l = 0, u = 0;
1803 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
1804 BuiltinID == PPC::BI__builtin_divdeu ||
1805 BuiltinID == PPC::BI__builtin_bpermd;
1809 .getIntPtrType()) == 64;
1810 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
1811 BuiltinID == PPC::BI__builtin_divweu ||
1812 BuiltinID == PPC::BI__builtin_divde ||
1813 BuiltinID == PPC::BI__builtin_divdeu;
1815 if (Is64BitBltin && !IsTarget64Bit)
1816 return Diag(TheCall->
getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
1820 (BuiltinID == PPC::BI__builtin_bpermd &&
1822 return Diag(TheCall->
getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
1825 switch (BuiltinID) {
1826 default:
return false;
1827 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1828 case PPC::BI__builtin_altivec_crypto_vshasigmad:
1829 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1830 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1831 case PPC::BI__builtin_tbegin:
1832 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1;
break;
1833 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7;
break;
1834 case PPC::BI__builtin_tabortwc:
1835 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31;
break;
1836 case PPC::BI__builtin_tabortwci:
1837 case PPC::BI__builtin_tabortdci:
1838 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1839 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
1840 case PPC::BI__builtin_vsx_xxpermdi:
1841 case PPC::BI__builtin_vsx_xxsldwi:
1842 return SemaBuiltinVSX(TheCall);
1844 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1847 bool Sema::CheckSystemZBuiltinFunctionCall(
unsigned BuiltinID,
1849 if (BuiltinID == SystemZ::BI__builtin_tabort) {
1851 llvm::APSInt AbortCode(32);
1853 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1854 return Diag(Arg->
getLocStart(), diag::err_systemz_invalid_tabort_code)
1860 unsigned i = 0, l = 0, u = 0;
1861 switch (BuiltinID) {
1862 default:
return false;
1863 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15;
break;
1864 case SystemZ::BI__builtin_s390_verimb:
1865 case SystemZ::BI__builtin_s390_verimh:
1866 case SystemZ::BI__builtin_s390_verimf:
1867 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255;
break;
1868 case SystemZ::BI__builtin_s390_vfaeb:
1869 case SystemZ::BI__builtin_s390_vfaeh:
1870 case SystemZ::BI__builtin_s390_vfaef:
1871 case SystemZ::BI__builtin_s390_vfaebs:
1872 case SystemZ::BI__builtin_s390_vfaehs:
1873 case SystemZ::BI__builtin_s390_vfaefs:
1874 case SystemZ::BI__builtin_s390_vfaezb:
1875 case SystemZ::BI__builtin_s390_vfaezh:
1876 case SystemZ::BI__builtin_s390_vfaezf:
1877 case SystemZ::BI__builtin_s390_vfaezbs:
1878 case SystemZ::BI__builtin_s390_vfaezhs:
1879 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15;
break;
1880 case SystemZ::BI__builtin_s390_vfisb:
1881 case SystemZ::BI__builtin_s390_vfidb:
1882 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1883 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1884 case SystemZ::BI__builtin_s390_vftcisb:
1885 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095;
break;
1886 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15;
break;
1887 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15;
break;
1888 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15;
break;
1889 case SystemZ::BI__builtin_s390_vstrcb:
1890 case SystemZ::BI__builtin_s390_vstrch:
1891 case SystemZ::BI__builtin_s390_vstrcf:
1892 case SystemZ::BI__builtin_s390_vstrczb:
1893 case SystemZ::BI__builtin_s390_vstrczh:
1894 case SystemZ::BI__builtin_s390_vstrczf:
1895 case SystemZ::BI__builtin_s390_vstrcbs:
1896 case SystemZ::BI__builtin_s390_vstrchs:
1897 case SystemZ::BI__builtin_s390_vstrcfs:
1898 case SystemZ::BI__builtin_s390_vstrczbs:
1899 case SystemZ::BI__builtin_s390_vstrczhs:
1900 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15;
break;
1901 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15;
break;
1902 case SystemZ::BI__builtin_s390_vfminsb:
1903 case SystemZ::BI__builtin_s390_vfmaxsb:
1904 case SystemZ::BI__builtin_s390_vfmindb:
1905 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15;
break;
1907 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1918 return S.
Diag(TheCall->
getLocStart(), diag::err_expr_not_string_literal)
1938 return S.
Diag(TheCall->
getLocStart(), diag::err_expr_not_string_literal)
1951 bool Sema::CheckX86BuiltinRoundingOrSAE(
unsigned BuiltinID,
CallExpr *TheCall) {
1955 unsigned ArgNum = 0;
1956 switch (BuiltinID) {
1959 case X86::BI__builtin_ia32_vcvttsd2si32:
1960 case X86::BI__builtin_ia32_vcvttsd2si64:
1961 case X86::BI__builtin_ia32_vcvttsd2usi32:
1962 case X86::BI__builtin_ia32_vcvttsd2usi64:
1963 case X86::BI__builtin_ia32_vcvttss2si32:
1964 case X86::BI__builtin_ia32_vcvttss2si64:
1965 case X86::BI__builtin_ia32_vcvttss2usi32:
1966 case X86::BI__builtin_ia32_vcvttss2usi64:
1969 case X86::BI__builtin_ia32_cvtps2pd512_mask:
1970 case X86::BI__builtin_ia32_cvttpd2dq512_mask:
1971 case X86::BI__builtin_ia32_cvttpd2qq512_mask:
1972 case X86::BI__builtin_ia32_cvttpd2udq512_mask:
1973 case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
1974 case X86::BI__builtin_ia32_cvttps2dq512_mask:
1975 case X86::BI__builtin_ia32_cvttps2qq512_mask:
1976 case X86::BI__builtin_ia32_cvttps2udq512_mask:
1977 case X86::BI__builtin_ia32_cvttps2uqq512_mask:
1978 case X86::BI__builtin_ia32_exp2pd_mask:
1979 case X86::BI__builtin_ia32_exp2ps_mask:
1980 case X86::BI__builtin_ia32_getexppd512_mask:
1981 case X86::BI__builtin_ia32_getexpps512_mask:
1982 case X86::BI__builtin_ia32_rcp28pd_mask:
1983 case X86::BI__builtin_ia32_rcp28ps_mask:
1984 case X86::BI__builtin_ia32_rsqrt28pd_mask:
1985 case X86::BI__builtin_ia32_rsqrt28ps_mask:
1986 case X86::BI__builtin_ia32_vcomisd:
1987 case X86::BI__builtin_ia32_vcomiss:
1988 case X86::BI__builtin_ia32_vcvtph2ps512_mask:
1991 case X86::BI__builtin_ia32_cmppd512_mask:
1992 case X86::BI__builtin_ia32_cmpps512_mask:
1993 case X86::BI__builtin_ia32_cmpsd_mask:
1994 case X86::BI__builtin_ia32_cmpss_mask:
1995 case X86::BI__builtin_ia32_cvtss2sd_round_mask:
1996 case X86::BI__builtin_ia32_getexpsd128_round_mask:
1997 case X86::BI__builtin_ia32_getexpss128_round_mask:
1998 case X86::BI__builtin_ia32_maxpd512_mask:
1999 case X86::BI__builtin_ia32_maxps512_mask:
2000 case X86::BI__builtin_ia32_maxsd_round_mask:
2001 case X86::BI__builtin_ia32_maxss_round_mask:
2002 case X86::BI__builtin_ia32_minpd512_mask:
2003 case X86::BI__builtin_ia32_minps512_mask:
2004 case X86::BI__builtin_ia32_minsd_round_mask:
2005 case X86::BI__builtin_ia32_minss_round_mask:
2006 case X86::BI__builtin_ia32_rcp28sd_round_mask:
2007 case X86::BI__builtin_ia32_rcp28ss_round_mask:
2008 case X86::BI__builtin_ia32_reducepd512_mask:
2009 case X86::BI__builtin_ia32_reduceps512_mask:
2010 case X86::BI__builtin_ia32_rndscalepd_mask:
2011 case X86::BI__builtin_ia32_rndscaleps_mask:
2012 case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
2013 case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
2016 case X86::BI__builtin_ia32_fixupimmpd512_mask:
2017 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2018 case X86::BI__builtin_ia32_fixupimmps512_mask:
2019 case X86::BI__builtin_ia32_fixupimmps512_maskz:
2020 case X86::BI__builtin_ia32_fixupimmsd_mask:
2021 case X86::BI__builtin_ia32_fixupimmsd_maskz:
2022 case X86::BI__builtin_ia32_fixupimmss_mask:
2023 case X86::BI__builtin_ia32_fixupimmss_maskz:
2024 case X86::BI__builtin_ia32_rangepd512_mask:
2025 case X86::BI__builtin_ia32_rangeps512_mask:
2026 case X86::BI__builtin_ia32_rangesd128_round_mask:
2027 case X86::BI__builtin_ia32_rangess128_round_mask:
2028 case X86::BI__builtin_ia32_reducesd_mask:
2029 case X86::BI__builtin_ia32_reducess_mask:
2030 case X86::BI__builtin_ia32_rndscalesd_round_mask:
2031 case X86::BI__builtin_ia32_rndscaless_round_mask:
2034 case X86::BI__builtin_ia32_vcvtsd2si64:
2035 case X86::BI__builtin_ia32_vcvtsd2si32:
2036 case X86::BI__builtin_ia32_vcvtsd2usi32:
2037 case X86::BI__builtin_ia32_vcvtsd2usi64:
2038 case X86::BI__builtin_ia32_vcvtss2si32:
2039 case X86::BI__builtin_ia32_vcvtss2si64:
2040 case X86::BI__builtin_ia32_vcvtss2usi32:
2041 case X86::BI__builtin_ia32_vcvtss2usi64:
2045 case X86::BI__builtin_ia32_cvtsi2sd64:
2046 case X86::BI__builtin_ia32_cvtsi2ss32:
2047 case X86::BI__builtin_ia32_cvtsi2ss64:
2048 case X86::BI__builtin_ia32_cvtusi2sd64:
2049 case X86::BI__builtin_ia32_cvtusi2ss32:
2050 case X86::BI__builtin_ia32_cvtusi2ss64:
2054 case X86::BI__builtin_ia32_cvtdq2ps512_mask:
2055 case X86::BI__builtin_ia32_cvtudq2ps512_mask:
2056 case X86::BI__builtin_ia32_cvtpd2ps512_mask:
2057 case X86::BI__builtin_ia32_cvtpd2qq512_mask:
2058 case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
2059 case X86::BI__builtin_ia32_cvtps2qq512_mask:
2060 case X86::BI__builtin_ia32_cvtps2uqq512_mask:
2061 case X86::BI__builtin_ia32_cvtqq2pd512_mask:
2062 case X86::BI__builtin_ia32_cvtqq2ps512_mask:
2063 case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
2064 case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
2065 case X86::BI__builtin_ia32_sqrtpd512_mask:
2066 case X86::BI__builtin_ia32_sqrtps512_mask:
2070 case X86::BI__builtin_ia32_addpd512_mask:
2071 case X86::BI__builtin_ia32_addps512_mask:
2072 case X86::BI__builtin_ia32_divpd512_mask:
2073 case X86::BI__builtin_ia32_divps512_mask:
2074 case X86::BI__builtin_ia32_mulpd512_mask:
2075 case X86::BI__builtin_ia32_mulps512_mask:
2076 case X86::BI__builtin_ia32_subpd512_mask:
2077 case X86::BI__builtin_ia32_subps512_mask:
2078 case X86::BI__builtin_ia32_addss_round_mask:
2079 case X86::BI__builtin_ia32_addsd_round_mask:
2080 case X86::BI__builtin_ia32_divss_round_mask:
2081 case X86::BI__builtin_ia32_divsd_round_mask:
2082 case X86::BI__builtin_ia32_mulss_round_mask:
2083 case X86::BI__builtin_ia32_mulsd_round_mask:
2084 case X86::BI__builtin_ia32_subss_round_mask:
2085 case X86::BI__builtin_ia32_subsd_round_mask:
2086 case X86::BI__builtin_ia32_scalefpd512_mask:
2087 case X86::BI__builtin_ia32_scalefps512_mask:
2088 case X86::BI__builtin_ia32_scalefsd_round_mask:
2089 case X86::BI__builtin_ia32_scalefss_round_mask:
2090 case X86::BI__builtin_ia32_getmantpd512_mask:
2091 case X86::BI__builtin_ia32_getmantps512_mask:
2092 case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
2093 case X86::BI__builtin_ia32_sqrtsd_round_mask:
2094 case X86::BI__builtin_ia32_sqrtss_round_mask:
2095 case X86::BI__builtin_ia32_vfmaddpd512_mask:
2096 case X86::BI__builtin_ia32_vfmaddpd512_mask3:
2097 case X86::BI__builtin_ia32_vfmaddpd512_maskz:
2098 case X86::BI__builtin_ia32_vfmaddps512_mask:
2099 case X86::BI__builtin_ia32_vfmaddps512_mask3:
2100 case X86::BI__builtin_ia32_vfmaddps512_maskz:
2101 case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
2102 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
2103 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
2104 case X86::BI__builtin_ia32_vfmaddsubps512_mask:
2105 case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
2106 case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
2107 case X86::BI__builtin_ia32_vfmsubpd512_mask3:
2108 case X86::BI__builtin_ia32_vfmsubps512_mask3:
2109 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
2110 case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
2111 case X86::BI__builtin_ia32_vfnmaddpd512_mask:
2112 case X86::BI__builtin_ia32_vfnmaddps512_mask:
2113 case X86::BI__builtin_ia32_vfnmsubpd512_mask:
2114 case X86::BI__builtin_ia32_vfnmsubpd512_mask3:
2115 case X86::BI__builtin_ia32_vfnmsubps512_mask:
2116 case X86::BI__builtin_ia32_vfnmsubps512_mask3:
2117 case X86::BI__builtin_ia32_vfmaddsd3_mask:
2118 case X86::BI__builtin_ia32_vfmaddsd3_maskz:
2119 case X86::BI__builtin_ia32_vfmaddsd3_mask3:
2120 case X86::BI__builtin_ia32_vfmaddss3_mask:
2121 case X86::BI__builtin_ia32_vfmaddss3_maskz:
2122 case X86::BI__builtin_ia32_vfmaddss3_mask3:
2126 case X86::BI__builtin_ia32_getmantsd_round_mask:
2127 case X86::BI__builtin_ia32_getmantss_round_mask:
2133 llvm::APSInt Result;
2141 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2149 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
2152 return Diag(TheCall->
getLocStart(), diag::err_x86_builtin_invalid_rounding)
2157 bool Sema::CheckX86BuiltinGatherScatterScale(
unsigned BuiltinID,
2159 unsigned ArgNum = 0;
2160 switch (BuiltinID) {
2163 case X86::BI__builtin_ia32_gatherpfdpd:
2164 case X86::BI__builtin_ia32_gatherpfdps:
2165 case X86::BI__builtin_ia32_gatherpfqpd:
2166 case X86::BI__builtin_ia32_gatherpfqps:
2167 case X86::BI__builtin_ia32_scatterpfdpd:
2168 case X86::BI__builtin_ia32_scatterpfdps:
2169 case X86::BI__builtin_ia32_scatterpfqpd:
2170 case X86::BI__builtin_ia32_scatterpfqps:
2173 case X86::BI__builtin_ia32_gatherd_pd:
2174 case X86::BI__builtin_ia32_gatherd_pd256:
2175 case X86::BI__builtin_ia32_gatherq_pd:
2176 case X86::BI__builtin_ia32_gatherq_pd256:
2177 case X86::BI__builtin_ia32_gatherd_ps:
2178 case X86::BI__builtin_ia32_gatherd_ps256:
2179 case X86::BI__builtin_ia32_gatherq_ps:
2180 case X86::BI__builtin_ia32_gatherq_ps256:
2181 case X86::BI__builtin_ia32_gatherd_q:
2182 case X86::BI__builtin_ia32_gatherd_q256:
2183 case X86::BI__builtin_ia32_gatherq_q:
2184 case X86::BI__builtin_ia32_gatherq_q256:
2185 case X86::BI__builtin_ia32_gatherd_d:
2186 case X86::BI__builtin_ia32_gatherd_d256:
2187 case X86::BI__builtin_ia32_gatherq_d:
2188 case X86::BI__builtin_ia32_gatherq_d256:
2189 case X86::BI__builtin_ia32_gather3div2df:
2190 case X86::BI__builtin_ia32_gather3div2di:
2191 case X86::BI__builtin_ia32_gather3div4df:
2192 case X86::BI__builtin_ia32_gather3div4di:
2193 case X86::BI__builtin_ia32_gather3div4sf:
2194 case X86::BI__builtin_ia32_gather3div4si:
2195 case X86::BI__builtin_ia32_gather3div8sf:
2196 case X86::BI__builtin_ia32_gather3div8si:
2197 case X86::BI__builtin_ia32_gather3siv2df:
2198 case X86::BI__builtin_ia32_gather3siv2di:
2199 case X86::BI__builtin_ia32_gather3siv4df:
2200 case X86::BI__builtin_ia32_gather3siv4di:
2201 case X86::BI__builtin_ia32_gather3siv4sf:
2202 case X86::BI__builtin_ia32_gather3siv4si:
2203 case X86::BI__builtin_ia32_gather3siv8sf:
2204 case X86::BI__builtin_ia32_gather3siv8si:
2205 case X86::BI__builtin_ia32_gathersiv8df:
2206 case X86::BI__builtin_ia32_gathersiv16sf:
2207 case X86::BI__builtin_ia32_gatherdiv8df:
2208 case X86::BI__builtin_ia32_gatherdiv16sf:
2209 case X86::BI__builtin_ia32_gathersiv8di:
2210 case X86::BI__builtin_ia32_gathersiv16si:
2211 case X86::BI__builtin_ia32_gatherdiv8di:
2212 case X86::BI__builtin_ia32_gatherdiv16si:
2213 case X86::BI__builtin_ia32_scatterdiv2df:
2214 case X86::BI__builtin_ia32_scatterdiv2di:
2215 case X86::BI__builtin_ia32_scatterdiv4df:
2216 case X86::BI__builtin_ia32_scatterdiv4di:
2217 case X86::BI__builtin_ia32_scatterdiv4sf:
2218 case X86::BI__builtin_ia32_scatterdiv4si:
2219 case X86::BI__builtin_ia32_scatterdiv8sf:
2220 case X86::BI__builtin_ia32_scatterdiv8si:
2221 case X86::BI__builtin_ia32_scattersiv2df:
2222 case X86::BI__builtin_ia32_scattersiv2di:
2223 case X86::BI__builtin_ia32_scattersiv4df:
2224 case X86::BI__builtin_ia32_scattersiv4di:
2225 case X86::BI__builtin_ia32_scattersiv4sf:
2226 case X86::BI__builtin_ia32_scattersiv4si:
2227 case X86::BI__builtin_ia32_scattersiv8sf:
2228 case X86::BI__builtin_ia32_scattersiv8si:
2229 case X86::BI__builtin_ia32_scattersiv8df:
2230 case X86::BI__builtin_ia32_scattersiv16sf:
2231 case X86::BI__builtin_ia32_scatterdiv8df:
2232 case X86::BI__builtin_ia32_scatterdiv16sf:
2233 case X86::BI__builtin_ia32_scattersiv8di:
2234 case X86::BI__builtin_ia32_scattersiv16si:
2235 case X86::BI__builtin_ia32_scatterdiv8di:
2236 case X86::BI__builtin_ia32_scatterdiv16si:
2241 llvm::APSInt Result;
2249 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2252 if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
2255 return Diag(TheCall->
getLocStart(), diag::err_x86_builtin_invalid_scale)
2259 bool Sema::CheckX86BuiltinFunctionCall(
unsigned BuiltinID,
CallExpr *TheCall) {
2260 if (BuiltinID == X86::BI__builtin_cpu_supports)
2263 if (BuiltinID == X86::BI__builtin_cpu_is)
2267 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
2271 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
2276 int i = 0, l = 0, u = 0;
2277 switch (BuiltinID) {
2280 case X86::BI_mm_prefetch:
2281 i = 1; l = 0; u = 7;
2283 case X86::BI__builtin_ia32_sha1rnds4:
2284 case X86::BI__builtin_ia32_shuf_f32x4_256_mask:
2285 case X86::BI__builtin_ia32_shuf_f64x2_256_mask:
2286 case X86::BI__builtin_ia32_shuf_i32x4_256_mask:
2287 case X86::BI__builtin_ia32_shuf_i64x2_256_mask:
2288 i = 2; l = 0; u = 3;
2290 case X86::BI__builtin_ia32_vpermil2pd:
2291 case X86::BI__builtin_ia32_vpermil2pd256:
2292 case X86::BI__builtin_ia32_vpermil2ps:
2293 case X86::BI__builtin_ia32_vpermil2ps256:
2294 i = 3; l = 0; u = 3;
2296 case X86::BI__builtin_ia32_cmpb128_mask:
2297 case X86::BI__builtin_ia32_cmpw128_mask:
2298 case X86::BI__builtin_ia32_cmpd128_mask:
2299 case X86::BI__builtin_ia32_cmpq128_mask:
2300 case X86::BI__builtin_ia32_cmpb256_mask:
2301 case X86::BI__builtin_ia32_cmpw256_mask:
2302 case X86::BI__builtin_ia32_cmpd256_mask:
2303 case X86::BI__builtin_ia32_cmpq256_mask:
2304 case X86::BI__builtin_ia32_cmpb512_mask:
2305 case X86::BI__builtin_ia32_cmpw512_mask:
2306 case X86::BI__builtin_ia32_cmpd512_mask:
2307 case X86::BI__builtin_ia32_cmpq512_mask:
2308 case X86::BI__builtin_ia32_ucmpb128_mask:
2309 case X86::BI__builtin_ia32_ucmpw128_mask:
2310 case X86::BI__builtin_ia32_ucmpd128_mask:
2311 case X86::BI__builtin_ia32_ucmpq128_mask:
2312 case X86::BI__builtin_ia32_ucmpb256_mask:
2313 case X86::BI__builtin_ia32_ucmpw256_mask:
2314 case X86::BI__builtin_ia32_ucmpd256_mask:
2315 case X86::BI__builtin_ia32_ucmpq256_mask:
2316 case X86::BI__builtin_ia32_ucmpb512_mask:
2317 case X86::BI__builtin_ia32_ucmpw512_mask:
2318 case X86::BI__builtin_ia32_ucmpd512_mask:
2319 case X86::BI__builtin_ia32_ucmpq512_mask:
2320 case X86::BI__builtin_ia32_vpcomub:
2321 case X86::BI__builtin_ia32_vpcomuw:
2322 case X86::BI__builtin_ia32_vpcomud:
2323 case X86::BI__builtin_ia32_vpcomuq:
2324 case X86::BI__builtin_ia32_vpcomb:
2325 case X86::BI__builtin_ia32_vpcomw:
2326 case X86::BI__builtin_ia32_vpcomd:
2327 case X86::BI__builtin_ia32_vpcomq:
2328 i = 2; l = 0; u = 7;
2330 case X86::BI__builtin_ia32_roundps:
2331 case X86::BI__builtin_ia32_roundpd:
2332 case X86::BI__builtin_ia32_roundps256:
2333 case X86::BI__builtin_ia32_roundpd256:
2334 i = 1; l = 0; u = 15;
2336 case X86::BI__builtin_ia32_roundss:
2337 case X86::BI__builtin_ia32_roundsd:
2338 case X86::BI__builtin_ia32_rangepd128_mask:
2339 case X86::BI__builtin_ia32_rangepd256_mask:
2340 case X86::BI__builtin_ia32_rangepd512_mask:
2341 case X86::BI__builtin_ia32_rangeps128_mask:
2342 case X86::BI__builtin_ia32_rangeps256_mask:
2343 case X86::BI__builtin_ia32_rangeps512_mask:
2344 case X86::BI__builtin_ia32_getmantsd_round_mask:
2345 case X86::BI__builtin_ia32_getmantss_round_mask:
2346 i = 2; l = 0; u = 15;
2348 case X86::BI__builtin_ia32_cmpps:
2349 case X86::BI__builtin_ia32_cmpss:
2350 case X86::BI__builtin_ia32_cmppd:
2351 case X86::BI__builtin_ia32_cmpsd:
2352 case X86::BI__builtin_ia32_cmpps256:
2353 case X86::BI__builtin_ia32_cmppd256:
2354 case X86::BI__builtin_ia32_cmpps128_mask:
2355 case X86::BI__builtin_ia32_cmppd128_mask:
2356 case X86::BI__builtin_ia32_cmpps256_mask:
2357 case X86::BI__builtin_ia32_cmppd256_mask:
2358 case X86::BI__builtin_ia32_cmpps512_mask:
2359 case X86::BI__builtin_ia32_cmppd512_mask:
2360 case X86::BI__builtin_ia32_cmpsd_mask:
2361 case X86::BI__builtin_ia32_cmpss_mask:
2362 i = 2; l = 0; u = 31;
2364 case X86::BI__builtin_ia32_xabort:
2365 i = 0; l = -128; u = 255;
2367 case X86::BI__builtin_ia32_pshufw:
2368 case X86::BI__builtin_ia32_aeskeygenassist128:
2369 i = 1; l = -128; u = 255;
2371 case X86::BI__builtin_ia32_vcvtps2ph:
2372 case X86::BI__builtin_ia32_vcvtps2ph_mask:
2373 case X86::BI__builtin_ia32_vcvtps2ph256:
2374 case X86::BI__builtin_ia32_vcvtps2ph256_mask:
2375 case X86::BI__builtin_ia32_vcvtps2ph512_mask:
2376 case X86::BI__builtin_ia32_rndscaleps_128_mask:
2377 case X86::BI__builtin_ia32_rndscalepd_128_mask:
2378 case X86::BI__builtin_ia32_rndscaleps_256_mask:
2379 case X86::BI__builtin_ia32_rndscalepd_256_mask:
2380 case X86::BI__builtin_ia32_rndscaleps_mask:
2381 case X86::BI__builtin_ia32_rndscalepd_mask:
2382 case X86::BI__builtin_ia32_reducepd128_mask:
2383 case X86::BI__builtin_ia32_reducepd256_mask:
2384 case X86::BI__builtin_ia32_reducepd512_mask:
2385 case X86::BI__builtin_ia32_reduceps128_mask:
2386 case X86::BI__builtin_ia32_reduceps256_mask:
2387 case X86::BI__builtin_ia32_reduceps512_mask:
2388 case X86::BI__builtin_ia32_prold512_mask:
2389 case X86::BI__builtin_ia32_prolq512_mask:
2390 case X86::BI__builtin_ia32_prold128_mask:
2391 case X86::BI__builtin_ia32_prold256_mask:
2392 case X86::BI__builtin_ia32_prolq128_mask:
2393 case X86::BI__builtin_ia32_prolq256_mask:
2394 case X86::BI__builtin_ia32_prord128_mask:
2395 case X86::BI__builtin_ia32_prord256_mask:
2396 case X86::BI__builtin_ia32_prorq128_mask:
2397 case X86::BI__builtin_ia32_prorq256_mask:
2398 case X86::BI__builtin_ia32_fpclasspd128_mask:
2399 case X86::BI__builtin_ia32_fpclasspd256_mask:
2400 case X86::BI__builtin_ia32_fpclassps128_mask:
2401 case X86::BI__builtin_ia32_fpclassps256_mask:
2402 case X86::BI__builtin_ia32_fpclassps512_mask:
2403 case X86::BI__builtin_ia32_fpclasspd512_mask:
2404 case X86::BI__builtin_ia32_fpclasssd_mask:
2405 case X86::BI__builtin_ia32_fpclassss_mask:
2406 i = 1; l = 0; u = 255;
2408 case X86::BI__builtin_ia32_palignr:
2409 case X86::BI__builtin_ia32_insertps128:
2410 case X86::BI__builtin_ia32_dpps:
2411 case X86::BI__builtin_ia32_dppd:
2412 case X86::BI__builtin_ia32_dpps256:
2413 case X86::BI__builtin_ia32_mpsadbw128:
2414 case X86::BI__builtin_ia32_mpsadbw256:
2415 case X86::BI__builtin_ia32_pcmpistrm128:
2416 case X86::BI__builtin_ia32_pcmpistri128:
2417 case X86::BI__builtin_ia32_pcmpistria128:
2418 case X86::BI__builtin_ia32_pcmpistric128:
2419 case X86::BI__builtin_ia32_pcmpistrio128:
2420 case X86::BI__builtin_ia32_pcmpistris128:
2421 case X86::BI__builtin_ia32_pcmpistriz128:
2422 case X86::BI__builtin_ia32_pclmulqdq128:
2423 case X86::BI__builtin_ia32_vperm2f128_pd256:
2424 case X86::BI__builtin_ia32_vperm2f128_ps256:
2425 case X86::BI__builtin_ia32_vperm2f128_si256:
2426 case X86::BI__builtin_ia32_permti256:
2427 i = 2; l = -128; u = 255;
2429 case X86::BI__builtin_ia32_palignr128:
2430 case X86::BI__builtin_ia32_palignr256:
2431 case X86::BI__builtin_ia32_palignr512_mask:
2432 case X86::BI__builtin_ia32_vcomisd:
2433 case X86::BI__builtin_ia32_vcomiss:
2434 case X86::BI__builtin_ia32_shuf_f32x4_mask:
2435 case X86::BI__builtin_ia32_shuf_f64x2_mask:
2436 case X86::BI__builtin_ia32_shuf_i32x4_mask:
2437 case X86::BI__builtin_ia32_shuf_i64x2_mask:
2438 case X86::BI__builtin_ia32_dbpsadbw128_mask:
2439 case X86::BI__builtin_ia32_dbpsadbw256_mask:
2440 case X86::BI__builtin_ia32_dbpsadbw512_mask:
2441 i = 2; l = 0; u = 255;
2443 case X86::BI__builtin_ia32_fixupimmpd512_mask:
2444 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2445 case X86::BI__builtin_ia32_fixupimmps512_mask:
2446 case X86::BI__builtin_ia32_fixupimmps512_maskz:
2447 case X86::BI__builtin_ia32_fixupimmsd_mask:
2448 case X86::BI__builtin_ia32_fixupimmsd_maskz:
2449 case X86::BI__builtin_ia32_fixupimmss_mask:
2450 case X86::BI__builtin_ia32_fixupimmss_maskz:
2451 case X86::BI__builtin_ia32_fixupimmpd128_mask:
2452 case X86::BI__builtin_ia32_fixupimmpd128_maskz:
2453 case X86::BI__builtin_ia32_fixupimmpd256_mask:
2454 case X86::BI__builtin_ia32_fixupimmpd256_maskz:
2455 case X86::BI__builtin_ia32_fixupimmps128_mask:
2456 case X86::BI__builtin_ia32_fixupimmps128_maskz:
2457 case X86::BI__builtin_ia32_fixupimmps256_mask:
2458 case X86::BI__builtin_ia32_fixupimmps256_maskz:
2459 case X86::BI__builtin_ia32_pternlogd512_mask:
2460 case X86::BI__builtin_ia32_pternlogd512_maskz:
2461 case X86::BI__builtin_ia32_pternlogq512_mask:
2462 case X86::BI__builtin_ia32_pternlogq512_maskz:
2463 case X86::BI__builtin_ia32_pternlogd128_mask:
2464 case X86::BI__builtin_ia32_pternlogd128_maskz:
2465 case X86::BI__builtin_ia32_pternlogd256_mask:
2466 case X86::BI__builtin_ia32_pternlogd256_maskz:
2467 case X86::BI__builtin_ia32_pternlogq128_mask:
2468 case X86::BI__builtin_ia32_pternlogq128_maskz:
2469 case X86::BI__builtin_ia32_pternlogq256_mask:
2470 case X86::BI__builtin_ia32_pternlogq256_maskz:
2471 i = 3; l = 0; u = 255;
2473 case X86::BI__builtin_ia32_gatherpfdpd:
2474 case X86::BI__builtin_ia32_gatherpfdps:
2475 case X86::BI__builtin_ia32_gatherpfqpd:
2476 case X86::BI__builtin_ia32_gatherpfqps:
2477 case X86::BI__builtin_ia32_scatterpfdpd:
2478 case X86::BI__builtin_ia32_scatterpfdps:
2479 case X86::BI__builtin_ia32_scatterpfqpd:
2480 case X86::BI__builtin_ia32_scatterpfqps:
2481 i = 4; l = 2; u = 3;
2483 case X86::BI__builtin_ia32_pcmpestrm128:
2484 case X86::BI__builtin_ia32_pcmpestri128:
2485 case X86::BI__builtin_ia32_pcmpestria128:
2486 case X86::BI__builtin_ia32_pcmpestric128:
2487 case X86::BI__builtin_ia32_pcmpestrio128:
2488 case X86::BI__builtin_ia32_pcmpestris128:
2489 case X86::BI__builtin_ia32_pcmpestriz128:
2490 i = 4; l = -128; u = 255;
2492 case X86::BI__builtin_ia32_rndscalesd_round_mask:
2493 case X86::BI__builtin_ia32_rndscaless_round_mask:
2494 i = 4; l = 0; u = 255;
2497 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
2504 bool Sema::getFormatStringInfo(
const FormatAttr *Format,
bool IsCXXMember,
2505 FormatStringInfo *FSI) {
2506 FSI->HasVAListArg = Format->getFirstArg() == 0;
2507 FSI->FormatIdx = Format->getFormatIdx() - 1;
2508 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
2514 if(FSI->FormatIdx == 0)
2517 if (FSI->FirstDataArg != 0)
2518 --FSI->FirstDataArg;
2528 if (
auto nullability
2537 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2539 dyn_cast<CompoundLiteralExpr>(Expr))
2541 dyn_cast<InitListExpr>(CLE->getInitializer()))
2542 Expr = ILE->getInit(0);
2552 const Expr *ArgExpr,
2560 FormatStringInfo FSI;
2561 if ((GetFormatStringType(Format) == FST_NSString) &&
2562 getFormatStringInfo(Format,
false, &FSI)) {
2563 Idx = FSI.FormatIdx;
2577 bool Format =
false;
2590 if (!Format || NumArgs <= Idx)
2592 const Expr *FormatExpr = Args[Idx];
2593 if (
const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
2594 FormatExpr = CSCE->getSubExpr();
2604 S.
Diag(FormatExpr->
getExprLoc(), diag::warn_objc_cdirective_format_string)
2622 ArrayRef<const Expr *> Args,
2624 assert((FDecl || Proto) &&
"Need a function declaration or prototype");
2627 llvm::SmallBitVector NonNullArgs;
2633 for (
const auto *Arg : Args)
2639 for (
unsigned Val :
NonNull->args()) {
2640 if (Val >= Args.size())
2642 if (NonNullArgs.empty())
2643 NonNullArgs.resize(Args.size());
2644 NonNullArgs.set(Val);
2649 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
2652 ArrayRef<ParmVarDecl*> parms;
2653 if (
const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
2654 parms = FD->parameters();
2656 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
2658 unsigned ParamIndex = 0;
2659 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
2660 I != E; ++I, ++ParamIndex) {
2662 if (PVD->
hasAttr<NonNullAttr>() ||
2664 if (NonNullArgs.empty())
2665 NonNullArgs.resize(Args.size());
2667 NonNullArgs.set(ParamIndex);
2674 if (
const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
2693 if (NonNullArgs.empty())
2694 NonNullArgs.resize(Args.size());
2696 NonNullArgs.set(Index);
2705 for (
unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
2706 ArgIndex != ArgIndexEnd; ++ArgIndex) {
2707 if (NonNullArgs[ArgIndex])
2716 const Expr *ThisArg, ArrayRef<const Expr *> Args,
2720 if (CurContext->isDependentContext())
2724 llvm::SmallBitVector CheckedVarArgs;
2728 CheckedVarArgs.resize(Args.size());
2730 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
2737 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
2738 if (CallType != VariadicDoesNotApply &&
2739 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
2741 : FDecl && isa<FunctionDecl>(FDecl)
2742 ? cast<FunctionDecl>(FDecl)->getNumParams()
2743 : FDecl && isa<ObjCMethodDecl>(FDecl)
2744 ? cast<ObjCMethodDecl>(FDecl)->param_size()
2747 for (
unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
2749 if (
const Expr *Arg = Args[ArgIdx]) {
2750 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
2751 checkVariadicArgument(Arg, CallType);
2756 if (FDecl || Proto) {
2761 for (
const auto *I : FDecl->
specific_attrs<ArgumentWithTypeTagAttr>())
2762 CheckArgumentWithTypeTag(I, Args, Loc);
2767 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
2773 ArrayRef<const Expr *> Args,
2776 VariadicCallType CallType =
2777 Proto->
isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
2778 checkCall(FDecl, Proto,
nullptr, Args,
true,
2786 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
2787 isa<CXXMethodDecl>(FDecl);
2788 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
2789 IsMemberOperatorCall;
2790 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
2795 Expr *ImplicitThis =
nullptr;
2796 if (IsMemberOperatorCall) {
2800 ImplicitThis = Args[0];
2803 }
else if (IsMemberFunction)
2805 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
2807 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
2817 CheckAbsoluteValueFunction(TheCall, FDecl);
2818 CheckMaxUnsignedZero(TheCall, FDecl);
2820 if (getLangOpts().ObjC1)
2828 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
2829 CheckStrlcpycatArguments(TheCall, FnInfo);
2830 else if (CMId == Builtin::BIstrncat)
2831 CheckStrncatArguments(TheCall, FnInfo);
2833 CheckMemaccessArguments(TheCall, CMId, FnInfo);
2839 ArrayRef<const Expr *> Args) {
2840 VariadicCallType CallType =
2841 Method->
isVariadic() ? VariadicMethod : VariadicDoesNotApply;
2843 checkCall(Method,
nullptr,
nullptr, Args,
2853 if (
const auto *V = dyn_cast<VarDecl>(NDecl))
2854 Ty = V->getType().getNonReferenceType();
2855 else if (
const auto *F = dyn_cast<FieldDecl>(NDecl))
2856 Ty = F->getType().getNonReferenceType();
2864 VariadicCallType CallType;
2866 CallType = VariadicDoesNotApply;
2868 CallType = VariadicBlock;
2870 CallType = VariadicFunction;
2873 checkCall(NDecl, Proto,
nullptr,
2884 VariadicCallType CallType = getVariadicCallType(
nullptr, Proto,
2886 checkCall(
nullptr, Proto,
nullptr,
2895 if (!llvm::isValidAtomicOrderingCABI(Ordering))
2898 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
2900 case AtomicExpr::AO__c11_atomic_init:
2901 case AtomicExpr::AO__opencl_atomic_init:
2902 llvm_unreachable(
"There is no ordering argument for an init");
2904 case AtomicExpr::AO__c11_atomic_load:
2905 case AtomicExpr::AO__opencl_atomic_load:
2906 case AtomicExpr::AO__atomic_load_n:
2907 case AtomicExpr::AO__atomic_load:
2908 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
2909 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
2911 case AtomicExpr::AO__c11_atomic_store:
2912 case AtomicExpr::AO__opencl_atomic_store:
2913 case AtomicExpr::AO__atomic_store:
2914 case AtomicExpr::AO__atomic_store_n:
2915 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
2916 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
2917 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
2926 CallExpr *TheCall = cast<CallExpr>(TheCallResult.
get());
2961 const unsigned NumForm = GNUCmpXchg + 1;
2962 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
2963 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
2971 static_assert(
sizeof(NumArgs)/
sizeof(NumArgs[0]) == NumForm
2972 &&
sizeof(NumVals)/
sizeof(NumVals[0]) == NumForm,
2973 "need to update code for modified forms");
2974 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
2975 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
2976 AtomicExpr::AO__atomic_load,
2977 "need to update code for modified C11 atomics");
2978 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
2979 Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
2980 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
2981 Op <= AtomicExpr::AO__c11_atomic_fetch_xor) ||
2983 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
2984 Op == AtomicExpr::AO__atomic_store_n ||
2985 Op == AtomicExpr::AO__atomic_exchange_n ||
2986 Op == AtomicExpr::AO__atomic_compare_exchange_n;
2987 bool IsAddSub =
false;
2990 case AtomicExpr::AO__c11_atomic_init:
2991 case AtomicExpr::AO__opencl_atomic_init:
2995 case AtomicExpr::AO__c11_atomic_load:
2996 case AtomicExpr::AO__opencl_atomic_load:
2997 case AtomicExpr::AO__atomic_load_n:
3001 case AtomicExpr::AO__atomic_load:
3005 case AtomicExpr::AO__c11_atomic_store:
3006 case AtomicExpr::AO__opencl_atomic_store:
3007 case AtomicExpr::AO__atomic_store:
3008 case AtomicExpr::AO__atomic_store_n:
3012 case AtomicExpr::AO__c11_atomic_fetch_add:
3013 case AtomicExpr::AO__c11_atomic_fetch_sub:
3014 case AtomicExpr::AO__opencl_atomic_fetch_add:
3015 case AtomicExpr::AO__opencl_atomic_fetch_sub:
3016 case AtomicExpr::AO__opencl_atomic_fetch_min:
3017 case AtomicExpr::AO__opencl_atomic_fetch_max:
3018 case AtomicExpr::AO__atomic_fetch_add:
3019 case AtomicExpr::AO__atomic_fetch_sub:
3020 case AtomicExpr::AO__atomic_add_fetch:
3021 case AtomicExpr::AO__atomic_sub_fetch:
3024 case AtomicExpr::AO__c11_atomic_fetch_and:
3025 case AtomicExpr::AO__c11_atomic_fetch_or:
3026 case AtomicExpr::AO__c11_atomic_fetch_xor:
3027 case AtomicExpr::AO__opencl_atomic_fetch_and:
3028 case AtomicExpr::AO__opencl_atomic_fetch_or:
3029 case AtomicExpr::AO__opencl_atomic_fetch_xor:
3030 case AtomicExpr::AO__atomic_fetch_and:
3031 case AtomicExpr::AO__atomic_fetch_or:
3032 case AtomicExpr::AO__atomic_fetch_xor:
3033 case AtomicExpr::AO__atomic_fetch_nand:
3034 case AtomicExpr::AO__atomic_and_fetch:
3035 case AtomicExpr::AO__atomic_or_fetch:
3036 case AtomicExpr::AO__atomic_xor_fetch:
3037 case AtomicExpr::AO__atomic_nand_fetch:
3041 case AtomicExpr::AO__c11_atomic_exchange:
3042 case AtomicExpr::AO__opencl_atomic_exchange:
3043 case AtomicExpr::AO__atomic_exchange_n:
3047 case AtomicExpr::AO__atomic_exchange:
3051 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
3052 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
3053 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
3054 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
3058 case AtomicExpr::AO__atomic_compare_exchange:
3059 case AtomicExpr::AO__atomic_compare_exchange_n:
3064 unsigned AdjustedNumArgs = NumArgs[Form];
3065 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
3068 if (TheCall->
getNumArgs() < AdjustedNumArgs) {
3069 Diag(TheCall->
getLocEnd(), diag::err_typecheck_call_too_few_args)
3070 << 0 << AdjustedNumArgs << TheCall->
getNumArgs()
3073 }
else if (TheCall->
getNumArgs() > AdjustedNumArgs) {
3075 diag::err_typecheck_call_too_many_args)
3076 << 0 << AdjustedNumArgs << TheCall->
getNumArgs()
3083 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
3087 Ptr = ConvertedPtr.
get();
3090 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3100 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
3106 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
3112 }
else if (Form != Load && Form != LoadCopy) {
3114 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
3121 if (Form == Arithmetic) {
3124 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
3129 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
3135 diag::err_incomplete_type)) {
3141 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
3150 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
3166 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
3177 if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
3179 ResultType = Context.
VoidTy;
3180 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
3181 ResultType = Context.
BoolTy;
3192 for (
unsigned i = 1; i != TheCall->
getNumArgs(); ++i) {
3194 if (i < NumVals[Form] + 1) {
3201 assert(Form != Load);
3202 if (Form == Init || (Form == Arithmetic && ValType->
isIntegerType()))
3204 else if (Form == Copy || Form == Xchg)
3206 else if (Form == Arithmetic)
3217 AS = PtrTy->getPointeeType().getAddressSpace();
3249 SubExprs.push_back(Ptr);
3253 SubExprs.push_back(TheCall->
getArg(1));
3256 SubExprs.push_back(TheCall->
getArg(1));
3262 SubExprs.push_back(TheCall->
getArg(2));
3263 SubExprs.push_back(TheCall->
getArg(1));
3267 SubExprs.push_back(TheCall->
getArg(3));
3268 SubExprs.push_back(TheCall->
getArg(1));
3269 SubExprs.push_back(TheCall->
getArg(2));
3272 SubExprs.push_back(TheCall->
getArg(3));
3273 SubExprs.push_back(TheCall->
getArg(1));
3274 SubExprs.push_back(TheCall->
getArg(4));
3275 SubExprs.push_back(TheCall->
getArg(2));
3278 SubExprs.push_back(TheCall->
getArg(4));
3279 SubExprs.push_back(TheCall->
getArg(1));
3280 SubExprs.push_back(TheCall->
getArg(5));
3281 SubExprs.push_back(TheCall->
getArg(2));
3282 SubExprs.push_back(TheCall->
getArg(3));
3286 if (SubExprs.size() >= 2 && Form != Init) {
3287 llvm::APSInt Result(32);
3288 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
3290 Diag(SubExprs[1]->getLocStart(),
3291 diag::warn_atomic_op_has_invalid_memory_order)
3292 << SubExprs[1]->getSourceRange();
3297 llvm::APSInt Result(32);
3298 if (
Scope->isIntegerConstantExpr(Result, Context) &&
3299 !ScopeModel->isValid(Result.getZExtValue())) {
3300 Diag(
Scope->getLocStart(), diag::err_atomic_op_has_invalid_synch_scope)
3301 <<
Scope->getSourceRange();
3303 SubExprs.push_back(
Scope);
3307 SubExprs, ResultType, Op,
3310 if ((Op == AtomicExpr::AO__c11_atomic_load ||
3311 Op == AtomicExpr::AO__c11_atomic_store ||
3312 Op == AtomicExpr::AO__opencl_atomic_load ||
3313 Op == AtomicExpr::AO__opencl_atomic_store ) &&
3316 << ((Op == AtomicExpr::AO__c11_atomic_load ||
3317 Op == AtomicExpr::AO__opencl_atomic_load)
3332 assert(Fn &&
"builtin call without direct callee!");
3356 Sema::SemaBuiltinAtomicOverloaded(
ExprResult TheCallResult) {
3363 Diag(TheCall->
getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3375 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
3378 FirstArg = FirstArgResult.
get();
3379 TheCall->
setArg(0, FirstArg);
3391 Diag(DRE->
getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
3420 #define BUILTIN_ROW(x) \ 3421 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 3422 Builtin::BI##x##_8, Builtin::BI##x##_16 } 3424 static const unsigned BuiltinIndices[][5] = {
3450 case 1: SizeIndex = 0;
break;
3451 case 2: SizeIndex = 1;
break;
3452 case 4: SizeIndex = 2;
break;
3453 case 8: SizeIndex = 3;
break;
3454 case 16: SizeIndex = 4;
break;
3465 unsigned BuiltinID = FDecl->getBuiltinID();
3466 unsigned BuiltinIndex, NumFixed = 1;
3467 bool WarnAboutSemanticsChange =
false;
3468 switch (BuiltinID) {
3469 default: llvm_unreachable(
"Unknown overloaded atomic builtin!");
3470 case Builtin::BI__sync_fetch_and_add:
3471 case Builtin::BI__sync_fetch_and_add_1:
3472 case Builtin::BI__sync_fetch_and_add_2:
3473 case Builtin::BI__sync_fetch_and_add_4:
3474 case Builtin::BI__sync_fetch_and_add_8:
3475 case Builtin::BI__sync_fetch_and_add_16:
3479 case Builtin::BI__sync_fetch_and_sub:
3480 case Builtin::BI__sync_fetch_and_sub_1:
3481 case Builtin::BI__sync_fetch_and_sub_2:
3482 case Builtin::BI__sync_fetch_and_sub_4:
3483 case Builtin::BI__sync_fetch_and_sub_8:
3484 case Builtin::BI__sync_fetch_and_sub_16:
3488 case Builtin::BI__sync_fetch_and_or:
3489 case Builtin::BI__sync_fetch_and_or_1:
3490 case Builtin::BI__sync_fetch_and_or_2:
3491 case Builtin::BI__sync_fetch_and_or_4:
3492 case Builtin::BI__sync_fetch_and_or_8:
3493 case Builtin::BI__sync_fetch_and_or_16:
3497 case Builtin::BI__sync_fetch_and_and:
3498 case Builtin::BI__sync_fetch_and_and_1:
3499 case Builtin::BI__sync_fetch_and_and_2:
3500 case Builtin::BI__sync_fetch_and_and_4:
3501 case Builtin::BI__sync_fetch_and_and_8:
3502 case Builtin::BI__sync_fetch_and_and_16:
3506 case Builtin::BI__sync_fetch_and_xor:
3507 case Builtin::BI__sync_fetch_and_xor_1:
3508 case Builtin::BI__sync_fetch_and_xor_2:
3509 case Builtin::BI__sync_fetch_and_xor_4:
3510 case Builtin::BI__sync_fetch_and_xor_8:
3511 case Builtin::BI__sync_fetch_and_xor_16:
3515 case Builtin::BI__sync_fetch_and_nand:
3516 case Builtin::BI__sync_fetch_and_nand_1:
3517 case Builtin::BI__sync_fetch_and_nand_2:
3518 case Builtin::BI__sync_fetch_and_nand_4:
3519 case Builtin::BI__sync_fetch_and_nand_8:
3520 case Builtin::BI__sync_fetch_and_nand_16:
3522 WarnAboutSemanticsChange =
true;
3525 case Builtin::BI__sync_add_and_fetch:
3526 case Builtin::BI__sync_add_and_fetch_1:
3527 case Builtin::BI__sync_add_and_fetch_2:
3528 case Builtin::BI__sync_add_and_fetch_4:
3529 case Builtin::BI__sync_add_and_fetch_8:
3530 case Builtin::BI__sync_add_and_fetch_16:
3534 case Builtin::BI__sync_sub_and_fetch:
3535 case Builtin::BI__sync_sub_and_fetch_1:
3536 case Builtin::BI__sync_sub_and_fetch_2:
3537 case Builtin::BI__sync_sub_and_fetch_4:
3538 case Builtin::BI__sync_sub_and_fetch_8:
3539 case Builtin::BI__sync_sub_and_fetch_16:
3543 case Builtin::BI__sync_and_and_fetch:
3544 case Builtin::BI__sync_and_and_fetch_1:
3545 case Builtin::BI__sync_and_and_fetch_2:
3546 case Builtin::BI__sync_and_and_fetch_4:
3547 case Builtin::BI__sync_and_and_fetch_8:
3548 case Builtin::BI__sync_and_and_fetch_16:
3552 case Builtin::BI__sync_or_and_fetch:
3553 case Builtin::BI__sync_or_and_fetch_1:
3554 case Builtin::BI__sync_or_and_fetch_2:
3555 case Builtin::BI__sync_or_and_fetch_4:
3556 case Builtin::BI__sync_or_and_fetch_8:
3557 case Builtin::BI__sync_or_and_fetch_16:
3561 case Builtin::BI__sync_xor_and_fetch:
3562 case Builtin::BI__sync_xor_and_fetch_1:
3563 case Builtin::BI__sync_xor_and_fetch_2:
3564 case Builtin::BI__sync_xor_and_fetch_4:
3565 case Builtin::BI__sync_xor_and_fetch_8:
3566 case Builtin::BI__sync_xor_and_fetch_16:
3570 case Builtin::BI__sync_nand_and_fetch:
3571 case Builtin::BI__sync_nand_and_fetch_1:
3572 case Builtin::BI__sync_nand_and_fetch_2:
3573 case Builtin::BI__sync_nand_and_fetch_4:
3574 case Builtin::BI__sync_nand_and_fetch_8:
3575 case Builtin::BI__sync_nand_and_fetch_16:
3577 WarnAboutSemanticsChange =
true;
3580 case Builtin::BI__sync_val_compare_and_swap:
3581 case Builtin::BI__sync_val_compare_and_swap_1:
3582 case Builtin::BI__sync_val_compare_and_swap_2:
3583 case Builtin::BI__sync_val_compare_and_swap_4:
3584 case Builtin::BI__sync_val_compare_and_swap_8:
3585 case Builtin::BI__sync_val_compare_and_swap_16:
3590 case Builtin::BI__sync_bool_compare_and_swap:
3591 case Builtin::BI__sync_bool_compare_and_swap_1:
3592 case Builtin::BI__sync_bool_compare_and_swap_2:
3593 case Builtin::BI__sync_bool_compare_and_swap_4:
3594 case Builtin::BI__sync_bool_compare_and_swap_8:
3595 case Builtin::BI__sync_bool_compare_and_swap_16:
3598 ResultType = Context.
BoolTy;
3601 case Builtin::BI__sync_lock_test_and_set:
3602 case Builtin::BI__sync_lock_test_and_set_1:
3603 case Builtin::BI__sync_lock_test_and_set_2:
3604 case Builtin::BI__sync_lock_test_and_set_4:
3605 case Builtin::BI__sync_lock_test_and_set_8:
3606 case Builtin::BI__sync_lock_test_and_set_16:
3610 case Builtin::BI__sync_lock_release:
3611 case Builtin::BI__sync_lock_release_1:
3612 case Builtin::BI__sync_lock_release_2:
3613 case Builtin::BI__sync_lock_release_4:
3614 case Builtin::BI__sync_lock_release_8:
3615 case Builtin::BI__sync_lock_release_16:
3618 ResultType = Context.
VoidTy;
3621 case Builtin::BI__sync_swap:
3622 case Builtin::BI__sync_swap_1:
3623 case Builtin::BI__sync_swap_2:
3624 case Builtin::BI__sync_swap_4:
3625 case Builtin::BI__sync_swap_8:
3626 case Builtin::BI__sync_swap_16:
3634 Diag(TheCall->
getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3640 if (WarnAboutSemanticsChange) {
3641 Diag(TheCall->
getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
3647 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
3650 if (NewBuiltinID == BuiltinID)
3651 NewBuiltinDecl = FDecl;
3656 LookupName(Res, TUScope,
true);
3657 assert(Res.getFoundDecl());
3658 NewBuiltinDecl = dyn_cast<
FunctionDecl>(Res.getFoundDecl());
3659 if (!NewBuiltinDecl)
3666 for (
unsigned i = 0; i != NumFixed; ++i) {
3703 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
3704 CK_BuiltinFnToFnPtr);
3712 return TheCallResult;
3727 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
3728 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
3729 "Unexpected nontemporal load/store builtin!");
3730 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
3731 unsigned numArgs = isStore ? 2 : 1;
3741 Expr *PointerArg = TheCall->
getArg(numArgs - 1);
3743 DefaultFunctionArrayLvalueConversion(PointerArg);
3747 PointerArg = PointerArgResult.
get();
3748 TheCall->
setArg(numArgs - 1, PointerArg);
3752 Diag(DRE->
getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
3765 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
3772 return TheCallResult;
3777 Context, ValType,
false);
3778 ValArg = PerformCopyInitialization(Entity,
SourceLocation(), ValArg);
3784 return TheCallResult;
3791 bool Sema::CheckObjCString(
Expr *Arg) {
3795 if (!Literal || !Literal->
isAscii()) {
3796 Diag(Arg->
getLocStart(), diag::err_cfstring_literal_not_string_constant)
3802 StringRef String = Literal->
getString();
3803 unsigned NumBytes = String.size();
3805 const llvm::UTF8 *FromPtr = (
const llvm::UTF8 *)String.data();
3806 llvm::UTF16 *ToPtr = &ToBuf[0];
3808 llvm::ConversionResult Result =
3809 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
3810 ToPtr + NumBytes, llvm::strictConversion);
3812 if (Result != llvm::conversionOK)
3825 if (
auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
3830 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
3840 Result = PerformCopyInitialization(Entity,
SourceLocation(), Result);
3848 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
3849 bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64;
3850 bool IsWindows = TT.isOSWindows();
3851 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
3852 if (IsX64 || IsAArch64) {
3855 CC = FD->getType()->getAs<
FunctionType>()->getCallConv();
3860 diag::err_ms_va_start_used_in_sysv_function);
3869 diag::err_va_start_used_in_wrong_abi_function)
3884 bool IsVariadic =
false;
3885 ArrayRef<ParmVarDecl *> Params;
3887 if (
auto *Block = dyn_cast<BlockDecl>(Caller)) {
3888 IsVariadic = Block->isVariadic();
3889 Params = Block->parameters();
3890 }
else if (
auto *FD = dyn_cast<FunctionDecl>(Caller)) {
3891 IsVariadic = FD->isVariadic();
3892 Params = FD->parameters();
3893 }
else if (
auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
3894 IsVariadic = MD->isVariadic();
3896 Params = MD->parameters();
3897 }
else if (isa<CapturedDecl>(Caller)) {
3913 *LastParam = Params.empty() ? nullptr : Params.back();
3921 bool Sema::SemaBuiltinVAStart(
unsigned BuiltinID,
CallExpr *TheCall) {
3929 diag::err_typecheck_call_too_many_args)
3933 (*(TheCall->
arg_end()-1))->getLocEnd());
3939 diag::err_typecheck_call_too_few_args_at_least)
3954 bool SecondArgIsLastNamedArgument =
false;
3961 bool IsCRegister =
false;
3963 if (
const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
3964 if (
const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
3965 SecondArgIsLastNamedArgument = PV == LastParam;
3967 Type = PV->getType();
3968 ParamLoc = PV->getLocation();
3970 PV->getStorageClass() ==
SC_Register && !getLangOpts().CPlusPlus;
3974 if (!SecondArgIsLastNamedArgument)
3976 diag::warn_second_arg_of_va_start_not_last_named_param);
3989 unsigned Reason = 0;
3991 else if (IsCRegister) Reason = 2;
3992 Diag(Arg->
getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
3993 Diag(ParamLoc, diag::note_parameter_type) << Type;
4000 bool Sema::SemaBuiltinVAStartARMMicrosoft(
CallExpr *Call) {
4008 diag::err_typecheck_call_too_few_args_at_least)
4032 << Arg1->
getType() << ConstCharPtrTy
4036 << 2 << Arg1->
getType() << ConstCharPtrTy;
4045 << 3 << Arg2->
getType() << SizeTy;
4052 bool Sema::SemaBuiltinUnorderedCompare(
CallExpr *TheCall) {
4054 return Diag(TheCall->
getLocEnd(), diag::err_typecheck_call_too_few_args)
4058 diag::err_typecheck_call_too_many_args)
4061 (*(TheCall->
arg_end()-1))->getLocEnd());
4068 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1,
false);
4069 if (OrigArg0.isInvalid() || OrigArg1.
isInvalid())
4075 TheCall->
setArg(0, OrigArg0.get());
4078 if (OrigArg0.get()->isTypeDependent() || OrigArg1.
get()->isTypeDependent())
4084 return Diag(OrigArg0.get()->getLocStart(),
4085 diag::err_typecheck_call_invalid_ordered_compare)
4086 << OrigArg0.get()->getType() << OrigArg1.
get()->getType()
4087 <<
SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.
get()->getLocEnd());
4096 bool Sema::SemaBuiltinFPClassification(
CallExpr *TheCall,
unsigned NumArgs) {
4098 return Diag(TheCall->
getLocEnd(), diag::err_typecheck_call_too_few_args)
4102 diag::err_typecheck_call_too_many_args)
4105 (*(TheCall->
arg_end()-1))->getLocEnd());
4109 if (OrigArg->isTypeDependent())
4113 if (!OrigArg->getType()->isRealFloatingType())
4114 return Diag(OrigArg->getLocStart(),
4115 diag::err_typecheck_call_invalid_unary_fp)
4116 << OrigArg->getType() << OrigArg->getSourceRange();
4121 if (Cast->getCastKind() == CK_FloatingCast) {
4122 Expr *CastArg = Cast->getSubExpr();
4124 assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
4125 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) &&
4126 "promotion from float to either float or double is the only expected cast here");
4127 Cast->setSubExpr(
nullptr);
4128 TheCall->
setArg(NumArgs-1, CastArg);
4143 bool Sema::SemaBuiltinVSX(
CallExpr *TheCall) {
4144 unsigned ExpectedNumArgs = 3;
4147 diag::err_typecheck_call_too_few_args_at_least)
4148 << 0 << ExpectedNumArgs << TheCall->
getNumArgs()
4153 diag::err_typecheck_call_too_many_args_at_most)
4154 << 0 << ExpectedNumArgs << TheCall->
getNumArgs()
4161 diag::err_vsx_builtin_nonconstant_argument)
4171 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
4173 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
4181 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
4200 diag::err_typecheck_call_too_few_args_at_least)
4208 unsigned numElements = 0;
4217 diag::err_vec_builtin_non_vector)
4223 unsigned numResElements = TheCall->
getNumArgs() - 2;
4232 diag::err_vec_builtin_incompatible_vector)
4238 diag::err_vec_builtin_incompatible_vector)
4242 }
else if (numElements != numResElements) {
4249 for (
unsigned i = 2; i < TheCall->
getNumArgs(); i++) {
4254 llvm::APSInt Result(32);
4257 diag::err_shufflevector_nonconstant_argument)
4261 if (Result.isSigned() && Result.isAllOnesValue())
4264 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
4266 diag::err_shufflevector_argument_too_large)
4272 for (
unsigned i = 0, e = TheCall->
getNumArgs(); i != e; i++) {
4273 exprs.push_back(TheCall->
getArg(i));
4274 TheCall->
setArg(i,
nullptr);
4293 diag::err_convertvector_non_vector)
4297 diag::err_convertvector_non_vector_type));
4302 if (SrcElts != DstElts)
4304 diag::err_convertvector_incompatible_vector)
4308 return new (Context)
4315 bool Sema::SemaBuiltinPrefetch(
CallExpr *TheCall) {
4320 diag::err_typecheck_call_too_many_args_at_most)
4321 << 0 << 3 << NumArgs
4326 for (
unsigned i = 1; i != NumArgs; ++i)
4327 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
4336 bool Sema::SemaBuiltinAssume(
CallExpr *TheCall) {
4351 bool Sema::SemaBuiltinAllocaWithAlign(
CallExpr *TheCall) {
4357 if (
const auto *UE =
4365 if (!Result.isPowerOf2())
4367 diag::err_alignment_not_power_of_two)
4386 bool Sema::SemaBuiltinAssumeAligned(
CallExpr *TheCall) {
4391 diag::err_typecheck_call_too_many_args_at_most)
4392 << 0 << 3 << NumArgs
4400 llvm::APSInt Result;
4401 if (SemaBuiltinConstantArg(TheCall, 1, Result))
4404 if (!Result.isPowerOf2())
4406 diag::err_alignment_not_power_of_two)
4415 if (Arg.isInvalid())
return true;
4416 TheCall->
setArg(2, Arg.get());
4422 bool Sema::SemaBuiltinOSLogFormat(
CallExpr *TheCall) {
4423 unsigned BuiltinID =
4424 cast<FunctionDecl>(TheCall->
getCalleeDecl())->getBuiltinID();
4425 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
4428 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
4429 if (NumArgs < NumRequiredArgs) {
4430 return Diag(TheCall->
getLocEnd(), diag::err_typecheck_call_too_few_args)
4431 << 0 << NumRequiredArgs << NumArgs
4434 if (NumArgs >= NumRequiredArgs + 0x100) {
4436 diag::err_typecheck_call_too_many_args_at_most)
4437 << 0 << (NumRequiredArgs + 0xff) << NumArgs
4448 if (Arg.isInvalid())
4450 TheCall->
setArg(i, Arg.get());
4455 unsigned FormatIdx = i;
4465 unsigned FirstDataArg = i;
4466 while (i < NumArgs) {
4467 ExprResult Arg = DefaultVariadicArgumentPromotion(
4468 TheCall->
getArg(i), VariadicFunction,
nullptr);
4473 return Diag(Arg.
get()->getLocEnd(), diag::err_os_log_argument_too_big)
4484 llvm::SmallBitVector CheckedVarArgs(NumArgs,
false);
4486 bool Success = CheckFormatArguments(
4487 Args,
false, FormatIdx, FirstDataArg, FST_OSLog,
4504 bool Sema::SemaBuiltinConstantArg(
CallExpr *TheCall,
int ArgNum,
4505 llvm::APSInt &Result) {
4513 return Diag(TheCall->
getLocStart(), diag::err_constant_integer_arg_type)
4521 bool Sema::SemaBuiltinConstantArgRange(
CallExpr *TheCall,
int ArgNum,
4522 int Low,
int High) {
4523 llvm::APSInt Result;
4531 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4534 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
4543 bool Sema::SemaBuiltinConstantArgMultiple(
CallExpr *TheCall,
int ArgNum,
4545 llvm::APSInt Result;
4553 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4556 if (Result.getSExtValue() % Num != 0)
4565 bool Sema::SemaBuiltinARMSpecialReg(
unsigned BuiltinID,
CallExpr *TheCall,
4566 int ArgNum,
unsigned ExpectedFieldNum,
4568 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
4569 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
4570 BuiltinID == ARM::BI__builtin_arm_rsr ||
4571 BuiltinID == ARM::BI__builtin_arm_rsrp ||
4572 BuiltinID == ARM::BI__builtin_arm_wsr ||
4573 BuiltinID == ARM::BI__builtin_arm_wsrp;
4574 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
4575 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
4576 BuiltinID == AArch64::BI__builtin_arm_rsr ||
4577 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
4578 BuiltinID == AArch64::BI__builtin_arm_wsr ||
4579 BuiltinID == AArch64::BI__builtin_arm_wsrp;
4580 assert((IsARMBuiltin || IsAArch64Builtin) &&
"Unexpected ARM builtin.");
4589 return Diag(TheCall->
getLocStart(), diag::err_expr_not_string_literal)
4595 Reg.split(Fields,
":");
4597 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
4605 if (Fields.size() > 1) {
4606 bool FiveFields = Fields.size() == 5;
4608 bool ValidString =
true;
4610 ValidString &= Fields[0].startswith_lower(
"cp") ||
4611 Fields[0].startswith_lower(
"p");
4614 Fields[0].drop_front(Fields[0].startswith_lower(
"cp") ? 2 : 1);
4616 ValidString &= Fields[2].startswith_lower(
"c");
4618 Fields[2] = Fields[2].drop_front(1);
4621 ValidString &= Fields[3].startswith_lower(
"c");
4623 Fields[3] = Fields[3].drop_front(1);
4629 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
4631 Ranges.append({15, 7, 15});
4633 for (
unsigned i=0; i<Fields.size(); ++i) {
4635 ValidString &= !Fields[i].getAsInteger(10, IntField);
4636 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
4642 }
else if (IsAArch64Builtin && Fields.size() == 1) {
4652 std::string RegLower = Reg.lower();
4653 if (RegLower !=
"spsel" && RegLower !=
"daifset" && RegLower !=
"daifclr" &&
4654 RegLower !=
"pan" && RegLower !=
"uao")
4657 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
4666 bool Sema::SemaBuiltinLongjmp(
CallExpr *TheCall) {
4668 return Diag(TheCall->
getLocStart(), diag::err_builtin_longjmp_unsupported)
4672 llvm::APSInt Result;
4675 if (SemaBuiltinConstantArg(TheCall, 1, Result))
4679 return Diag(TheCall->
getLocStart(), diag::err_builtin_longjmp_invalid_val)
4687 bool Sema::SemaBuiltinSetjmp(
CallExpr *TheCall) {
4689 return Diag(TheCall->
getLocStart(), diag::err_builtin_setjmp_unsupported)
4696 class UncoveredArgHandler {
4697 enum { Unknown = -1, AllCovered = -2 };
4699 signed FirstUncoveredArg = Unknown;
4703 UncoveredArgHandler() =
default;
4705 bool hasUncoveredArg()
const {
4706 return (FirstUncoveredArg >= 0);
4709 unsigned getUncoveredArg()
const {
4710 assert(hasUncoveredArg() &&
"no uncovered argument");
4711 return FirstUncoveredArg;
4714 void setAllCovered() {
4717 DiagnosticExprs.clear();
4718 FirstUncoveredArg = AllCovered;
4721 void Update(
signed NewFirstUncoveredArg,
const Expr *StrExpr) {
4722 assert(NewFirstUncoveredArg >= 0 &&
"Outside range");
4725 if (FirstUncoveredArg == AllCovered)
4730 if (NewFirstUncoveredArg == FirstUncoveredArg)
4731 DiagnosticExprs.push_back(StrExpr);
4732 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
4733 DiagnosticExprs.clear();
4734 DiagnosticExprs.push_back(StrExpr);
4735 FirstUncoveredArg = NewFirstUncoveredArg;
4739 void Diagnose(
Sema &S,
bool IsFunctionCall,
const Expr *ArgExpr);
4744 SLCT_UncheckedLiteral,
4752 bool AddendIsRight) {
4753 unsigned BitWidth = Offset.getBitWidth();
4754 unsigned AddendBitWidth = Addend.getBitWidth();
4756 if (Addend.isUnsigned()) {
4757 Addend = Addend.zext(++AddendBitWidth);
4758 Addend.setIsSigned(
true);
4761 if (AddendBitWidth > BitWidth) {
4762 Offset = Offset.sext(AddendBitWidth);
4763 BitWidth = AddendBitWidth;
4764 }
else if (BitWidth > AddendBitWidth) {
4765 Addend = Addend.sext(BitWidth);
4769 llvm::APSInt ResOffset =
Offset;
4770 if (BinOpKind == BO_Add)
4771 ResOffset = Offset.sadd_ov(Addend, Ov);
4773 assert(AddendIsRight && BinOpKind == BO_Sub &&
4774 "operator must be add or sub with addend on the right");
4775 ResOffset = Offset.ssub_ov(Addend, Ov);
4782 "index (intermediate) result too big");
4783 Offset = Offset.sext(2 * BitWidth);
4784 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
4796 class FormatStringLiteral {
4801 FormatStringLiteral(
const StringLiteral *fexpr, int64_t Offset = 0)
4802 : FExpr(fexpr),
Offset(Offset) {}
4804 StringRef getString()
const {
4805 return FExpr->
getString().drop_front(Offset);
4808 unsigned getByteLength()
const {
4819 bool isAscii()
const {
return FExpr->
isAscii(); }
4820 bool isWide()
const {
return FExpr->
isWide(); }
4821 bool isUTF8()
const {
return FExpr->
isUTF8(); }
4822 bool isUTF16()
const {
return FExpr->
isUTF16(); }
4823 bool isUTF32()
const {
return FExpr->
isUTF32(); }
4824 bool isPascal()
const {
return FExpr->
isPascal(); }
4828 const TargetInfo &Target,
unsigned *StartToken =
nullptr,
4829 unsigned *StartTokenByteOffset =
nullptr)
const {
4831 StartToken, StartTokenByteOffset);
4844 const Expr *OrigFormatExpr,
4845 ArrayRef<const Expr *> Args,
4846 bool HasVAListArg,
unsigned format_idx,
4847 unsigned firstDataArg,
4849 bool inFunctionCall,
4851 llvm::SmallBitVector &CheckedVarArgs,
4852 UncoveredArgHandler &UncoveredArg);
4860 bool HasVAListArg,
unsigned format_idx,
4863 llvm::SmallBitVector &CheckedVarArgs,
4864 UncoveredArgHandler &UncoveredArg,
4867 assert(Offset.isSigned() &&
"invalid offset");
4870 return SLCT_NotALiteral;
4879 return SLCT_UncheckedLiteral;
4882 case Stmt::BinaryConditionalOperatorClass:
4883 case Stmt::ConditionalOperatorClass: {
4887 cast<AbstractConditionalOperator>(E);
4892 bool CheckLeft =
true, CheckRight =
true;
4908 Left = SLCT_UncheckedLiteral;
4911 HasVAListArg, format_idx, firstDataArg,
4912 Type, CallType, InFunctionCall,
4913 CheckedVarArgs, UncoveredArg,
Offset);
4914 if (Left == SLCT_NotALiteral || !CheckRight) {
4921 HasVAListArg, format_idx, firstDataArg,
4922 Type, CallType, InFunctionCall, CheckedVarArgs,
4925 return (CheckLeft && Left < Right) ? Left : Right;
4928 case Stmt::ImplicitCastExprClass:
4929 E = cast<ImplicitCastExpr>(E)->getSubExpr();
4932 case Stmt::OpaqueValueExprClass:
4933 if (
const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
4937 return SLCT_NotALiteral;
4939 case Stmt::PredefinedExprClass:
4943 return SLCT_UncheckedLiteral;
4945 case Stmt::DeclRefExprClass: {
4951 bool isConstant =
false;
4955 isConstant = AT->getElementType().isConstant(S.
Context);
4958 PT->getPointeeType().isConstant(S.
Context);
4966 if (
const Expr *Init = VD->getAnyInitializer()) {
4968 if (
const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4969 if (InitList->isStringLiteralInit())
4970 Init = InitList->getInit(0)->IgnoreParenImpCasts();
4973 HasVAListArg, format_idx,
4974 firstDataArg, Type, CallType,
4975 false, CheckedVarArgs,
4976 UncoveredArg, Offset);
4995 if (
const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
4996 if (
const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
4997 int PVIndex = PV->getFunctionScopeIndex() + 1;
4998 for (
const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
5001 if (MD->isInstance())
5005 if (PVIndex == PVFormat->getFormatIdx() &&
5007 return SLCT_UncheckedLiteral;
5014 return SLCT_NotALiteral;
5017 case Stmt::CallExprClass:
5018 case Stmt::CXXMemberCallExprClass: {
5019 const CallExpr *CE = cast<CallExpr>(E);
5021 if (
const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
5022 unsigned ArgIndex = FA->getFormatIdx();
5024 if (MD->isInstance())
5029 HasVAListArg, format_idx, firstDataArg,
5030 Type, CallType, InFunctionCall,
5031 CheckedVarArgs, UncoveredArg, Offset);
5032 }
else if (
const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
5033 unsigned BuiltinID = FD->getBuiltinID();
5034 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
5035 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
5038 HasVAListArg, format_idx,
5039 firstDataArg, Type, CallType,
5040 InFunctionCall, CheckedVarArgs,
5041 UncoveredArg, Offset);
5046 return SLCT_NotALiteral;
5048 case Stmt::ObjCMessageExprClass: {
5049 const auto *ME = cast<ObjCMessageExpr>(E);
5050 if (
const auto *ND = ME->getMethodDecl()) {
5051 if (
const auto *FA = ND->getAttr<FormatArgAttr>()) {
5052 unsigned ArgIndex = FA->getFormatIdx();
5053 const Expr *Arg = ME->getArg(ArgIndex - 1);
5055 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
5056 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
5060 return SLCT_NotALiteral;
5062 case Stmt::ObjCStringLiteralClass:
5063 case Stmt::StringLiteralClass: {
5069 StrE = cast<StringLiteral>(E);
5072 if (Offset.isNegative() || Offset > StrE->
getLength()) {
5075 return SLCT_NotALiteral;
5077 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
5079 firstDataArg, Type, InFunctionCall, CallType,
5080 CheckedVarArgs, UncoveredArg);
5081 return SLCT_CheckedLiteral;
5084 return SLCT_NotALiteral;
5086 case Stmt::BinaryOperatorClass: {
5087 llvm::APSInt LResult;
5088 llvm::APSInt RResult;
5097 if (LIsInt != RIsInt) {
5101 if (BinOpKind == BO_Add) {
5102 sumOffsets(Offset, LResult, BinOpKind, RIsInt);
5107 sumOffsets(Offset, RResult, BinOpKind, RIsInt);
5114 return SLCT_NotALiteral;
5116 case Stmt::UnaryOperatorClass: {
5119 if (UnaOp->
getOpcode() == UO_AddrOf && ASE) {
5120 llvm::APSInt IndexResult;
5121 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.
Context)) {
5122 sumOffsets(Offset, IndexResult, BO_Add,
true);
5128 return SLCT_NotALiteral;
5132 return SLCT_NotALiteral;
5137 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
5138 .Case(
"scanf", FST_Scanf)
5139 .Cases(
"printf",
"printf0", FST_Printf)
5140 .Cases(
"NSString",
"CFString", FST_NSString)
5141 .Case(
"strftime", FST_Strftime)
5142 .Case(
"strfmon", FST_Strfmon)
5143 .Cases(
"kprintf",
"cmn_err",
"vcmn_err",
"zcmn_err", FST_Kprintf)
5144 .Case(
"freebsd_kprintf", FST_FreeBSDKPrintf)
5145 .Case(
"os_trace", FST_OSLog)
5146 .Case(
"os_log", FST_OSLog)
5147 .Default(FST_Unknown);
5153 bool Sema::CheckFormatArguments(
const FormatAttr *Format,
5158 llvm::SmallBitVector &CheckedVarArgs) {
5159 FormatStringInfo FSI;
5160 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
5161 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
5162 FSI.FirstDataArg, GetFormatStringType(Format),
5163 CallType, Loc, Range, CheckedVarArgs);
5168 bool HasVAListArg,
unsigned format_idx,
5172 llvm::SmallBitVector &CheckedVarArgs) {
5174 if (format_idx >= Args.size()) {
5175 Diag(Loc, diag::warn_missing_format_string) << Range;
5179 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
5193 UncoveredArgHandler UncoveredArg;
5196 format_idx, firstDataArg,
Type, CallType,
5197 true, CheckedVarArgs,
5199 llvm::APSInt(64,
false) = 0);
5202 if (UncoveredArg.hasUncoveredArg()) {
5203 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
5204 assert(ArgIdx < Args.size() &&
"ArgIdx outside bounds");
5205 UncoveredArg.Diagnose(*
this,
true, Args[ArgIdx]);
5208 if (CT != SLCT_NotALiteral)
5210 return CT == SLCT_CheckedLiteral;
5214 if (
Type == FST_Strftime)
5222 if (
Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
5227 if (Args.size() == firstDataArg) {
5228 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
5234 case FST_FreeBSDKPrintf:
5236 Diag(FormatLoc, diag::note_format_security_fixit)
5240 Diag(FormatLoc, diag::note_format_security_fixit)
5245 Diag(FormatLoc, diag::warn_format_nonliteral)
5256 const FormatStringLiteral *FExpr;
5257 const Expr *OrigFormatExpr;
5259 const unsigned FirstDataArg;
5260 const unsigned NumDataArgs;
5262 const bool HasVAListArg;
5265 llvm::SmallBitVector CoveredArgs;
5266 bool usesPositionalArgs =
false;
5267 bool atFirstArg =
true;
5268 bool inFunctionCall;
5270 llvm::SmallBitVector &CheckedVarArgs;
5271 UncoveredArgHandler &UncoveredArg;
5274 CheckFormatHandler(
Sema &s,
const FormatStringLiteral *fexpr,
5275 const Expr *origFormatExpr,
5277 unsigned numDataArgs,
const char *beg,
bool hasVAListArg,
5280 llvm::SmallBitVector &CheckedVarArgs,
5281 UncoveredArgHandler &UncoveredArg)
5282 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
5283 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
5284 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
5285 inFunctionCall(inFunctionCall), CallType(callType),
5286 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
5287 CoveredArgs.resize(numDataArgs);
5288 CoveredArgs.reset();
5291 void DoneProcessing();
5293 void HandleIncompleteSpecifier(
const char *startSpecifier,
5294 unsigned specifierLen)
override;
5296 void HandleInvalidLengthModifier(
5299 const char *startSpecifier,
unsigned specifierLen,
5302 void HandleNonStandardLengthModifier(
5304 const char *startSpecifier,
unsigned specifierLen);
5306 void HandleNonStandardConversionSpecifier(
5308 const char *startSpecifier,
unsigned specifierLen);
5310 void HandlePosition(
const char *startPos,
unsigned posLen)
override;
5312 void HandleInvalidPosition(
const char *startSpecifier,
5313 unsigned specifierLen,
5316 void HandleZeroPosition(
const char *startPos,
unsigned posLen)
override;
5318 void HandleNullChar(
const char *nullCharacter)
override;
5320 template <
typename Range>
5322 EmitFormatDiagnostic(
Sema &S,
bool inFunctionCall,
const Expr *ArgumentExpr,
5324 bool IsStringLocation, Range StringRange,
5328 bool HandleInvalidConversionSpecifier(
unsigned argIndex,
SourceLocation Loc,
5329 const char *startSpec,
5330 unsigned specifierLen,
5331 const char *csStart,
unsigned csLen);
5334 const char *startSpec,
5335 unsigned specifierLen);
5339 unsigned specifierLen);
5342 const Expr *getDataArg(
unsigned i)
const;
5346 const char *startSpecifier,
unsigned specifierLen,
5349 template <
typename Range>
5351 bool IsStringLocation, Range StringRange,
5357 SourceRange CheckFormatHandler::getFormatStringRange() {
5362 getSpecifierRange(
const char *startSpecifier,
unsigned specifierLen) {
5372 SourceLocation CheckFormatHandler::getLocationOfByte(
const char *x) {
5377 void CheckFormatHandler::HandleIncompleteSpecifier(
const char *startSpecifier,
5378 unsigned specifierLen){
5379 EmitFormatDiagnostic(S.
PDiag(diag::warn_printf_incomplete_specifier),
5380 getLocationOfByte(startSpecifier),
5382 getSpecifierRange(startSpecifier, specifierLen));
5385 void CheckFormatHandler::HandleInvalidLengthModifier(
5388 const char *startSpecifier,
unsigned specifierLen,
unsigned DiagID) {
5389 using namespace analyze_format_string;
5392 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5397 EmitFormatDiagnostic(S.
PDiag(DiagID) << LM.toString() << CS.
toString(),
5398 getLocationOfByte(LM.getStart()),
5400 getSpecifierRange(startSpecifier, specifierLen));
5402 S.
Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5403 << FixedLM->toString()
5408 if (DiagID == diag::warn_format_nonsensical_length)
5411 EmitFormatDiagnostic(S.
PDiag(DiagID) << LM.toString() << CS.
toString(),
5412 getLocationOfByte(LM.getStart()),
5414 getSpecifierRange(startSpecifier, specifierLen),
5419 void CheckFormatHandler::HandleNonStandardLengthModifier(
5421 const char *startSpecifier,
unsigned specifierLen) {
5422 using namespace analyze_format_string;
5425 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5430 EmitFormatDiagnostic(S.
PDiag(diag::warn_format_non_standard)
5431 << LM.toString() << 0,
5432 getLocationOfByte(LM.getStart()),
5434 getSpecifierRange(startSpecifier, specifierLen));
5436 S.
Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5437 << FixedLM->toString()
5441 EmitFormatDiagnostic(S.
PDiag(diag::warn_format_non_standard)
5442 << LM.toString() << 0,
5443 getLocationOfByte(LM.getStart()),
5445 getSpecifierRange(startSpecifier, specifierLen));
5449 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
5451 const char *startSpecifier,
unsigned specifierLen) {
5452 using namespace analyze_format_string;
5457 EmitFormatDiagnostic(S.
PDiag(diag::warn_format_non_standard)
5461 getSpecifierRange(startSpecifier, specifierLen));
5464 S.
Diag(getLocationOfByte(CS.
getStart()), diag::note_format_fix_specifier)
5465 << FixedCS->toString()
5468 EmitFormatDiagnostic(S.
PDiag(diag::warn_format_non_standard)
5472 getSpecifierRange(startSpecifier, specifierLen));
5476 void CheckFormatHandler::HandlePosition(
const char *startPos,
5478 EmitFormatDiagnostic(S.
PDiag(diag::warn_format_non_standard_positional_arg),
5479 getLocationOfByte(startPos),
5481 getSpecifierRange(startPos, posLen));
5485 CheckFormatHandler::HandleInvalidPosition(
const char *startPos,
unsigned posLen,
5487 EmitFormatDiagnostic(S.
PDiag(diag::warn_format_invalid_positional_specifier)
5489 getLocationOfByte(startPos),
true,
5490 getSpecifierRange(startPos, posLen));
5493 void CheckFormatHandler::HandleZeroPosition(
const char *startPos,
5495 EmitFormatDiagnostic(S.
PDiag(diag::warn_format_zero_positional_specifier),
5496 getLocationOfByte(startPos),
5498 getSpecifierRange(startPos, posLen));
5501 void CheckFormatHandler::HandleNullChar(
const char *nullCharacter) {
5502 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
5504 EmitFormatDiagnostic(
5505 S.
PDiag(diag::warn_printf_format_string_contains_null_char),
5506 getLocationOfByte(nullCharacter),
true,
5507 getFormatStringRange());
5513 const Expr *CheckFormatHandler::getDataArg(
unsigned i)
const {
5514 return Args[FirstDataArg + i];
5517 void CheckFormatHandler::DoneProcessing() {
5520 if (!HasVAListArg) {
5523 signed notCoveredArg = CoveredArgs.find_first();
5524 if (notCoveredArg >= 0) {
5525 assert((
unsigned)notCoveredArg < NumDataArgs);
5526 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
5528 UncoveredArg.setAllCovered();
5533 void UncoveredArgHandler::Diagnose(
Sema &S,
bool IsFunctionCall,
5534 const Expr *ArgExpr) {
5535 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
5547 for (
auto E : DiagnosticExprs)
5550 CheckFormatHandler::EmitFormatDiagnostic(
5551 S, IsFunctionCall, DiagnosticExprs[0],
5557 CheckFormatHandler::HandleInvalidConversionSpecifier(
unsigned argIndex,
5559 const char *startSpec,
5560 unsigned specifierLen,
5561 const char *csStart,
5563 bool keepGoing =
true;
5564 if (argIndex < NumDataArgs) {
5567 CoveredArgs.set(argIndex);
5583 std::string CodePointStr;
5584 if (!llvm::sys::locale::isPrint(*csStart)) {
5585 llvm::UTF32 CodePoint;
5586 const llvm::UTF8 **B =
reinterpret_cast<const llvm::UTF8 **
>(&csStart);
5587 const llvm::UTF8 *E =
5588 reinterpret_cast<const llvm::UTF8 *
>(csStart + csLen);
5589 llvm::ConversionResult Result =
5590 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
5592 if (Result != llvm::conversionOK) {
5593 unsigned char FirstChar = *csStart;
5594 CodePoint = (llvm::UTF32)FirstChar;
5597 llvm::raw_string_ostream OS(CodePointStr);
5598 if (CodePoint < 256)
5599 OS <<
"\\x" << llvm::format(
"%02x", CodePoint);
5600 else if (CodePoint <= 0xFFFF)
5601 OS <<
"\\u" << llvm::format(
"%04x", CodePoint);
5603 OS <<
"\\U" << llvm::format(
"%08x", CodePoint);
5605 Specifier = CodePointStr;
5608 EmitFormatDiagnostic(
5610 true, getSpecifierRange(startSpec, specifierLen));
5616 CheckFormatHandler::HandlePositionalNonpositionalArgs(
SourceLocation Loc,
5617 const char *startSpec,
5618 unsigned specifierLen) {
5619 EmitFormatDiagnostic(
5620 S.
PDiag(diag::warn_format_mix_positional_nonpositional_args),
5621 Loc,
true, getSpecifierRange(startSpec, specifierLen));
5625 CheckFormatHandler::CheckNumArgs(
5628 const char *startSpecifier,
unsigned specifierLen,
unsigned argIndex) {
5630 if (argIndex >= NumDataArgs) {
5632 ? (S.
PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
5633 << (argIndex+1) << NumDataArgs)
5634 : S.
PDiag(diag::warn_printf_insufficient_data_args);
5635 EmitFormatDiagnostic(
5636 PDiag, getLocationOfByte(CS.
getStart()),
true,
5637 getSpecifierRange(startSpecifier, specifierLen));
5641 UncoveredArg.setAllCovered();
5647 template<
typename Range>
5650 bool IsStringLocation,
5653 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
5654 Loc, IsStringLocation, StringRange, FixIt);
5684 template <
typename Range>
5685 void CheckFormatHandler::EmitFormatDiagnostic(
5686 Sema &S,
bool InFunctionCall,
const Expr *ArgumentExpr,
5689 if (InFunctionCall) {
5694 S.
Diag(IsStringLocation ? ArgumentExpr->
getExprLoc() : Loc, PDiag)
5698 S.
Diag(IsStringLocation ? Loc : StringRange.getBegin(),
5699 diag::note_format_string_defined);
5701 Note << StringRange;
5710 class CheckPrintfHandler :
public CheckFormatHandler {
5712 CheckPrintfHandler(
Sema &s,
const FormatStringLiteral *fexpr,
5713 const Expr *origFormatExpr,
5715 unsigned numDataArgs,
bool isObjC,
const char *beg,
5717 unsigned formatIdx,
bool inFunctionCall,
5719 llvm::SmallBitVector &CheckedVarArgs,
5720 UncoveredArgHandler &UncoveredArg)
5721 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
5722 numDataArgs, beg, hasVAListArg, Args, formatIdx,
5723 inFunctionCall, CallType, CheckedVarArgs,
5729 bool allowsObjCArg()
const {
5734 bool HandleInvalidPrintfConversionSpecifier(
5736 const char *startSpecifier,
5737 unsigned specifierLen)
override;
5740 const char *startSpecifier,
5741 unsigned specifierLen)
override;
5743 const char *StartSpecifier,
5744 unsigned SpecifierLen,
5748 const char *startSpecifier,
unsigned specifierLen);
5752 const char *startSpecifier,
unsigned specifierLen);
5755 const char *startSpecifier,
unsigned specifierLen);
5759 const char *startSpecifier,
unsigned specifierLen);
5763 void HandleEmptyObjCModifierFlag(
const char *startFlag,
5764 unsigned flagLen)
override;
5766 void HandleInvalidObjCModifierFlag(
const char *startFlag,
5767 unsigned flagLen)
override;
5769 void HandleObjCFlagsWithNonObjCConversion(
const char *flagsStart,
5770 const char *flagsEnd,
5771 const char *conversionPosition)
5777 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
5779 const char *startSpecifier,
5780 unsigned specifierLen) {
5784 return HandleInvalidConversionSpecifier(FS.
getArgIndex(),
5786 startSpecifier, specifierLen,
5790 bool CheckPrintfHandler::HandleAmount(
5792 unsigned k,
const char *startSpecifier,
5793 unsigned specifierLen) {
5795 if (!HasVAListArg) {
5797 if (argIndex >= NumDataArgs) {
5798 EmitFormatDiagnostic(S.
PDiag(diag::warn_printf_asterisk_missing_arg)
5802 getSpecifierRange(startSpecifier, specifierLen));
5812 CoveredArgs.set(argIndex);
5813 const Expr *Arg = getDataArg(argIndex);
5823 EmitFormatDiagnostic(S.
PDiag(diag::warn_printf_asterisk_wrong_type)
5828 getSpecifierRange(startSpecifier, specifierLen));
5838 void CheckPrintfHandler::HandleInvalidAmount(
5842 const char *startSpecifier,
5843 unsigned specifierLen) {
5853 EmitFormatDiagnostic(S.
PDiag(diag::warn_printf_nonsensical_optional_amount)
5857 getSpecifierRange(startSpecifier, specifierLen),
5863 const char *startSpecifier,
5864 unsigned specifierLen) {
5868 EmitFormatDiagnostic(S.
PDiag(diag::warn_printf_nonsensical_flag)
5872 getSpecifierRange(startSpecifier, specifierLen),
5877 void CheckPrintfHandler::HandleIgnoredFlag(
5881 const char *startSpecifier,
5882 unsigned specifierLen) {
5884 EmitFormatDiagnostic(S.
PDiag(diag::warn_printf_ignored_flag)
5888 getSpecifierRange(startSpecifier, specifierLen),
5890 getSpecifierRange(ignoredFlag.
getPosition(), 1)));
5893 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(
const char *startFlag,
5896 EmitFormatDiagnostic(S.
PDiag(diag::warn_printf_empty_objc_flag),
5897 getLocationOfByte(startFlag),
5899 getSpecifierRange(startFlag, flagLen));
5902 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(
const char *startFlag,
5905 auto Range = getSpecifierRange(startFlag, flagLen);
5906 StringRef flag(startFlag, flagLen);
5907 EmitFormatDiagnostic(S.
PDiag(diag::warn_printf_invalid_objc_flag) << flag,
5908 getLocationOfByte(startFlag),
5913 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
5914 const char *flagsStart,
const char *flagsEnd,
const char *conversionPosition) {
5916 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
5917 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
5918 EmitFormatDiagnostic(S.
PDiag(diag) << StringRef(conversionPosition, 1),
5919 getLocationOfByte(conversionPosition),
5927 template<
typename MemberKind>
5928 static llvm::SmallPtrSet<MemberKind*, 1>
5931 llvm::SmallPtrSet<MemberKind*, 1> Results;
5948 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
5959 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
5962 CXXRecordMembersNamed<CXXMethodDecl>(
"c_str", *
this, E->
getType());
5963 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5965 if ((*MI)->getMinRequiredArguments() == 0)
5973 bool CheckPrintfHandler::checkForCStrMembers(
5975 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
5978 CXXRecordMembersNamed<CXXMethodDecl>(
"c_str", S, E->
getType());
5980 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
6000 const char *startSpecifier,
6001 unsigned specifierLen) {
6002 using namespace analyze_format_string;
6003 using namespace analyze_printf;
6013 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6014 startSpecifier, specifierLen);
6022 startSpecifier, specifierLen)) {
6027 startSpecifier, specifierLen)) {
6031 if (!CS.consumesDataArgument()) {
6039 if (argIndex < NumDataArgs) {
6043 CoveredArgs.set(argIndex);
6047 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
6048 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
6050 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
6054 CoveredArgs.set(argIndex + 1);
6057 const Expr *Ex = getDataArg(argIndex);
6059 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
6062 EmitFormatDiagnostic(
6063 S.
PDiag(diag::warn_format_conversion_argument_type_mismatch)
6067 getSpecifierRange(startSpecifier, specifierLen));
6070 Ex = getDataArg(argIndex + 1);
6073 EmitFormatDiagnostic(
6074 S.
PDiag(diag::warn_format_conversion_argument_type_mismatch)
6076 <<
false << Ex->getSourceRange(),
6077 Ex->getLocStart(),
false,
6078 getSpecifierRange(startSpecifier, specifierLen));
6085 if (!allowsObjCArg() && CS.isObjCArg()) {
6086 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6091 if (FSType !=
Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
6092 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6097 if (FSType ==
Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
6098 EmitFormatDiagnostic(S.
PDiag(diag::warn_os_log_format_narg),
6099 getLocationOfByte(CS.getStart()),
6101 getSpecifierRange(startSpecifier, specifierLen));
6108 (CS.getKind() == ConversionSpecifier::PArg ||
6109 CS.getKind() == ConversionSpecifier::sArg ||
6110 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
6111 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6118 EmitFormatDiagnostic(S.
PDiag(diag::warn_format_invalid_annotation)
6122 getSpecifierRange(startSpecifier, specifierLen));
6125 EmitFormatDiagnostic(S.
PDiag(diag::warn_format_invalid_annotation)
6129 getSpecifierRange(startSpecifier, specifierLen));
6136 startSpecifier, specifierLen);
6142 startSpecifier, specifierLen);
6146 if (CS.getKind() == ConversionSpecifier::PArg &&
6148 EmitFormatDiagnostic(S.
PDiag(diag::warn_format_P_no_precision),
6149 getLocationOfByte(startSpecifier),
6151 getSpecifierRange(startSpecifier, specifierLen));
6160 HandleFlag(FS, FS.
hasPlusPrefix(), startSpecifier, specifierLen);
6162 HandleFlag(FS, FS.
hasSpacePrefix(), startSpecifier, specifierLen);
6171 startSpecifier, specifierLen);
6174 startSpecifier, specifierLen);
6178 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6179 diag::warn_format_nonsensical_length);
6181 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
6183 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6184 diag::warn_format_non_standard_conversion_spec);
6187 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6193 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
6196 const Expr *Arg = getDataArg(argIndex);
6200 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
6212 case Stmt::ArraySubscriptExprClass:
6213 case Stmt::CallExprClass:
6214 case Stmt::CharacterLiteralClass:
6215 case Stmt::CXXBoolLiteralExprClass:
6216 case Stmt::DeclRefExprClass:
6217 case Stmt::FloatingLiteralClass:
6218 case Stmt::IntegerLiteralClass:
6219 case Stmt::MemberExprClass:
6220 case Stmt::ObjCArrayLiteralClass:
6221 case Stmt::ObjCBoolLiteralExprClass:
6222 case Stmt::ObjCBoxedExprClass:
6223 case Stmt::ObjCDictionaryLiteralClass:
6224 case Stmt::ObjCEncodeExprClass:
6225 case Stmt::ObjCIvarRefExprClass:
6226 case Stmt::ObjCMessageExprClass:
6227 case Stmt::ObjCPropertyRefExprClass:
6228 case Stmt::ObjCStringLiteralClass:
6229 case Stmt::ObjCSubscriptRefExprClass:
6230 case Stmt::ParenExprClass:
6231 case Stmt::StringLiteralClass:
6232 case Stmt::UnaryOperatorClass:
6239 static std::pair<QualType, StringRef>
6246 StringRef Name = UserTy->getDecl()->getName();
6247 QualType CastTy = llvm::StringSwitch<QualType>(Name)
6251 .Case(
"SInt32", Context.
IntTy)
6256 return std::make_pair(CastTy, Name);
6258 TyTy = UserTy->desugar();
6262 if (
const ParenExpr *PE = dyn_cast<ParenExpr>(E))
6264 PE->getSubExpr()->getType(),
6273 StringRef TrueName, FalseName;
6275 std::tie(TrueTy, TrueName) =
6277 CO->getTrueExpr()->getType(),
6279 std::tie(FalseTy, FalseName) =
6281 CO->getFalseExpr()->getType(),
6282 CO->getFalseExpr());
6284 if (TrueTy == FalseTy)
6285 return std::make_pair(TrueTy, TrueName);
6286 else if (TrueTy.
isNull())
6287 return std::make_pair(FalseTy, FalseName);
6288 else if (FalseTy.
isNull())
6289 return std::make_pair(TrueTy, TrueName);
6292 return std::make_pair(
QualType(), StringRef());
6297 const char *StartSpecifier,
6298 unsigned SpecifierLen,
6300 using namespace analyze_format_string;
6301 using namespace analyze_printf;
6310 while (
const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
6311 ExprTy = TET->getUnderlyingExpr()->getType();
6325 if (ICE->getCastKind() == CK_IntegralCast ||
6326 ICE->getCastKind() == CK_FloatingCast) {
6327 E = ICE->getSubExpr();
6336 if (AT.matchesType(S.
Context, ExprTy))
6350 bool IsEnum =
false;
6352 ExprTy = EnumTy->getDecl()->getIntegerType();
6360 if (isObjCContext() &&
6371 const llvm::APInt &V = IL->getValue();
6381 if (TD->getUnderlyingType() == IntendedTy)
6389 bool ShouldNotPrintDirectly =
false; StringRef CastTyName;
6394 IntendedTy = CastTy;
6395 ShouldNotPrintDirectly =
true;
6400 PrintfSpecifier fixedFS = FS;
6407 llvm::raw_svector_ostream os(buf);
6408 fixedFS.toString(os);
6410 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
6412 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
6413 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6415 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6419 EmitFormatDiagnostic(S.
PDiag(diag)
6420 << AT.getRepresentativeTypeName(S.
Context)
6434 llvm::raw_svector_ostream CastFix(CastBuf);
6440 if (!AT.matchesType(S.
Context, IntendedTy) || ShouldNotPrintDirectly)
6445 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
6463 if (ShouldNotPrintDirectly) {
6468 if (
const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
6469 Name = TypedefTy->getDecl()->getName();
6472 EmitFormatDiagnostic(S.
PDiag(diag::warn_format_argument_needs_cast)
6473 << Name << IntendedTy << IsEnum
6481 EmitFormatDiagnostic(
6482 S.
PDiag(diag::warn_format_conversion_argument_type_mismatch)
6483 << AT.getRepresentativeTypeName(S.
Context) << ExprTy << IsEnum
6498 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6500 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6503 EmitFormatDiagnostic(
6504 S.
PDiag(diag) << AT.getRepresentativeTypeName(S.
Context) << ExprTy
6511 EmitFormatDiagnostic(
6512 S.
PDiag(diag::warn_non_pod_vararg_with_format_string)
6516 << AT.getRepresentativeTypeName(S.
Context)
6520 checkForCStrMembers(AT, E);
6525 EmitFormatDiagnostic(
6526 S.
PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
6530 << AT.getRepresentativeTypeName(S.
Context)
6538 << isa<InitListExpr>(E) << ExprTy << CallType
6539 << AT.getRepresentativeTypeName(S.
Context)
6544 assert(FirstDataArg + FS.
getArgIndex() < CheckedVarArgs.size() &&
6545 "format string specifier index out of range");
6546 CheckedVarArgs[FirstDataArg + FS.
getArgIndex()] =
true;
6556 class CheckScanfHandler :
public CheckFormatHandler {
6558 CheckScanfHandler(
Sema &s,
const FormatStringLiteral *fexpr,
6560 unsigned firstDataArg,
unsigned numDataArgs,
6561 const char *beg,
bool hasVAListArg,
6562 ArrayRef<const Expr *> Args,
unsigned formatIdx,
6564 llvm::SmallBitVector &CheckedVarArgs,
6565 UncoveredArgHandler &UncoveredArg)
6566 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
6567 numDataArgs, beg, hasVAListArg, Args, formatIdx,
6568 inFunctionCall, CallType, CheckedVarArgs,
6572 const char *startSpecifier,
6573 unsigned specifierLen)
override;
6575 bool HandleInvalidScanfConversionSpecifier(
6577 const char *startSpecifier,
6578 unsigned specifierLen)
override;
6580 void HandleIncompleteScanList(
const char *start,
const char *end)
override;
6585 void CheckScanfHandler::HandleIncompleteScanList(
const char *start,
6587 EmitFormatDiagnostic(S.
PDiag(diag::warn_scanf_scanlist_incomplete),
6588 getLocationOfByte(end),
true,
6589 getSpecifierRange(start, end - start));
6592 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
6594 const char *startSpecifier,
6595 unsigned specifierLen) {
6599 return HandleInvalidConversionSpecifier(FS.
getArgIndex(),
6601 startSpecifier, specifierLen,
6605 bool CheckScanfHandler::HandleScanfSpecifier(
6607 const char *startSpecifier,
6608 unsigned specifierLen) {
6609 using namespace analyze_scanf;
6610 using namespace analyze_format_string;
6622 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6623 startSpecifier, specifierLen);
6630 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
6631 if (Amt.getConstantAmount() == 0) {
6633 Amt.getConstantLength());
6634 EmitFormatDiagnostic(S.
PDiag(diag::warn_scanf_nonzero_width),
6635 getLocationOfByte(Amt.getStart()),
6649 if (argIndex < NumDataArgs) {
6653 CoveredArgs.set(argIndex);
6658 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6659 diag::warn_format_nonsensical_length);
6661 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
6663 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6664 diag::warn_format_non_standard_conversion_spec);
6667 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6673 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
6677 const Expr *Ex = getDataArg(argIndex);
6693 ScanfSpecifier fixedFS = FS;
6697 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6699 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6705 llvm::raw_svector_ostream os(buf);
6706 fixedFS.toString(os);
6708 EmitFormatDiagnostic(
6713 getSpecifierRange(startSpecifier, specifierLen),
6715 getSpecifierRange(startSpecifier, specifierLen), os.str()));
6717 EmitFormatDiagnostic(S.
PDiag(diag)
6722 getSpecifierRange(startSpecifier, specifierLen));
6729 const Expr *OrigFormatExpr,
6730 ArrayRef<const Expr *> Args,
6731 bool HasVAListArg,
unsigned format_idx,
6732 unsigned firstDataArg,
6734 bool inFunctionCall,
6736 llvm::SmallBitVector &CheckedVarArgs,
6737 UncoveredArgHandler &UncoveredArg) {
6739 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
6740 CheckFormatHandler::EmitFormatDiagnostic(
6741 S, inFunctionCall, Args[format_idx],
6742 S.
PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
6748 StringRef StrRef = FExpr->getString();
6749 const char *Str = StrRef.data();
6753 assert(T &&
"String literal not of constant array type!");
6754 size_t TypeSize = T->
getSize().getZExtValue();
6755 size_t StrLen =
std::min(
std::max(TypeSize,
size_t(1)) - 1, StrRef.size());
6756 const unsigned numDataArgs = Args.size() - firstDataArg;
6760 if (TypeSize <= StrRef.size() &&
6761 StrRef.substr(0, TypeSize).find(
'\0') == StringRef::npos) {
6762 CheckFormatHandler::EmitFormatDiagnostic(
6763 S, inFunctionCall, Args[format_idx],
6764 S.
PDiag(diag::warn_printf_format_string_not_null_terminated),
6765 FExpr->getLocStart(),
6771 if (StrLen == 0 && numDataArgs > 0) {
6772 CheckFormatHandler::EmitFormatDiagnostic(
6773 S, inFunctionCall, Args[format_idx],
6774 S.
PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
6782 CheckPrintfHandler H(
6783 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
6785 HasVAListArg, Args, format_idx, inFunctionCall, CallType,
6786 CheckedVarArgs, UncoveredArg);
6794 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
6795 numDataArgs, Str, HasVAListArg, Args, format_idx,
6796 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
6808 const char *Str = StrRef.data();
6811 assert(T &&
"String literal not of constant array type!");
6812 size_t TypeSize = T->
getSize().getZExtValue();
6813 size_t StrLen =
std::min(
std::max(TypeSize,
size_t(1)) - 1, StrRef.size());
6824 switch (AbsFunction) {
6828 case Builtin::BI__builtin_abs:
6829 return Builtin::BI__builtin_labs;
6830 case Builtin::BI__builtin_labs:
6831 return Builtin::BI__builtin_llabs;
6832 case Builtin::BI__builtin_llabs:
6835 case Builtin::BI__builtin_fabsf:
6836 return Builtin::BI__builtin_fabs;
6837 case Builtin::BI__builtin_fabs:
6838 return Builtin::BI__builtin_fabsl;
6839 case Builtin::BI__builtin_fabsl:
6842 case Builtin::BI__builtin_cabsf:
6843 return Builtin::BI__builtin_cabs;
6844 case Builtin::BI__builtin_cabs:
6845 return Builtin::BI__builtin_cabsl;
6846 case Builtin::BI__builtin_cabsl:
6849 case Builtin::BIabs:
6850 return Builtin::BIlabs;
6851 case Builtin::BIlabs:
6852 return Builtin::BIllabs;
6853 case Builtin::BIllabs:
6856 case Builtin::BIfabsf:
6857 return Builtin::BIfabs;
6858 case Builtin::BIfabs:
6859 return Builtin::BIfabsl;
6860 case Builtin::BIfabsl:
6863 case Builtin::BIcabsf:
6864 return Builtin::BIcabs;
6865 case Builtin::BIcabs:
6866 return Builtin::BIcabsl;
6867 case Builtin::BIcabsl:
6896 unsigned AbsFunctionKind) {
6897 unsigned BestKind = 0;
6899 for (
unsigned Kind = AbsFunctionKind;
Kind != 0;
6905 else if (Context.
hasSameType(ParamType, ArgType)) {
6928 llvm_unreachable(
"Type not integer, floating, or complex");
6935 switch (ValueKind) {
6940 case Builtin::BI__builtin_fabsf:
6941 case Builtin::BI__builtin_fabs:
6942 case Builtin::BI__builtin_fabsl:
6943 case Builtin::BI__builtin_cabsf:
6944 case Builtin::BI__builtin_cabs:
6945 case Builtin::BI__builtin_cabsl:
6946 return Builtin::BI__builtin_abs;
6947 case Builtin::BIfabsf:
6948 case Builtin::BIfabs:
6949 case Builtin::BIfabsl:
6950 case Builtin::BIcabsf:
6951 case Builtin::BIcabs:
6952 case Builtin::BIcabsl:
6953 return Builtin::BIabs;
6959 case Builtin::BI__builtin_abs:
6960 case Builtin::BI__builtin_labs:
6961 case Builtin::BI__builtin_llabs:
6962 case Builtin::BI__builtin_cabsf:
6963 case Builtin::BI__builtin_cabs:
6964 case Builtin::BI__builtin_cabsl:
6965 return Builtin::BI__builtin_fabsf;
6966 case Builtin::BIabs:
6967 case Builtin::BIlabs:
6968 case Builtin::BIllabs:
6969 case Builtin::BIcabsf:
6970 case Builtin::BIcabs:
6971 case Builtin::BIcabsl:
6972 return Builtin::BIfabsf;
6978 case Builtin::BI__builtin_abs:
6979 case Builtin::BI__builtin_labs:
6980 case Builtin::BI__builtin_llabs:
6981 case Builtin::BI__builtin_fabsf:
6982 case Builtin::BI__builtin_fabs:
6983 case Builtin::BI__builtin_fabsl:
6984 return Builtin::BI__builtin_cabsf;
6985 case Builtin::BIabs:
6986 case Builtin::BIlabs:
6987 case Builtin::BIllabs:
6988 case Builtin::BIfabsf:
6989 case Builtin::BIfabs:
6990 case Builtin::BIfabsl:
6991 return Builtin::BIcabsf;
6994 llvm_unreachable(
"Unable to convert function");
7005 case Builtin::BI__builtin_abs:
7006 case Builtin::BI__builtin_fabs:
7007 case Builtin::BI__builtin_fabsf:
7008 case Builtin::BI__builtin_fabsl:
7009 case Builtin::BI__builtin_labs:
7010 case Builtin::BI__builtin_llabs:
7011 case Builtin::BI__builtin_cabs:
7012 case Builtin::BI__builtin_cabsf:
7013 case Builtin::BI__builtin_cabsl:
7014 case Builtin::BIabs:
7015 case Builtin::BIlabs:
7016 case Builtin::BIllabs:
7017 case Builtin::BIfabs:
7018 case Builtin::BIfabsf:
7019 case Builtin::BIfabsl:
7020 case Builtin::BIcabs:
7021 case Builtin::BIcabsf:
7022 case Builtin::BIcabsl:
7025 llvm_unreachable(
"Unknown Builtin type");
7031 unsigned AbsKind,
QualType ArgType) {
7032 bool EmitHeaderHint =
true;
7033 const char *HeaderName =
nullptr;
7034 const char *FunctionName =
nullptr;
7036 FunctionName =
"std::abs";
7038 HeaderName =
"cstdlib";
7040 HeaderName =
"cmath";
7042 llvm_unreachable(
"Invalid Type");
7051 for (
const auto *I : R) {
7054 FDecl = dyn_cast<
FunctionDecl>(UsingD->getTargetDecl());
7071 EmitHeaderHint =
false;
7083 R.suppressDiagnostics();
7086 if (R.isSingleResult()) {
7089 EmitHeaderHint =
false;
7093 }
else if (!R.empty()) {
7099 S.
Diag(Loc, diag::note_replace_abs_function)
7105 if (!EmitHeaderHint)
7108 S.
Diag(Loc, diag::note_include_header_or_declare) << HeaderName
7112 template <std::
size_t StrLen>
7114 const char (&Str)[StrLen]) {
7126 void Sema::CheckAbsoluteValueFunction(
const CallExpr *Call,
7133 if (AbsKind == 0 && !IsStdAbs)
7142 const char *FunctionName =
7144 Diag(Call->
getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
7154 unsigned DiagType = 0;
7160 Diag(Call->
getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
7174 if (ArgValueKind == ParamValueKind) {
7180 << FDecl << ArgType << ParamType;
7182 if (NewAbsKind == 0)
7195 if (NewAbsKind == 0)
7199 << FDecl << ParamValueKind << ArgValueKind;
7206 void Sema::CheckMaxUnsignedZero(
const CallExpr *Call,
7208 if (!Call || !FDecl)
return;
7211 if (inTemplateInstantiation())
return;
7218 if (!ArgList)
return;
7219 if (ArgList->size() != 1)
return;
7222 const auto& TA = ArgList->
get(0);
7228 auto IsLiteralZeroArg = [](
const Expr* E) ->
bool {
7230 if (!MTE)
return false;
7231 const auto *Num = dyn_cast<
IntegerLiteral>(MTE->GetTemporaryExpr());
7232 if (!Num)
return false;
7233 if (Num->getValue() != 0)
return false;
7239 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
7240 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
7243 if (IsFirstArgZero == IsSecondArgZero)
return;
7248 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
7255 if (IsFirstArgZero) {
7288 << SizeRange << FnName;
7289 S.
Diag(FnLoc, diag::note_memsize_comparison_paren)
7293 S.
Diag(SizeRange.
getBegin(), diag::note_memsize_comparison_cast_silence)
7304 bool &IsContained) {
7307 IsContained =
false;
7320 for (
auto *FD : RD->
fields()) {
7336 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
7337 if (SizeOf->getKind() ==
UETT_SizeOf && !SizeOf->isArgumentType())
7346 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
7348 return SizeOf->getTypeOfArgument();
7360 void Sema::CheckMemaccessArguments(
const CallExpr *Call,
7367 unsigned ExpectedNumArgs =
7368 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
7372 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
7373 BId == Builtin::BIstrndup ? 1 : 2);
7375 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
7385 llvm::FoldingSetNodeID SizeOfArgID;
7394 for (
unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
7413 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
7417 if (SizeOfArgID == llvm::FoldingSetNodeID())
7418 SizeOfArg->
Profile(SizeOfArgID, Context,
true);
7419 llvm::FoldingSetNodeID DestID;
7420 Dest->
Profile(DestID, Context,
true);
7421 if (DestID == SizeOfArgID) {
7424 unsigned ActionIdx = 0;
7425 StringRef ReadableName = FnName->
getName();
7427 if (
const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
7428 if (UnaryOp->getOpcode() == UO_AddrOf)
7451 DiagRuntimeBehavior(SL, SizeOfArg,
7452 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
7458 DiagRuntimeBehavior(SL, SizeOfArg,
7459 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
7473 DiagRuntimeBehavior(LenExpr->
getExprLoc(), Dest,
7474 PDiag(diag::warn_sizeof_pointer_type_memaccess)
7475 << FnName << SizeOfArgTy << ArgIdx
7493 unsigned OperationType = 0;
7496 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
7497 if (BId == Builtin::BImemcpy)
7499 else if(BId == Builtin::BImemmove)
7501 else if (BId == Builtin::BImemcmp)
7505 DiagRuntimeBehavior(
7507 PDiag(diag::warn_dyn_class_memaccess)
7508 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
7509 << FnName << IsContained << ContainedRD << OperationType
7512 BId != Builtin::BImemset)
7513 DiagRuntimeBehavior(
7515 PDiag(diag::warn_arc_object_memaccess)
7516 << ArgIdx << FnName << PointeeTy
7521 DiagRuntimeBehavior(
7523 PDiag(diag::note_bad_memaccess_silence)
7543 if (isa<IntegerLiteral>(RHS))
7545 else if (isa<IntegerLiteral>(LHS))
7559 if (CAT->getSize().getSExtValue() <= 1)
7569 void Sema::CheckStrlcpycatArguments(
const CallExpr *Call,
7574 if ((NumArgs != 3) && (NumArgs != 4))
7579 const Expr *CompareWithSrc =
nullptr;
7587 CompareWithSrc = Ex;
7590 if (
const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
7591 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
7592 SizeCall->getNumArgs() == 1)
7597 if (!CompareWithSrc)
7609 if (!CompareWithSrcDRE ||
7613 const Expr *OriginalSizeArg = Call->
getArg(2);
7614 Diag(CompareWithSrcDRE->
getLocStart(), diag::warn_strlcpycat_wrong_size)
7626 llvm::raw_svector_ostream OS(sizeString);
7628 DstArg->
printPretty(OS,
nullptr, getPrintingPolicy());
7631 Diag(OriginalSizeArg->
getLocStart(), diag::note_strlcpycat_wrong_size)
7638 if (
const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
7639 if (
const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
7640 return D1->getDecl() == D2->getDecl();
7645 if (
const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7649 return CE->getArg(0)->IgnoreParenCasts();
7657 void Sema::CheckStrncatArguments(
const CallExpr *CE,
7672 unsigned PatternType = 0;
7680 }
else if (
const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
7681 if (BE->getOpcode() == BO_Sub) {
7694 if (PatternType == 0)
7713 if (!isKnownSizeArray) {
7714 if (PatternType == 1)
7715 Diag(SL, diag::warn_strncat_wrong_size) << SR;
7717 Diag(SL, diag::warn_strncat_src_size) << SR;
7721 if (PatternType == 1)
7722 Diag(SL, diag::warn_strncat_large_size) << SR;
7724 Diag(SL, diag::warn_strncat_src_size) << SR;
7727 llvm::raw_svector_ostream OS(sizeString);
7729 DstArg->
printPretty(OS,
nullptr, getPrintingPolicy());
7732 DstArg->
printPretty(OS,
nullptr, getPrintingPolicy());
7735 Diag(SL, diag::note_strncat_wrong_size)
7742 SmallVectorImpl<const DeclRefExpr *> &refVars,
7743 const Decl *ParentDecl);
7745 SmallVectorImpl<const DeclRefExpr *> &refVars,
7746 const Decl *ParentDecl);
7753 const Expr *stackE =
nullptr;
7760 stackE =
EvalAddr(RetValExp, refVars,
nullptr);
7762 stackE =
EvalVal(RetValExp, refVars,
nullptr);
7770 for (
auto *DRE : refVars)
7771 if (isa<ParmVarDecl>(DRE->getDecl()))
7776 if (refVars.empty()) {
7784 diagLoc = refVars[0]->getLocStart();
7785 diagRange = refVars[0]->getSourceRange();
7788 if (
const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
7791 << DR->getDecl()->getDeclName() << diagRange;
7792 }
else if (isa<BlockExpr>(stackE)) {
7793 S.
Diag(diagLoc, diag::err_ret_local_block) << diagRange;
7794 }
else if (isa<AddrLabelExpr>(stackE)) {
7795 S.
Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
7799 if (
auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
7800 if (ICE->getCastKind() == CK_LValueToRValue) {
7804 S.
Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
7810 for (
unsigned i = 0, e = refVars.size(); i != e; ++i) {
7811 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
7849 SmallVectorImpl<const DeclRefExpr *> &refVars,
7850 const Decl *ParentDecl) {
7858 "EvalAddr only works on pointers");
7866 case Stmt::DeclRefExprClass: {
7876 if (V->hasLocalStorage() &&
7877 V->getType()->isReferenceType() && V->hasInit()) {
7879 refVars.push_back(DR);
7880 return EvalAddr(V->getInit(), refVars, ParentDecl);
7886 case Stmt::UnaryOperatorClass: {
7896 case Stmt::BinaryOperatorClass: {
7902 if (op != BO_Add && op != BO_Sub)
7913 return EvalAddr(Base, refVars, ParentDecl);
7918 case Stmt::ConditionalOperatorClass: {
7925 if (!LHSExpr->getType()->isVoidType())
7926 if (
const Expr *LHS =
EvalAddr(LHSExpr, refVars, ParentDecl))
7937 case Stmt::BlockExprClass:
7938 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
7942 case Stmt::AddrLabelExprClass:
7945 case Stmt::ExprWithCleanupsClass:
7946 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7951 case Stmt::ImplicitCastExprClass:
7952 case Stmt::CStyleCastExprClass:
7953 case Stmt::CXXFunctionalCastExprClass:
7954 case Stmt::ObjCBridgedCastExprClass:
7955 case Stmt::CXXStaticCastExprClass:
7956 case Stmt::CXXDynamicCastExprClass:
7957 case Stmt::CXXConstCastExprClass:
7958 case Stmt::CXXReinterpretCastExprClass: {
7959 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
7960 switch (cast<CastExpr>(E)->getCastKind()) {
7961 case CK_LValueToRValue:
7963 case CK_BaseToDerived:
7964 case CK_DerivedToBase:
7965 case CK_UncheckedDerivedToBase:
7967 case CK_CPointerToObjCPointerCast:
7968 case CK_BlockPointerToObjCPointerCast:
7969 case CK_AnyPointerToBlockPointerCast:
7970 return EvalAddr(SubExpr, refVars, ParentDecl);
7972 case CK_ArrayToPointerDecay:
7973 return EvalVal(SubExpr, refVars, ParentDecl);
7979 return EvalAddr(SubExpr, refVars, ParentDecl);
7988 case Stmt::MaterializeTemporaryExprClass:
7989 if (
const Expr *Result =
7990 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7991 refVars, ParentDecl))
8004 SmallVectorImpl<const DeclRefExpr *> &refVars,
8005 const Decl *ParentDecl) {
8018 case Stmt::ImplicitCastExprClass: {
8027 case Stmt::ExprWithCleanupsClass:
8028 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
8031 case Stmt::DeclRefExprClass: {
8043 if (V == ParentDecl)
8046 if (V->hasLocalStorage()) {
8047 if (!V->getType()->isReferenceType())
8054 refVars.push_back(DR);
8055 return EvalVal(V->getInit(), refVars, V);
8063 case Stmt::UnaryOperatorClass: {
8075 case Stmt::ArraySubscriptExprClass: {
8079 const auto *ASE = cast<ArraySubscriptExpr>(E);
8080 if (ASE->isTypeDependent())
8082 return EvalAddr(ASE->getBase(), refVars, ParentDecl);
8085 case Stmt::OMPArraySectionExprClass: {
8086 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
8090 case Stmt::ConditionalOperatorClass: {
8098 if (!LHSExpr->getType()->isVoidType())
8099 if (
const Expr *LHS =
EvalVal(LHSExpr, refVars, ParentDecl))
8111 case Stmt::MemberExprClass: {
8127 case Stmt::MaterializeTemporaryExprClass:
8128 if (
const Expr *Result =
8129 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
8130 refVars, ParentDecl))
8147 Sema::CheckReturnValExpr(
Expr *RetValExp,
QualType lhsType,
8155 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
8158 Diag(ReturnLoc, diag::warn_null_ret)
8168 if (Op == OO_New || Op == OO_Array_New) {
8173 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
8174 << FD << getLangOpts().CPlusPlus11;
8190 if (
DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
8191 if (
DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
8192 if (DRL->getDecl() == DRR->getDecl())
8200 if (
FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
8204 if (
FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
8209 if (
CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
8210 if (CL->getBuiltinCallee())
8213 if (
CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
8214 if (CR->getBuiltinCallee())
8218 Diag(Loc, diag::warn_floatingpoint_eq)
8236 IntRange(
unsigned Width,
bool NonNegative)
8237 : Width(Width), NonNegative(NonNegative) {}
8240 static IntRange forBoolType() {
8241 return IntRange(1,
true);
8246 return forValueOfCanonicalType(C,
8251 static IntRange forValueOfCanonicalType(
ASTContext &C,
const Type *T) {
8254 if (
const VectorType *VT = dyn_cast<VectorType>(T))
8255 T = VT->getElementType().getTypePtr();
8256 if (
const ComplexType *CT = dyn_cast<ComplexType>(T))
8257 T = CT->getElementType().getTypePtr();
8258 if (
const AtomicType *AT = dyn_cast<AtomicType>(T))
8259 T = AT->getValueType().getTypePtr();
8263 if (
const EnumType *ET = dyn_cast<EnumType>(T))
8264 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
8265 }
else if (
const EnumType *ET = dyn_cast<EnumType>(T)) {
8272 !ET->isSignedIntegerOrEnumerationType());
8278 if (NumNegative == 0)
8279 return IntRange(NumPositive,
true);
8281 return IntRange(
std::max(NumPositive + 1, NumNegative),
8296 static IntRange forTargetOfCanonicalType(
ASTContext &C,
const Type *T) {
8299 if (
const VectorType *VT = dyn_cast<VectorType>(T))
8300 T = VT->getElementType().getTypePtr();
8301 if (
const ComplexType *CT = dyn_cast<ComplexType>(T))
8302 T = CT->getElementType().getTypePtr();
8303 if (
const AtomicType *AT = dyn_cast<AtomicType>(T))
8304 T = AT->getValueType().getTypePtr();
8305 if (
const EnumType *ET = dyn_cast<EnumType>(T))
8315 static IntRange join(IntRange L, IntRange R) {
8316 return IntRange(
std::max(L.Width, R.Width),
8317 L.NonNegative && R.NonNegative);
8321 static IntRange meet(IntRange L, IntRange R) {
8322 return IntRange(
std::min(L.Width, R.Width),
8323 L.NonNegative || R.NonNegative);
8330 unsigned MaxWidth) {
8331 if (value.isSigned() && value.isNegative())
8332 return IntRange(value.getMinSignedBits(),
false);
8334 if (value.getBitWidth() > MaxWidth)
8335 value = value.trunc(MaxWidth);
8339 return IntRange(value.getActiveBits(),
true);
8343 unsigned MaxWidth) {
8351 R = IntRange::join(R, El);
8359 return IntRange::join(R, I);
8374 Ty = AtomicRHS->getValueType();
8393 if (
const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
8394 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
8397 IntRange OutputTypeRange = IntRange::forValueOfType(C,
GetExprType(CE));
8399 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
8400 CE->getCastKind() == CK_BooleanToSignedIntegral;
8404 return OutputTypeRange;
8408 std::min(MaxWidth, OutputTypeRange.Width));
8411 if (SubRange.Width >= OutputTypeRange.Width)
8412 return OutputTypeRange;
8416 return IntRange(SubRange.Width,
8417 SubRange.NonNegative || OutputTypeRange.NonNegative);
8420 if (
const auto *CO = dyn_cast<ConditionalOperator>(E)) {
8423 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
8425 : CO->getFalseExpr(),
8429 IntRange L =
GetExprRange(C, CO->getTrueExpr(), MaxWidth);
8430 IntRange R =
GetExprRange(C, CO->getFalseExpr(), MaxWidth);
8431 return IntRange::join(L, R);
8434 if (
const auto *BO = dyn_cast<BinaryOperator>(E)) {
8435 switch (BO->getOpcode()) {
8437 llvm_unreachable(
"builtin <=> should have class type");
8448 return IntRange::forBoolType();
8460 return IntRange::forValueOfType(C,
GetExprType(E));
8471 return IntRange::forValueOfType(C,
GetExprType(E));
8476 return IntRange::meet(
GetExprRange(C, BO->getLHS(), MaxWidth),
8484 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
8485 if (I->getValue() == 1) {
8486 IntRange R = IntRange::forValueOfType(C,
GetExprType(E));
8487 return IntRange(R.Width,
true);
8493 return IntRange::forValueOfType(C,
GetExprType(E));
8497 case BO_ShrAssign: {
8503 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
8504 shift.isNonNegative()) {
8505 unsigned zext = shift.getZExtValue();
8506 if (zext >= L.Width)
8507 L.Width = (L.NonNegative ? 0 : 1);
8521 if (BO->getLHS()->getType()->isPointerType())
8522 return IntRange::forValueOfType(C,
GetExprType(E));
8533 llvm::APSInt divisor;
8534 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
8535 unsigned log2 = divisor.logBase2();
8536 if (log2 >= L.Width)
8537 L.Width = (L.NonNegative ? 0 : 1);
8539 L.Width =
std::min(L.Width - log2, MaxWidth);
8545 return IntRange(L.Width, L.NonNegative && R.NonNegative);
8556 IntRange meet = IntRange::meet(L, R);
8557 meet.Width =
std::min(meet.Width, MaxWidth);
8573 return IntRange::join(L, R);
8576 if (
const auto *UO = dyn_cast<UnaryOperator>(E)) {
8577 switch (UO->getOpcode()) {
8580 return IntRange::forBoolType();
8585 return IntRange::forValueOfType(C,
GetExprType(E));
8592 if (
const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
8593 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
8596 return IntRange(BitField->getBitWidthValue(C),
8597 BitField->getType()->isUnsignedIntegerOrEnumerationType());
8599 return IntRange::forValueOfType(C,
GetExprType(E));
8610 const llvm::fltSemantics &Src,
8611 const llvm::fltSemantics &Tgt) {
8612 llvm::APFloat truncated = value;
8615 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
8616 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
8618 return truncated.bitwiseIsEqual(value);
8627 const llvm::fltSemantics &Src,
8628 const llvm::fltSemantics &Tgt) {
8650 if (isa<EnumConstantDecl>(DR->getDecl()))
8677 struct PromotedRange {
8679 llvm::APSInt PromotedMin;
8681 llvm::APSInt PromotedMax;
8683 PromotedRange(IntRange R,
unsigned BitWidth,
bool Unsigned) {
8685 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
8686 else if (R.Width >= BitWidth && !Unsigned) {
8690 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
8691 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
8693 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
8694 .extOrTrunc(BitWidth);
8695 PromotedMin.setIsUnsigned(Unsigned);
8697 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
8698 .extOrTrunc(BitWidth);
8699 PromotedMax.setIsUnsigned(Unsigned);
8704 bool isContiguous()
const {
return PromotedMin <= PromotedMax; }
8707 enum ComparisonResult {
8716 Less = LE | LT | NE,
8717 Min = LE | InRangeFlag,
8718 InRange = InRangeFlag,
8719 Max = GE | InRangeFlag,
8720 Greater = GE | GT | NE,
8722 OnlyValue = LE | GE | EQ | InRangeFlag,
8726 ComparisonResult
compare(
const llvm::APSInt &
Value)
const {
8727 assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
8728 Value.isUnsigned() == PromotedMin.isUnsigned());
8729 if (!isContiguous()) {
8730 assert(Value.isUnsigned() &&
"discontiguous range for signed compare");
8731 if (Value.isMinValue())
return Min;
8732 if (Value.isMaxValue())
return Max;
8733 if (Value >= PromotedMin)
return InRange;
8734 if (Value <= PromotedMax)
return InRange;
8738 switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
8739 case -1:
return Less;
8740 case 0:
return PromotedMin == PromotedMax ? OnlyValue : Min;
8742 switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
8743 case -1:
return InRange;
8745 case 1:
return Greater;
8749 llvm_unreachable(
"impossible compare result");
8755 ComparisonResult LTFlag = LT, GTFlag = GT;
8756 if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
8758 if (R & EQ)
return StringRef(
"'std::strong_ordering::equal'");
8759 if (R & LTFlag)
return StringRef(
"'std::strong_ordering::less'");
8760 if (R & GTFlag)
return StringRef(
"'std::strong_ordering::greater'");
8764 ComparisonResult TrueFlag, FalseFlag;
8768 }
else if (Op == BO_NE) {
8772 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
8779 if (Op == BO_GE || Op == BO_LE)
8780 std::swap(TrueFlag, FalseFlag);
8783 return StringRef(
"true");
8785 return StringRef(
"false");
8794 if (ICE->getCastKind() != CK_IntegralCast &&
8795 ICE->getCastKind() != CK_NoOp)
8797 E = ICE->getSubExpr();
8806 enum ConstantValueKind {
8811 if (
auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
8812 return BL->getValue() ? ConstantValueKind::LiteralTrue
8813 : ConstantValueKind::LiteralFalse;
8814 return ConstantValueKind::Miscellaneous;
8819 const llvm::APSInt &
Value,
8824 Expr *OriginalOther = Other;
8844 OtherT = AT->getValueType();
8845 IntRange OtherRange = IntRange::forValueOfType(S.
Context, OtherT);
8849 bool OtherIsBooleanDespiteType =
8851 if (OtherIsBooleanDespiteType)
8852 OtherRange = IntRange::forBoolType();
8856 PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
8857 Value.isUnsigned());
8858 auto Cmp = OtherPromotedRange.compare(Value);
8859 auto Result = PromotedRange::constantValue(E->
getOpcode(), Cmp, RhsConstant);
8869 bool InRange = Cmp & PromotedRange::InRangeFlag;
8876 if (
const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
8877 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
8881 llvm::raw_svector_ostream OS(PrettySourceValue);
8883 OS <<
'\'' << *ED <<
"' (" << Value <<
")";
8893 S.
PDiag(!InRange ? diag::warn_out_of_range_compare
8894 : diag::warn_tautological_bool_compare)
8896 << OtherT << OtherIsBooleanDespiteType << *Result
8901 ? diag::warn_unsigned_enum_always_true_comparison
8902 : diag::warn_unsigned_always_true_comparison)
8903 : diag::warn_tautological_constant_compare;
8906 << RhsConstant << OtherT << E->
getOpcodeStr() << OS.str() << *Result
8940 llvm::APSInt RHSValue;
8941 llvm::APSInt LHSValue;
8947 if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
8951 if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
8953 const bool RhsConstant = IsRHSIntegralLiteral;
8954 Expr *Const = RhsConstant ? RHS : LHS;
8955 Expr *Other = RhsConstant ? LHS : RHS;
8956 const llvm::APSInt &
Value = RhsConstant ? RHSValue : LHSValue;
8979 if (
const auto *TET = dyn_cast<TypeOfExprType>(LHS->
getType()))
8981 if (
const auto *TET = dyn_cast<TypeOfExprType>(RHS->
getType()))
8987 Expr *signedOperand, *unsignedOperand;
8990 "unsigned comparison between two signed integer expressions?");
8991 signedOperand = LHS;
8992 unsignedOperand = RHS;
8994 signedOperand = RHS;
8995 unsignedOperand = LHS;
9009 if (signedRange.NonNegative)
9022 assert(unsignedRange.NonNegative &&
"unsigned range includes negative?");
9024 if (unsignedRange.Width < comparisonWidth)
9029 S.
PDiag(diag::warn_mixed_sign_comparison)
9057 S.
Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
9095 unsigned DiagID = 0;
9096 if (SignedEnum && !SignedBitfield) {
9097 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
9098 }
else if (SignedBitfield && !SignedEnum &&
9100 DiagID = diag::warn_signed_bitfield_enum_conversion;
9104 S.
Diag(InitLoc, DiagID) << Bitfield << ED;
9109 << SignedEnum << TypeRange;
9120 if (BitsNeeded > FieldWidth) {
9122 S.
Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
9132 unsigned OriginalWidth = Value.getBitWidth();
9134 if (!Value.isSigned() || Value.isNegative())
9135 if (
UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
9136 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
9137 OriginalWidth = Value.getMinSignedBits();
9139 if (OriginalWidth <= FieldWidth)
9143 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
9147 TruncatedValue = TruncatedValue.extend(OriginalWidth);
9148 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
9153 if (FieldWidth == 1 && Value == 1)
9156 std::string PrettyValue = Value.toString(10);
9157 std::string PrettyTrunc = TruncatedValue.toString(10);
9159 S.
Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
9160 << PrettyValue << PrettyTrunc << OriginalInit->
getType()
9189 bool pruneControlFlow =
false) {
9190 if (pruneControlFlow) {
9204 unsigned diag,
bool pruneControlFlow =
false) {
9218 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
9221 const bool IsLiteral =
9222 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
9224 llvm::APFloat
Value(0.0);
9229 diag::warn_impcast_float_integer, PruneWarnings);
9232 bool isExact =
false;
9236 if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
9237 &isExact) == llvm::APFloat::opOK &&
9239 if (IsLiteral)
return;
9240 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
9244 unsigned DiagID = 0;
9247 DiagID = diag::warn_impcast_literal_float_to_integer;
9248 }
else if (IntegerValue == 0) {
9249 if (Value.isZero()) {
9251 diag::warn_impcast_float_integer, PruneWarnings);
9254 DiagID = diag::warn_impcast_float_to_integer_zero;
9256 if (IntegerValue.isUnsigned()) {
9257 if (!IntegerValue.isMaxValue()) {
9259 diag::warn_impcast_float_integer, PruneWarnings);
9262 if (!IntegerValue.isMaxSignedValue() &&
9263 !IntegerValue.isMinSignedValue()) {
9265 diag::warn_impcast_float_integer, PruneWarnings);
9269 DiagID = diag::warn_impcast_float_to_integer;
9278 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
9279 precision = (precision * 59 + 195) / 196;
9280 Value.toString(PrettySourceValue, precision);
9284 PrettyTargetValue = Value.isZero() ?
"false" :
"true";
9286 IntegerValue.toString(PrettyTargetValue);
9288 if (PruneWarnings) {
9292 << PrettySourceValue << PrettyTargetValue
9303 if (!Range.Width)
return "0";
9305 llvm::APSInt ValueInRange =
Value;
9306 ValueInRange.setIsSigned(!Range.NonNegative);
9307 ValueInRange = ValueInRange.trunc(Range.Width);
9308 return ValueInRange.toString(10);
9312 if (!isa<ImplicitCastExpr>(Ex))
9317 const Type *Source =
9324 const Type *BoolCandidateType = ToBool ? Target : Source;
9326 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
9333 for (
unsigned i = 0; i < NumArgs; ++i) {
9338 bool IsSwapped = ((i > 0) &&
9340 IsSwapped |= ((i < (NumArgs - 1)) &&
9346 diag::warn_impcast_floating_point_to_bool);
9353 if (S.
Diags.
isIgnored(diag::warn_impcast_null_pointer_to_integer,
9358 if (isa<CallExpr>(E))
9387 if (MacroName ==
"NULL")
9395 S.
Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
9413 unsigned ElementKind) {
9415 if (
auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
9416 if (ICE->getCastKind() == CK_BitCast &&
9418 Element = ICE->getSubExpr();
9429 diag::warn_objc_collection_literal_element)
9430 << ElementType << ElementKind << TargetElementType
9434 if (
auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
9436 else if (
auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
9451 if (TargetObjCPtr->isUnspecialized() ||
9452 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9457 if (TypeArgs.size() != 1)
9460 QualType TargetElementType = TypeArgs[0];
9461 for (
unsigned I = 0, N = ArrayLiteral->
getNumElements(); I != N; ++I) {
9480 if (TargetObjCPtr->isUnspecialized() ||
9481 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9486 if (TypeArgs.size() != 2)
9489 QualType TargetKeyType = TypeArgs[0];
9490 QualType TargetObjectType = TypeArgs[1];
9491 for (
unsigned I = 0, N = DictionaryLiteral->
getNumElements(); I != N; ++I) {
9506 const char FirstLiteralCharacter =
9508 if (FirstLiteralCharacter ==
'0')
9515 const char FirstContextCharacter =
9517 if (FirstContextCharacter ==
'{')
9526 bool *ICContext =
nullptr) {
9531 if (Source == Target)
return;
9544 if (isa<StringLiteral>(E))
9549 diag::warn_impcast_string_literal_to_bool);
9550 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
9551 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
9555 diag::warn_impcast_objective_c_literal_to_bool);
9566 if (
auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
9568 else if (
auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
9572 if (isa<VectorType>(Source)) {
9573 if (!isa<VectorType>(Target)) {
9576 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
9584 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
9585 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
9587 if (
auto VecTy = dyn_cast<VectorType>(Target))
9588 Target = VecTy->getElementType().getTypePtr();
9591 if (isa<ComplexType>(Source)) {
9592 if (!isa<ComplexType>(Target)) {
9598 ? diag::err_impcast_complex_scalar
9599 : diag::warn_impcast_complex_scalar);
9602 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
9603 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
9612 if (TargetBT && TargetBT->isFloatingPoint()) {
9616 if (SourceBT->
getKind() > TargetBT->getKind()) {
9634 else if (TargetBT->getKind() > SourceBT->
getKind()) {
9644 if (TargetBT && TargetBT->isInteger()) {
9667 if (isa<ImplicitCastExpr>(LastA) &&
9671 diag::warn_impcast_floating_point_to_bool);
9691 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.
Context, Target);
9693 if (SourceRange.Width > TargetRange.Width) {
9696 llvm::APSInt
Value(32);
9701 std::string PrettySourceValue = Value.toString(10);
9705 S.
PDiag(diag::warn_impcast_integer_precision_constant)
9706 << PrettySourceValue << PrettyTargetValue
9719 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
9722 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
9732 std::string PrettySourceValue = Value.toString(10);
9737 S.
PDiag(diag::warn_impcast_integer_precision_constant)
9738 << PrettySourceValue << PrettyTargetValue << E->
getType() << T
9747 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
9748 (!TargetRange.NonNegative && SourceRange.NonNegative &&
9749 SourceRange.Width == TargetRange.Width)) {
9753 unsigned DiagID = diag::warn_impcast_integer_sign;
9761 DiagID = diag::warn_impcast_integer_sign_conditional;
9775 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
9783 if (SourceEnum->getDecl()->hasNameForLinkage() &&
9784 TargetEnum->getDecl()->hasNameForLinkage() &&
9785 SourceEnum != TargetEnum) {
9790 diag::warn_impcast_different_enum_types);
9801 if (isa<ConditionalOperator>(E))
9813 bool Suspicious =
false;
9819 if (!Suspicious)
return;
9822 if (!S.
Diags.
isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
9831 E->
getType(), CC, &Suspicious);
9834 E->
getType(), CC, &Suspicious);
9858 if (isa<ConditionalOperator>(E)) {
9865 if (
CallExpr *Call = dyn_cast<CallExpr>(E))
9880 for (
auto *SE : POE->semantics())
9881 if (
auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
9886 if (isa<ExplicitCastExpr>(E)) {
9893 if (BO->isComparisonOp())
9897 if (BO->getOpcode() == BO_Assign)
9905 if (isa<StmtExpr>(E))
return;
9908 if (isa<UnaryExprOrTypeTraitExpr>(E))
return;
9913 bool IsLogicalAndOperator = BO && BO->
getOpcode() == BO_LAnd;
9915 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
9919 if (IsLogicalAndOperator &&
9929 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
9933 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
9938 if (U->getOpcode() == UO_LNot)
9948 diag::err_opencl_enqueue_kernel_invalid_local_size_type);
9965 if (
const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9966 if (!DRE->getDecl()->getType()->isReferenceType())
9968 }
else if (
const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9969 if (!M->getMemberDecl()->getType()->isReferenceType())
9971 }
else if (
const CallExpr *Call = dyn_cast<CallExpr>(E)) {
9983 SemaRef.
Diag(FD->
getLocation(), diag::note_reference_is_return_value) << FD;
10028 if (isa<CXXThisExpr>(E)) {
10029 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
10030 : diag::warn_this_bool_conversion;
10035 bool IsAddressOf =
false;
10038 if (UO->getOpcode() != UO_AddrOf)
10040 IsAddressOf =
true;
10041 E = UO->getSubExpr();
10045 unsigned DiagID = IsCompare
10046 ? diag::warn_address_of_reference_null_compare
10047 : diag::warn_address_of_reference_bool_conversion;
10055 auto ComplainAboutNonnullParamOrCall = [&](
const Attr *NonnullAttr) {
10056 bool IsParam = isa<NonNullAttr>(NonnullAttr);
10058 llvm::raw_string_ostream S(Str);
10060 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
10061 : diag::warn_cast_nonnull_to_bool;
10064 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
10070 if (
const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
10071 ComplainAboutNonnullParamOrCall(A);
10081 }
else if (
MemberExpr *M = dyn_cast<MemberExpr>(E)) {
10082 D = M->getMemberDecl();
10090 if (
const auto* PV = dyn_cast<ParmVarDecl>(D)) {
10091 if (getCurFunction() &&
10092 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
10093 if (
const Attr *A = PV->getAttr<NonNullAttr>()) {
10094 ComplainAboutNonnullParamOrCall(A);
10098 if (
const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
10099 auto ParamIter = llvm::find(FD->
parameters(), PV);
10105 ComplainAboutNonnullParamOrCall(
NonNull);
10109 for (
unsigned ArgNo :
NonNull->args()) {
10110 if (ArgNo == ParamNo) {
10111 ComplainAboutNonnullParamOrCall(
NonNull);
10125 if (IsAddressOf && IsFunction) {
10130 if (!IsAddressOf && !IsFunction && !IsArray)
10135 llvm::raw_string_ostream S(Str);
10138 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
10139 : diag::warn_impcast_pointer_to_bool;
10146 DiagType = AddressOf;
10147 else if (IsFunction)
10148 DiagType = FunctionPointer;
10150 DiagType = ArrayPointer;
10152 llvm_unreachable(
"Could not determine diagnostic.");
10154 << Range << IsEqual;
10166 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
10167 if (ReturnType.isNull())
10174 if (!ReturnType->isPointerType()) {
10177 if (!ReturnType->isIntegerType())
10186 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
10202 if (isUnevaluatedContext())
10212 CheckArrayAccess(E);
10226 void Sema::CheckForIntOverflow (
Expr *E) {
10231 Expr *E = Exprs.pop_back_val();
10238 if (
auto InitList = dyn_cast<InitListExpr>(E))
10239 Exprs.append(InitList->inits().begin(), InitList->inits().end());
10241 if (isa<ObjCBoxedExpr>(E))
10243 }
while (!Exprs.empty());
10258 class SequenceTree {
10262 unsigned Merged : 1;
10270 friend class SequenceTree;
10272 unsigned Index = 0;
10274 explicit Seq(
unsigned N) : Index(N) {}
10280 SequenceTree() { Values.push_back(
Value(0)); }
10281 Seq root()
const {
return Seq(0); }
10286 Seq allocate(Seq
Parent) {
10287 Values.push_back(
Value(Parent.Index));
10288 return Seq(Values.size() - 1);
10292 void merge(Seq S) {
10293 Values[S.Index].Merged =
true;
10299 bool isUnsequenced(Seq Cur, Seq Old) {
10300 unsigned C = representative(Cur.Index);
10301 unsigned Target = representative(Old.Index);
10302 while (C >= Target) {
10305 C = Values[
C].Parent;
10312 unsigned representative(
unsigned K) {
10313 if (Values[K].Merged)
10315 return Values[K].Parent = representative(Values[K].Parent);
10335 UK_ModAsSideEffect,
10337 UK_Count = UK_ModAsSideEffect + 1
10341 Expr *Use =
nullptr;
10342 SequenceTree::Seq Seq;
10348 Usage Uses[UK_Count];
10351 bool Diagnosed =
false;
10353 UsageInfo() =
default;
10355 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
10363 UsageInfoMap UsageMap;
10366 SequenceTree::Seq Region;
10381 struct SequencedSubexpression {
10382 SequencedSubexpression(SequenceChecker &Self)
10383 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
10384 Self.ModAsSideEffect = &ModAsSideEffect;
10387 ~SequencedSubexpression() {
10388 for (
auto &M : llvm::reverse(ModAsSideEffect)) {
10389 UsageInfo &U = Self.UsageMap[M.first];
10390 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
10391 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
10392 SideEffectUsage = M.second;
10394 Self.ModAsSideEffect = OldModAsSideEffect;
10397 SequenceChecker &Self;
10406 class EvaluationTracker {
10408 EvaluationTracker(SequenceChecker &Self)
10409 : Self(Self), Prev(Self.EvalTracker) {
10410 Self.EvalTracker =
this;
10413 ~EvaluationTracker() {
10414 Self.EvalTracker = Prev;
10416 Prev->EvalOK &= EvalOK;
10419 bool evaluate(
const Expr *E,
bool &Result) {
10427 SequenceChecker &Self;
10428 EvaluationTracker *Prev;
10429 bool EvalOK =
true;
10430 } *EvalTracker =
nullptr;
10434 Object getObject(
Expr *E,
bool Mod)
const {
10437 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
10438 return getObject(UO->getSubExpr(), Mod);
10440 if (BO->getOpcode() == BO_Comma)
10441 return getObject(BO->getRHS(), Mod);
10442 if (Mod && BO->isAssignmentOp())
10443 return getObject(BO->getLHS(), Mod);
10444 }
else if (
MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
10446 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
10447 return ME->getMemberDecl();
10448 }
else if (
DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10450 return DRE->getDecl();
10455 void addUsage(UsageInfo &UI, Object O,
Expr *Ref, UsageKind UK) {
10456 Usage &U = UI.Uses[UK];
10457 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
10458 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
10459 ModAsSideEffect->push_back(std::make_pair(O, U));
10466 void checkUsage(Object O, UsageInfo &UI,
Expr *Ref, UsageKind OtherKind,
10471 const Usage &U = UI.Uses[OtherKind];
10472 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
10476 Expr *ModOrUse = Ref;
10477 if (OtherKind == UK_Use)
10478 std::swap(Mod, ModOrUse);
10481 IsModMod ? diag::warn_unsequenced_mod_mod
10482 : diag::warn_unsequenced_mod_use)
10484 UI.Diagnosed =
true;
10487 void notePreUse(Object O,
Expr *Use) {
10488 UsageInfo &U = UsageMap[O];
10490 checkUsage(O, U, Use, UK_ModAsValue,
false);
10493 void notePostUse(Object O,
Expr *Use) {
10494 UsageInfo &U = UsageMap[O];
10495 checkUsage(O, U, Use, UK_ModAsSideEffect,
false);
10496 addUsage(U, O, Use, UK_Use);
10499 void notePreMod(Object O,
Expr *Mod) {
10500 UsageInfo &U = UsageMap[O];
10502 checkUsage(O, U, Mod, UK_ModAsValue,
true);
10503 checkUsage(O, U, Mod, UK_Use,
false);
10506 void notePostMod(Object O,
Expr *Use, UsageKind UK) {
10507 UsageInfo &U = UsageMap[O];
10508 checkUsage(O, U, Use, UK_ModAsSideEffect,
true);
10509 addUsage(U, O, Use, UK);
10514 :
Base(S.
Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
10518 void VisitStmt(
Stmt *S) {
10522 void VisitExpr(
Expr *E) {
10524 Base::VisitStmt(E);
10528 Object O = Object();
10544 SequenceTree::Seq LHS = Tree.allocate(Region);
10545 SequenceTree::Seq RHS = Tree.allocate(Region);
10546 SequenceTree::Seq OldRegion = Region;
10549 SequencedSubexpression SeqLHS(*
this);
10557 Region = OldRegion;
10569 Object O = getObject(BO->
getLHS(),
true);
10571 return VisitExpr(BO);
10581 if (isa<CompoundAssignOperator>(BO))
10586 if (isa<CompoundAssignOperator>(BO))
10587 notePostUse(O, BO);
10595 notePostMod(O, BO, SemaRef.
getLangOpts().CPlusPlus ? UK_ModAsValue
10596 : UK_ModAsSideEffect);
10600 VisitBinAssign(CAO);
10603 void VisitUnaryPreInc(
UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10604 void VisitUnaryPreDec(
UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10606 Object O = getObject(UO->
getSubExpr(),
true);
10608 return VisitExpr(UO);
10614 notePostMod(O, UO, SemaRef.
getLangOpts().CPlusPlus ? UK_ModAsValue
10615 : UK_ModAsSideEffect);
10618 void VisitUnaryPostInc(
UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10619 void VisitUnaryPostDec(
UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10621 Object O = getObject(UO->
getSubExpr(),
true);
10623 return VisitExpr(UO);
10627 notePostMod(O, UO, UK_ModAsSideEffect);
10636 EvaluationTracker Eval(*
this);
10638 SequencedSubexpression Sequenced(*
this);
10643 if (Eval.evaluate(BO->
getLHS(), Result)) {
10653 WorkList.push_back(BO->
getRHS());
10657 EvaluationTracker Eval(*
this);
10659 SequencedSubexpression Sequenced(*
this);
10664 if (Eval.evaluate(BO->
getLHS(), Result)) {
10668 WorkList.push_back(BO->
getRHS());
10675 EvaluationTracker Eval(*
this);
10677 SequencedSubexpression Sequenced(*
this);
10682 if (Eval.evaluate(CO->
getCond(), Result))
10690 void VisitCallExpr(
CallExpr *CE) {
10697 SequencedSubexpression Sequenced(*
this);
10698 Base::VisitCallExpr(CE);
10705 SequencedSubexpression Sequenced(*
this);
10708 return VisitExpr(CCE);
10712 SequenceTree::Seq
Parent = Region;
10716 Region = Tree.allocate(Parent);
10717 Elts.push_back(Region);
10723 for (
unsigned I = 0; I < Elts.size(); ++I)
10724 Tree.merge(Elts[I]);
10729 return VisitExpr(ILE);
10733 SequenceTree::Seq
Parent = Region;
10734 for (
unsigned I = 0; I < ILE->
getNumInits(); ++I) {
10737 Region = Tree.allocate(Parent);
10738 Elts.push_back(Region);
10744 for (
unsigned I = 0; I < Elts.size(); ++I)
10745 Tree.merge(Elts[I]);
10751 void Sema::CheckUnsequencedOperations(
Expr *E) {
10753 WorkList.push_back(E);
10754 while (!WorkList.empty()) {
10755 Expr *Item = WorkList.pop_back_val();
10756 SequenceChecker(*
this, Item, WorkList);
10761 bool IsConstexpr) {
10762 CheckImplicitConversions(E, CheckLoc);
10764 CheckUnsequencedOperations(E);
10766 CheckForIntOverflow(E);
10767 DiagnoseMisalignedMembers();
10780 if (
const auto *PointerTy = dyn_cast<PointerType>(PType)) {
10784 if (
const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
10788 if (
const auto *ParenTy = dyn_cast<ParenType>(PType)) {
10802 S.
Diag(Loc, diag::err_array_star_in_function_definition);
10811 bool CheckParameterNames) {
10812 bool HasInvalidParm =
false;
10819 if (!Param->isInvalidDecl() &&
10820 RequireCompleteType(Param->getLocation(), Param->getType(),
10821 diag::err_typecheck_decl_incomplete_type)) {
10822 Param->setInvalidDecl();
10823 HasInvalidParm =
true;
10828 if (CheckParameterNames &&
10829 Param->getIdentifier() ==
nullptr &&
10830 !Param->isImplicit() &&
10831 !getLangOpts().CPlusPlus)
10832 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
10839 QualType PType = Param->getOriginalType();
10851 if (!Param->isInvalidDecl()) {
10853 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
10858 MarkFunctionReferenced(Param->getLocation(), Destructor);
10859 DiagnoseUseOfDecl(Destructor, Param->
getLocation());
10869 if (
const auto *
Attr = Param->getAttr<PassObjectSizeAttr>())
10870 if (!Param->getType().isConstQualified())
10871 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
10875 return HasInvalidParm;
10882 if (
const auto *DRE = dyn_cast<DeclRefExpr>(E))
10885 if (
const auto *ME = dyn_cast<MemberExpr>(E))
10896 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.
getBegin()))
10905 if (!DestPtr)
return;
10911 if (DestAlign.
isOne())
return;
10915 if (!SrcPtr)
return;
10926 if (
auto *CE = dyn_cast<CastExpr>(Op)) {
10927 if (CE->getCastKind() == CK_ArrayToPointerDecay)
10928 SrcAlign =
getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
10929 }
else if (
auto *UO = dyn_cast<UnaryOperator>(Op)) {
10930 if (UO->getOpcode() == UO_AddrOf)
10931 SrcAlign =
getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
10934 if (SrcAlign >= DestAlign)
return;
10939 << static_cast<unsigned>(DestAlign.
getQuantity())
10950 if (Size != 1 || !ND)
return false;
10953 if (!FD)
return false;
10976 if (!RD)
return false;
10977 if (RD->
isUnion())
return false;
10978 if (
const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
10979 if (!CRD->isStandardLayout())
return false;
10983 const Decl *D = FD;
10985 if (isa<FieldDecl>(D))
10990 void Sema::CheckArrayAccess(
const Expr *BaseExpr,
const Expr *IndexExpr,
10992 bool AllowOnePastEnd,
bool IndexNegated) {
10997 const Type *EffectiveType =
11005 llvm::APSInt index;
11012 if (
const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
11013 ND = dyn_cast<NamedDecl>(DRE->getDecl());
11014 if (
const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
11015 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
11017 if (index.isUnsigned() || !index.isNegative()) {
11018 llvm::APInt size = ArrayTy->
getSize();
11019 if (!size.isStrictlyPositive())
11023 if (BaseType != EffectiveType) {
11025 uint64_t ptrarith_typesize = Context.
getTypeSize(EffectiveType);
11026 uint64_t array_typesize = Context.
getTypeSize(BaseType);
11028 if (!ptrarith_typesize) ptrarith_typesize = 1;
11029 if (ptrarith_typesize != array_typesize) {
11031 uint64_t ratio = array_typesize / ptrarith_typesize;
11034 if (ptrarith_typesize * ratio == array_typesize)
11035 size *= llvm::APInt(size.getBitWidth(), ratio);
11039 if (size.getBitWidth() > index.getBitWidth())
11040 index = index.zext(size.getBitWidth());
11041 else if (size.getBitWidth() < index.getBitWidth())
11042 size = size.zext(index.getBitWidth());
11048 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
11063 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
11066 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
11071 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
11073 DiagID = diag::warn_array_index_exceeds_bounds;
11075 DiagRuntimeBehavior(BaseExpr->
getLocStart(), BaseExpr,
11076 PDiag(DiagID) << index.toString(10,
true)
11077 << size.toString(10,
true)
11078 << (unsigned)size.getLimitedValue(~0U)
11081 unsigned DiagID = diag::warn_array_index_precedes_bounds;
11083 DiagID = diag::warn_ptr_arith_precedes_bounds;
11084 if (index.isNegative()) index = -index;
11087 DiagRuntimeBehavior(BaseExpr->
getLocStart(), BaseExpr,
11088 PDiag(DiagID) << index.toString(10,
true)
11095 dyn_cast<ArraySubscriptExpr>(BaseExpr))
11097 if (
const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
11098 ND = dyn_cast<
NamedDecl>(DRE->getDecl());
11099 if (
const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
11100 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
11105 PDiag(diag::note_array_index_out_of_bounds)
11109 void Sema::CheckArrayAccess(
const Expr *
expr) {
11110 int AllowOnePastEnd = 0;
11114 case Stmt::ArraySubscriptExprClass: {
11117 AllowOnePastEnd > 0);
11120 case Stmt::OMPArraySectionExprClass: {
11124 nullptr, AllowOnePastEnd > 0);
11127 case Stmt::UnaryOperatorClass: {
11143 case Stmt::ConditionalOperatorClass: {
11146 CheckArrayAccess(lhs);
11148 CheckArrayAccess(rhs);
11151 case Stmt::CXXOperatorCallExprClass: {
11152 const auto *OCE = cast<CXXOperatorCallExpr>(
expr);
11153 for (
const auto *Arg : OCE->arguments())
11154 CheckArrayAccess(Arg);
11167 struct RetainCycleOwner {
11171 bool Indirect =
false;
11173 RetainCycleOwner() =
default;
11175 void setLocsFrom(
Expr *e) {
11192 owner.Variable = var;
11194 owner.setLocsFrom(ref);
11202 switch (
cast->getCastKind()) {
11204 case CK_LValueBitCast:
11205 case CK_LValueToRValue:
11206 case CK_ARCReclaimReturnedObject:
11207 e =
cast->getSubExpr();
11224 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
11225 owner.Indirect =
true;
11229 if (
DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
11231 if (!var)
return false;
11235 if (
MemberExpr *member = dyn_cast<MemberExpr>(e)) {
11236 if (member->isArrow())
return false;
11239 e = member->getBase();
11248 if (!pre)
return false;
11251 if (!property->isRetaining() &&
11252 !(
property->getPropertyIvarDecl() &&
11253 property->getPropertyIvarDecl()->getType()
11257 owner.Indirect =
true;
11260 if (!owner.Variable)
11266 e =
const_cast<Expr*
>(cast<OpaqueValueExpr>(pre->
getBase())
11267 ->getSourceExpr());
11282 Expr *Capturer =
nullptr;
11283 bool VarWillBeReased =
false;
11287 Context(Context), Variable(variable) {}
11290 if (ref->
getDecl() == Variable && !Capturer)
11295 if (Capturer)
return;
11301 void VisitBlockExpr(
BlockExpr *block) {
11308 if (Capturer)
return;
11314 if (!Variable || VarWillBeReased || BinOp->
getOpcode() != BO_Assign)
11317 if (
const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
11318 if (DRE->getDecl() != Variable)
11322 llvm::APSInt
Value;
11335 assert(owner.Variable && owner.Loc.isValid());
11343 e = ME->getInstanceReceiver();
11346 e = e->IgnoreParenCasts();
11348 }
else if (
CallExpr *CE = dyn_cast<CallExpr>(e)) {
11353 if (FnI && FnI->
isStr(
"_Block_copy")) {
11364 FindCaptureVisitor visitor(S.
Context, owner.Variable);
11366 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
11370 RetainCycleOwner &owner) {
11372 assert(owner.Variable && owner.Loc.isValid());
11376 S.
Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
11377 << owner.Indirect << owner.Range;
11386 while (!str.empty() && str.front() ==
'_') str = str.substr(1);
11387 if (str.startswith(
"set"))
11388 str = str.substr(3);
11389 else if (str.startswith(
"add")) {
11391 if (sel.
getNumArgs() == 1 && str.startswith(
"addOperationWithBlock"))
11393 str = str.substr(3);
11398 if (str.empty())
return true;
11404 bool IsMutableArray = S.
NSAPIObj->isSubclassOfNSClass(
11407 if (!IsMutableArray) {
11414 S.
NSAPIObj->getNSArrayMethodKind(Sel);
11439 bool IsMutableDictionary = S.
NSAPIObj->isSubclassOfNSClass(
11442 if (!IsMutableDictionary) {
11449 S.
NSAPIObj->getNSDictionaryMethodKind(Sel);
11470 bool IsMutableSet = S.
NSAPIObj->isSubclassOfNSClass(
11474 bool IsMutableOrderedSet = S.
NSAPIObj->isSubclassOfNSClass(
11477 if (!IsMutableSet && !IsMutableOrderedSet) {
11516 int ArgIndex = *ArgOpt;
11524 if (
DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
11525 if (ArgRE->isObjCSelfExpr()) {
11527 diag::warn_objc_circular_container)
11528 << ArgRE->getDecl()->getName() << StringRef(
"super");
11538 if (
DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
11539 if (
DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
11540 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
11543 diag::warn_objc_circular_container)
11545 if (!ArgRE->isObjCSelfExpr()) {
11547 diag::note_objc_circular_container_declared_here)
11552 }
else if (
ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
11554 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
11557 diag::warn_objc_circular_container)
11560 diag::note_objc_circular_container_declared_here)
11575 RetainCycleOwner owner;
11581 owner.Variable = getCurMethodDecl()->getSelfDecl();
11588 for (
unsigned i = 0, e = msg->
getNumArgs(); i != e; ++i) {
11591 if (MD && MD->
parameters()[i]->hasAttr<NoEscapeAttr>())
11600 RetainCycleOwner owner;
11609 RetainCycleOwner Owner;
11623 Expr *RHS,
bool isProperty) {
11635 S.
Diag(Loc, diag::warn_arc_literal_assign)
11637 << (isProperty ? 0 : 1)
11645 Expr *RHS,
bool isProperty) {
11648 if (
cast->getCastKind() == CK_ARCConsumeObject) {
11649 S.
Diag(Loc, diag::warn_arc_retained_assign)
11651 << (isProperty ? 0 : 1)
11655 RHS =
cast->getSubExpr();
11697 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
11698 getCurFunction()->markSafeWeakUse(LHS);
11701 if (checkUnsafeAssigns(Loc, LHSType, RHS))
11721 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
11726 if (
cast->getCastKind() == CK_ARCConsumeObject) {
11727 Diag(Loc, diag::warn_arc_retained_property_assign)
11731 RHS =
cast->getSubExpr();
11755 bool StmtLineInvalid;
11758 if (StmtLineInvalid)
11761 bool BodyLineInvalid;
11764 if (BodyLineInvalid)
11768 if (StmtLine != BodyLine)
11779 if (CurrentInstantiationScope)
11792 Diag(NBody->
getSemiLoc(), diag::note_empty_body_on_separate_line);
11796 const Stmt *PossibleBody) {
11797 assert(!CurrentInstantiationScope);
11802 if (
const ForStmt *FS = dyn_cast<ForStmt>(S)) {
11803 StmtLoc = FS->getRParenLoc();
11804 Body = FS->getBody();
11805 DiagID = diag::warn_empty_for_body;
11806 }
else if (
const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
11807 StmtLoc = WS->getCond()->getSourceRange().getEnd();
11808 Body = WS->getBody();
11809 DiagID = diag::warn_empty_while_body;
11819 if (Diags.isIgnored(DiagID, NBody->
getSemiLoc()))
11837 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
11838 if (!ProbableTypo) {
11839 bool BodyColInvalid;
11840 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
11843 if (BodyColInvalid)
11846 bool StmtColInvalid;
11847 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
11850 if (StmtColInvalid)
11853 if (BodyCol > StmtCol)
11854 ProbableTypo =
true;
11857 if (ProbableTypo) {
11859 Diag(NBody->
getSemiLoc(), diag::note_empty_body_on_separate_line);
11868 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
11871 if (inTemplateInstantiation())
11888 RHSExpr = CE->
getArg(0);
11894 if (LHSDeclRef && RHSDeclRef) {
11895 if (!LHSDeclRef->
getDecl() || !RHSDeclRef->getDecl())
11901 Diag(OpLoc, diag::warn_self_move) << LHSExpr->
getType()
11911 const Expr *LHSBase = LHSExpr;
11912 const Expr *RHSBase = RHSExpr;
11915 if (!LHSME || !RHSME)
11918 while (LHSME && RHSME) {
11924 RHSBase = RHSME->getBase();
11931 if (LHSDeclRef && RHSDeclRef) {
11932 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11934 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11935 RHSDeclRef->getDecl()->getCanonicalDecl())
11938 Diag(OpLoc, diag::warn_self_move) << LHSExpr->
getType()
11944 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
11945 Diag(OpLoc, diag::warn_self_move) << LHSExpr->
getType()
11977 if (Bits1 != Bits2)
11989 if (
const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
11994 if (D1CXX->getNumBases() != D2CXX->
getNumBases())
11999 Base1 = D1CXX->bases_begin(),
12000 BaseEnd1 = D1CXX->bases_end(),
12003 ++Base1, ++Base2) {
12007 }
else if (
const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
12009 if (D2CXX->getNumBases() > 0)
12018 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
12022 if (Field1 != Field1End || Field2 != Field2End)
12032 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
12033 for (
auto *Field2 : RD2->
fields())
12034 UnmatchedFields.insert(Field2);
12036 for (
auto *Field1 : RD1->
fields()) {
12037 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
12038 I = UnmatchedFields.begin(),
12039 E = UnmatchedFields.end();
12041 for ( ; I != E; ++I) {
12043 bool Result = UnmatchedFields.erase(*I);
12053 return UnmatchedFields.empty();
12087 if (TC1 == Type::Enum) {
12089 cast<EnumType>(T1)->getDecl(),
12090 cast<EnumType>(T2)->getDecl());
12091 }
else if (TC1 == Type::Record) {
12096 cast<RecordType>(T1)->getDecl(),
12097 cast<RecordType>(T2)->getDecl());
12113 const ValueDecl **VD, uint64_t *MagicValue) {
12121 case Stmt::UnaryOperatorClass: {
12130 case Stmt::DeclRefExprClass: {
12131 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
12136 case Stmt::IntegerLiteralClass: {
12138 llvm::APInt MagicValueAPInt = IL->
getValue();
12139 if (MagicValueAPInt.getActiveBits() <= 64) {
12140 *MagicValue = MagicValueAPInt.getZExtValue();
12146 case Stmt::BinaryConditionalOperatorClass:
12147 case Stmt::ConditionalOperatorClass: {
12149 cast<AbstractConditionalOperator>(TypeExpr);
12161 case Stmt::BinaryOperatorClass: {
12164 TypeExpr = BO->
getRHS();
12193 bool &FoundWrongKind,
12195 FoundWrongKind =
false;
12200 uint64_t MagicValue;
12206 if (TypeTagForDatatypeAttr *I = VD->
getAttr<TypeTagForDatatypeAttr>()) {
12207 if (I->getArgumentKind() != ArgumentKind) {
12208 FoundWrongKind =
true;
12211 TypeInfo.
Type = I->getMatchingCType();
12224 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
12225 if (I == MagicValues->end())
12228 TypeInfo = I->second;
12234 bool LayoutCompatible,
12236 if (!TypeTagForDatatypeMagicValues)
12237 TypeTagForDatatypeMagicValues.reset(
12238 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
12241 (*TypeTagForDatatypeMagicValues)[Magic] =
12257 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
12258 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
12259 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
12260 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
12263 void Sema::CheckArgumentWithTypeTag(
const ArgumentWithTypeTagAttr *
Attr,
12264 const ArrayRef<const Expr *> ExprArgs,
12267 bool IsPointerAttr = Attr->getIsPointer();
12270 if (Attr->getTypeTagIdx() >= ExprArgs.size()) {
12272 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
12273 << 0 << Attr->getTypeTagIdx() + 1;
12276 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
12277 bool FoundWrongKind;
12280 TypeTagForDatatypeMagicValues.get(),
12281 FoundWrongKind, TypeInfo)) {
12282 if (FoundWrongKind)
12284 diag::warn_type_tag_for_datatype_wrong_kind)
12290 if (Attr->getArgumentIdx() >= ExprArgs.size()) {
12292 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
12293 << 1 << Attr->getArgumentIdx() + 1;
12296 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
12297 if (IsPointerAttr) {
12299 if (
const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
12300 if (ICE->getType()->isVoidPointerType() &&
12301 ICE->getCastKind() == CK_BitCast)
12302 ArgumentExpr = ICE->getSubExpr();
12310 if (TypeInfo.MustBeNull) {
12315 diag::warn_type_safety_null_pointer_required)
12323 QualType RequiredType = TypeInfo.Type;
12327 bool mismatch =
false;
12328 if (!TypeInfo.LayoutCompatible) {
12329 mismatch = !Context.
hasSameType(ArgumentType, RequiredType);
12350 Diag(ArgumentExpr->
getExprLoc(), diag::warn_type_safety_type_mismatch)
12351 << ArgumentType << ArgumentKind
12352 << TypeInfo.LayoutCompatible << RequiredType
12359 MisalignedMembers.emplace_back(E, RD, MD, Alignment);
12363 for (MisalignedMember &m : MisalignedMembers) {
12369 Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
12372 MisalignedMembers.clear();
12379 if (isa<UnaryOperator>(E) &&
12380 cast<UnaryOperator>(E)->
getOpcode() == UO_AddrOf) {
12381 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->
IgnoreParens();
12382 if (isa<MemberExpr>(Op)) {
12383 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
12384 MisalignedMember(Op));
12385 if (MA != MisalignedMembers.end() &&
12390 MisalignedMembers.erase(MA);
12411 bool AnyIsPacked =
false;
12413 QualType BaseType = ME->getBase()->getType();
12427 AnyIsPacked || (RD->
hasAttr<PackedAttr>() || MD->
hasAttr<PackedAttr>());
12428 ReverseMemberChain.push_back(FD);
12431 ME = dyn_cast<
MemberExpr>(ME->getBase()->IgnoreParens());
12433 assert(TopME &&
"We did not compute a topmost MemberExpr!");
12440 const auto *DRE = dyn_cast<
DeclRefExpr>(TopBase);
12444 if (!DRE && !isa<CXXThisExpr>(TopBase))
12451 if (ExpectedAlignment.
isOne())
12456 for (
auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
12463 ReverseMemberChain.back()->getParent()->getTypeForDecl());
12467 if (DRE && !TopME->
isArrow()) {
12470 CompleteObjectAlignment =
12475 if (Offset % ExpectedAlignment != 0 ||
12478 CompleteObjectAlignment < ExpectedAlignment) {
12489 for (
FieldDecl *FDI : ReverseMemberChain) {
12490 if (FDI->hasAttr<PackedAttr>() ||
12491 FDI->getParent()->hasAttr<PackedAttr>()) {
12499 assert(FD &&
"We did not find a packed FieldDecl!");
12500 Action(E, FD->
getParent(), FD, Alignment);
12504 void Sema::CheckAddressOfPackedMember(
Expr *rhs) {
12505 using namespace std::placeholders;
12507 RefersToMemberWithReducedAlignment(
12508 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*
this), _1,
ArgType getArgType(ASTContext &Ctx, bool IsObjCLiteral) const
Returns the builtin type that a data argument paired with this format specifier should have...
ObjCPropertyRefExpr - A dot-syntax expression to access an ObjC property.
The receiver is the instance of the superclass object.
static void diagnoseArrayStarInParamType(Sema &S, QualType PType, SourceLocation Loc)
static FormatStringType GetFormatStringType(const FormatAttr *Format)
bool isFloatingPoint() const
Defines the clang::ASTContext interface.
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
const BlockDecl * getBlockDecl() const
unsigned getTypeWidth(IntType T) const
Return the width (in bits) of the specified integer type enum.
bool isCallToStdMove() const
static std::pair< QualType, StringRef > shouldNotPrintDirectly(const ASTContext &Context, QualType IntendedTy, const Expr *E)
IntType getInt64Type() const
const char * getHeaderName(unsigned ID) const
If this is a library function that comes from a specific header, retrieve that header name...
const OptionalFlag & hasAlternativeForm() const
QualType withConst() const
Retrieves a version of this type with const applied.
An instance of this class is created to represent a function declaration or definition.
NamespaceDecl * getStdNamespace() const
const char * getSpelling() const
Expr ** getArgs()
Retrieve the call arguments.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
The receiver is an object instance.
unsigned getMemoryFunctionKind() const
Identify a memory copying or setting function.
static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, Expr *Constant, Expr *Other, const llvm::APSInt &Value, bool RhsConstant)
static void CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType, SourceLocation ReturnLoc)
CheckReturnStackAddr - Check if a return statement returns the address of a stack variable...
SourceLocation getRParenLoc() const
ObjCDictionaryElement getKeyValueElement(unsigned Index) const
SourceLocation getLocWithOffset(int Offset) const
Return a source location with the specified offset from this SourceLocation.
Smart pointer class that efficiently represents Objective-C method names.
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
PointerType - C99 6.7.5.1 - Pointer Declarators.
QualType getElementType() const
EvaluatedExprVisitor - This class visits 'Expr *'s.
QualType getPointeeType() const
static llvm::SmallPtrSet< MemberKind *, 1 > CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty)
A (possibly-)qualified type.
bool isBlockPointerType() const
StringKind getKind() const
bool isMemberPointerType() const
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
static bool CheckForReference(Sema &SemaRef, const Expr *E, const PartialDiagnostic &PD)
static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall)
OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different overload formats specified ...
const ScanfConversionSpecifier & getConversionSpecifier() const
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
bool hasValidThousandsGroupingPrefix() const
Selector getSelector() const
static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall)
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
unsigned getNumBases() const
Retrieves the number of base classes of this class.
static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2)
Check if two types are layout-compatible in C++11 sense.
Defines enumerations for the type traits support.
void print(raw_ostream &OS, const PrintingPolicy &Policy, const Twine &PlaceHolder=Twine(), unsigned Indentation=0) const
bool isSuperReceiver() const
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc...
const Expr * getInit(unsigned Init) const
bool containsNonAsciiOrNull() const
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>.
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false)
Perform unqualified name lookup starting from a given scope.
Stmt - This represents one statement.
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
static Optional< int > GetNSMutableArrayArgumentIndex(Sema &S, ObjCMessageExpr *Message)
Expr * getBitWidth() const
bool consumesDataArgument() const
FunctionType - C99 6.7.5.3 - Function Declarators.
SourceLocation getLocationOfByte(unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, const TargetInfo &Target, unsigned *StartToken=nullptr, unsigned *StartTokenByteOffset=nullptr) const
getLocationOfByte - Return a source location that points to the specified byte of this string literal...
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee...
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
EnumConstantDecl - An instance of this object exists for each enum constant that is defined...
bool isRealFloatingType() const
Floating point categories.
C Language Family Type Representation.
Defines the SourceManager interface.
ObjCInterfaceDecl * getReceiverInterface() const
Retrieve the Objective-C interface to which this message is being directed, if known.
void addConst()
Add the const type qualifier to this QualType.
bool isRecordType() const
static void AnalyzeAssignment(Sema &S, BinaryOperator *E)
Analyze the given simple or compound assignment for warning-worthy operations.
static InitializedEntity InitializeParameter(ASTContext &Context, const ParmVarDecl *Parm)
Create the initialization entity for a parameter.
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
const Type * getTypeForDecl() const
bool hasIrrelevantDestructor() const
Determine whether this class has a destructor which has no semantic effect.
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Decl - This represents one declaration (or definition), e.g.
bool hasLeadingEmptyMacro() const
static bool referToTheSameDecl(const Expr *E1, const Expr *E2)
Check if two expressions refer to the same declaration.
ParenExpr - This represents a parethesized expression, e.g.
const char * getCharacterData(SourceLocation SL, bool *Invalid=nullptr) const
Return a pointer to the start of the specified location in the appropriate spelling MemoryBuffer...
Expr * getFalseExpr() const
Expr * getLowerBound()
Get lower bound of array section.
const RecordDecl * getParent() const
getParent - Returns the parent of this field declaration, which is the struct in which this field is ...
The base class of the type hierarchy.
CanQualType getNSUIntegerType() const
NSDictionaryMethodKind
Enumerates the NSDictionary/NSMutableDictionary methods used to generate literals and to apply some c...
Represents an array type, per C99 6.7.5.2 - Array Declarators.
NamespaceDecl - Represent a C++ namespace.
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Represents a call to a C++ constructor.
Wrapper for source info for typedefs.
static AbsoluteValueKind getAbsoluteValueKind(QualType T)
QualType withConst() const
static void AnalyzeComparison(Sema &S, BinaryOperator *E)
Implements -Wsign-compare.
const TargetInfo & getTargetInfo() const
const NestedNameSpecifier * Specifier
A container of type source information.
static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call)
Returns true if pipe element type is different from the pointer.
SourceLocation getLocStart() const LLVM_READONLY
Represents a prvalue temporary that is written into memory so that a reference can bind to it...
static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount)
Checks that a call expression's argument count is the desired number.
float __ovld __cnfn distance(float p0, float p1)
Returns the distance between p0 and p1.
QualType getElementType() const
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
static unsigned changeAbsFunction(unsigned AbsKind, AbsoluteValueKind ValueKind)
bool isValidPointerAttrType(QualType T, bool RefOkay=false)
Determine if type T is a valid subject for a nonnull and similar attributes.
bool usesPositionalArg() const
bool isUnsignedIntegerType() const
Return true if this is an integer type that is unsigned, according to C99 6.2.5p6 [which returns true...
bool EvaluateAsInt(llvm::APSInt &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer...
SourceLocation getImmediateMacroCallerLoc(SourceLocation Loc) const
Gets the location of the immediate macro caller, one level up the stack toward the initial macro type...
VarDecl - An instance of this class is created to represent a variable declaration or definition...
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
QualType getReturnType() const
ScopeFlags
ScopeFlags - These are bitfields that are or'd together when creating a scope, which defines the sort...
DiagnosticsEngine & Diags
CompoundLiteralExpr - [C99 6.5.2.5].
unsigned getNumParams() const
bool isEnumeralType() const
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
const AstTypeMatcher< PointerType > pointerType
Matches pointer types, but does not match Objective-C object pointer types.
bool isFixed() const
Returns true if this is an Objective-C, C++11, or Microsoft-style enumeration with a fixed underlying...
APFloat & getComplexFloatReal()
const T * getAs() const
Member-template getAs<specific type>'.
Extra information about a function prototype.
const OptionalFlag & hasThousandsGrouping() const
LangAS
Defines the address space values used by the address space qualifier of QualType. ...
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, bool Canonical) const
Produce a unique representation of the given statement.
ObjCMethodDecl - Represents an instance or class method declaration.
Expr * IgnoreImplicit() LLVM_READONLY
IgnoreImplicit - Skip past any implicit AST nodes which might surround this expression.
bool isInvalidDecl() const
Like System, but searched after the system directories.
bool isAddrLabelDiff() const
ParmVarDecl - Represents a parameter to a function.
OpenCLOptions & getOpenCLOptions()
Defines the clang::Expr interface and subclasses for C++ expressions.
ObjCInterfaceDecl * NSDictionaryDecl
The declaration of the Objective-C NSDictionary class.
static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, IdentifierInfo *FnName, SourceLocation FnLoc, SourceLocation RParenLoc)
Takes the expression passed to the size_t parameter of functions such as memcmp, strncat, etc and warns if it's a comparison.
Parse and apply any fixits to the source.
bool isStandardLayoutType() const
Test if this type is a standard-layout type.
bool isVariableArrayType() const
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, Qualifiers::ObjCLifetime LT, Expr *RHS, bool isProperty)
ObjCPropertyDecl * getExplicitProperty() const
static bool requiresParensToAddCast(const Expr *E)
ArgType getArgType(ASTContext &Ctx) const
static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall, Expr *BlockArg, unsigned NumNonVarArgs)
OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all 'local void*' parameter of passed blo...
IdentifierInfo * getIdentifier() const
getIdentifier - Get the identifier that names this declaration, if there is one.
Base wrapper for a particular "section" of type source info.
Expr * IgnoreImpCasts() LLVM_READONLY
IgnoreImpCasts - Skip past any implicit casts which might surround this expression.
RecordDecl - Represents a struct/union/class.
static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, ParmVarDecl **LastParam=nullptr)
ExprResult UsualUnaryConversions(Expr *E)
UsualUnaryConversions - Performs various conversions that are common to most operators (C99 6...
DeclarationName getDeclName() const
getDeclName - Get the actual, stored name of the declaration, which may be a special name...
TypeSourceInfo * getIntegerTypeSourceInfo() const
Return the type source info for the underlying integer type, if no type source info exists...
bool isComplete() const
Returns true if this can be considered a complete type.
One of these records is kept for each identifier that is lexed.
std::unique_ptr< NSAPI > NSAPIObj
Caches identifiers/selectors for NSFoundation APIs.
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Expr * getFalseExpr() const
const TemplateArgument & get(unsigned Idx) const
Retrieve the template argument at a given index.
ShuffleVectorExpr - clang-specific builtin-in function __builtin_shufflevector.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
QualType getPointeeType() const
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
ArrayRef< QualType > getParamTypes() const
field_range fields() const
FieldDecl - An instance of this class is created by Sema::ActOnField to represent a member of a struc...
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op)
static int classifyConstantValue(Expr *Constant)
bool isReferenceType() const
void setArg(unsigned Arg, Expr *ArgExpr)
setArg - Set the specified argument.
The iterator over UnresolvedSets.
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
static DeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *D, bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc, QualType T, ExprValueKind VK, NamedDecl *FoundD=nullptr, const TemplateArgumentListInfo *TemplateArgs=nullptr)
Expr * getSourceExpr() const
The source expression of an opaque value expression is the expression which originally generated the ...
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Stmt * getBody() const override
getBody - If this Decl represents a declaration for a body of code, such as a function or method defi...
bool hasValidLeftJustified() const
std::unique_ptr< AtomicScopeModel > getScopeModel() const
Get atomic scope model.
CanQualType OCLReserveIDTy
static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2)
Check if two standard-layout unions are layout-compatible.
SourceLocation getQuestionLoc() const
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
ObjCArrayLiteral - used for objective-c array containers; as in: @["Hello", NSApp, [NSNumber numberWithInt:42]];.
unsigned getCharByteWidth() const
bool isAtLeastAsQualifiedAs(QualType Other) const
Determine whether this type is at least as qualified as the other given type, requiring exact equalit...
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
void DiagnoseEmptyLoopBody(const Stmt *S, const Stmt *PossibleBody)
Warn if a for/while loop statement S, which is followed by PossibleBody, has a suspicious null statem...
static Optional< int > GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message)
An r-value expression (a pr-value in the C++11 taxonomy) produces a temporary value.
ArrayRef< ParmVarDecl * > parameters() const
bool isUnarySelector() const
bool hasValidPlusPrefix() const
Describes an C or C++ initializer list.
bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx) const
EvaluateAsBooleanCondition - Return true if this is a constant which we we can fold and convert to a ...
static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, unsigned Start, unsigned End)
bool isBitField() const
Determines whether this field is a bitfield.
ForStmt - This represents a 'for (init;cond;inc)' stmt.
unsigned getLength() const
static bool isEqualityOp(Opcode Opc)
Represents the results of name lookup.
bool EvaluateAsFloat(llvm::APFloat &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects) const
EvaluateAsFloat - Return true if this is a constant which we can fold and convert to a floating point...
ObjCMethodDecl * getCurMethodDecl()
getCurMethodDecl - If inside of a method body, this returns a pointer to the method decl for the meth...
CharUnits - This is an opaque type for sizes expressed in character units.
APValue Val
Val - This is the value the expression can be folded to.
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified...
bool hasValidPrecision() const
bool isOne() const
isOne - Test whether the quantity equals one.
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
static bool isNonNullType(ASTContext &ctx, QualType type)
Determine whether the given type has a non-null nullability annotation.
unsigned LayoutCompatible
If true, Type should be compared with other expression's types for layout-compatibility.
PropertyAttributeKind getPropertyAttributes() const
Represents a typeof (or typeof) expression (a GCC extension).
const clang::PrintingPolicy & getPrintingPolicy() const
A builtin binary operation expression such as "x + y" or "x <= y".
unsigned getNumPositiveBits() const
Returns the width in bits required to store all the non-negative enumerators of this enum...
bool isComplexFloat() const
QualType getExceptionObjectType(QualType T) const
unsigned getSpellingLineNumber(SourceLocation Loc, bool *Invalid=nullptr) const
bool isComplexInt() const
Defines the Diagnostic-related interfaces.
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
Expr * IgnoreParenCasts() LLVM_READONLY
IgnoreParenCasts - Ignore parentheses and casts.
ObjCStringLiteral, used for Objective-C string literals i.e.
Values of this type can never be null.
void printPretty(raw_ostream &OS, PrinterHelper *Helper, const PrintingPolicy &Policy, unsigned Indentation=0, const ASTContext *Context=nullptr) const
Scope - A scope is a transient data structure that is used while parsing the program.
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
field_iterator field_begin() const
unsigned getBitWidthValue(const ASTContext &Ctx) const
bool isNothrow(const ASTContext &Ctx, bool ResultIfDependent=false) const
Determine whether this function type has a non-throwing exception specification.
NSSetMethodKind
Enumerates the NSMutableSet/NSOrderedSet methods used to apply some checks.
static QualType GetExprType(const Expr *E)
bool isMacroBodyExpansion(SourceLocation Loc) const
Tests whether the given source location represents the expansion of a macro body. ...
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
base_class_iterator bases_begin()
SourceLocation getLocEnd() const LLVM_READONLY
SourceLocation getSpellingLoc(SourceLocation Loc) const
Given a SourceLocation object, return the spelling location referenced by the ID. ...
const LangOptions & getLangOpts() const
NestedNameSpecifierLoc getQualifierLoc() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name, with source-location information.
bool isTypeDependent() const
isTypeDependent - Determines whether this expression is type-dependent (C++ [temp.dep.expr]), which means that its type could change from one template instantiation to the next.
bool isScalarType() const
AssignConvertType CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS, bool Diagnose=true, bool DiagnoseCFAudited=false, bool ConvertRHS=true)
Check assignment constraints for an assignment of RHS to LHSType.
An ordinary object is located at an address in memory.
SmallVector< BoundNodes, 1 > match(MatcherT Matcher, const NodeT &Node, ASTContext &Context)
Returns the results of matching Matcher on Node.
static const CXXRecordDecl * getContainedDynamicClass(QualType T, bool &IsContained)
Determine whether the given type is or contains a dynamic class type (e.g., whether it has a vtable)...
bool fixType(QualType QT, QualType RawQT, const LangOptions &LangOpt, ASTContext &Ctx)
static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall)
OpenCL C v2.0, s6.13.17.6 - Check the argument to the get_kernel_work_group_size and get_kernel_prefe...
Member name lookup, which finds the names of class/struct/union members.
SourceLocation getTypeSpecStartLoc() const
Expression is a GNU-style __null constant.
static void diagnoseRetainCycle(Sema &S, Expr *capturer, RetainCycleOwner &owner)
static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E)
Analyze the operands of the given comparison.
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
APSInt & getComplexIntReal()
CanQualType UnsignedCharTy
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall)
Iterator for iterating over Stmt * arrays that contain only Expr *.
const OptionalFlag & hasLeadingZeros() const
bool hasUnsignedIntegerRepresentation() const
Determine whether this type has an unsigned integer representation of some sort, e.g., it is an unsigned integer type or a vector.
std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const
This object can be modified without requiring retains or releases.
param_iterator param_begin()
APValue & getVectorElt(unsigned I)
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
unsigned getFlags() const
getFlags - Return the flags for this scope.
Provides definitions for the various language-specific address spaces.
Decl * getNextDeclInContext()
OpenMP 4.0 [2.4, Array Sections].
const OptionalFlag & hasPlusPrefix() const
ConditionalOperator - The ?: ternary operator.
Sema - This implements semantic analysis and AST building for C.
StringRef getString() const
bool isPromotableIntegerType() const
More type predicates useful for type checking/promotion.
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Represents a prototype with parameter type info, e.g.
bool isDynamicClass() const
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any...
CastKind
CastKind - The kind of operation required for a conversion.
QualType getPromotionType() const
getPromotionType - Return the integer type that enumerators should promote to.
SourceLocation getLocEnd() const LLVM_READONLY
static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx)
Returns true if pipe element type is different from the pointer.
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand...
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to...
static const Expr * EvalVal(const Expr *E, SmallVectorImpl< const DeclRefExpr *> &refVars, const Decl *ParentDecl)
EvalVal - This function is complements EvalAddr in the mutual recursion.
const char * getName(unsigned ID) const
Return the identifier name for the specified builtin, e.g.
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
SourceLocation getLocation() const
bool isEnabled(llvm::StringRef Ext) const
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
TypeSourceInfo * getTypeSourceInfo() const
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx, SmallVectorImpl< PartialDiagnosticAt > *Diag=nullptr) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
Scope * getCurScope() const
Retrieve the parser's current scope.
static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext)
Diagnose an implicit cast from a floating point value to an integer value.
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
Exposes information about the current target.
NSArrayMethodKind
Enumerates the NSArray/NSMutableArray methods used to generate literals and to apply some checks...
Defines the TargetCXXABI class, which abstracts details of the C++ ABI that we're targeting...
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr...
static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl, CallExpr *TheCall, unsigned SizeIdx, unsigned DstSizeIdx)
QualType getVectorType(QualType VectorType, unsigned NumElts, VectorType::VectorKind VecKind) const
Return the unique reference to a vector type of the specified element type and size.
BlockDecl - This represents a block literal declaration, which is like an unnamed FunctionDecl...
ValueDecl - Represent the declaration of a variable (in which case it is an lvalue) a function (in wh...
Expr - This represents one expression.
Defines the clang::LangOptions interface.
const OptionalFlag & isLeftJustified() const
Allow any unmodeled side effect.
Represents a character-granular source range.
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
static bool compare(const PathDiagnostic &X, const PathDiagnostic &Y)
void EvaluateForOverflow(const ASTContext &Ctx) const
const FunctionProtoType * T
static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, SourceLocation CC)
virtual bool hasSjLjLowering() const
Controls if __builtin_longjmp / __builtin_setjmp can be lowered to llvm.eh.sjlj.longjmp / llvm...
const T * castAs() const
Member-template castAs<specific type>.
bool isObjCRetainableType() const
ObjCStringFormatFamily getObjCFStringFormattingFamily() const
static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg)
OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local void*, which is a requirem...
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Represents a C++ destructor within a class.
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
unsigned getNumInits() const
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
This scope corresponds to an SEH except.
Defines an enumeration for C++ overloaded operators.
const Expr * getCallee() const
bool isNullPtrType() const
bool hasValidLeadingZeros() const
field_iterator field_end() const
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
StringRef getNameForSlot(unsigned argIndex) const
Retrieve the name at a given position in the selector.
ObjCDictionaryLiteral - AST node to represent objective-c dictionary literals; as in:"name" : NSUserN...
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
DeclContext * getDeclContext()
CXXRecordDecl * getDefinition() const
bool isAnyComplexType() const
void setObjectKind(ExprObjectKind Cat)
setObjectKind - Set the object kind produced by this expression.
bool refersToEnclosingVariableOrCapture() const
Does this DeclRefExpr refer to an enclosing local or a captured variable?
void removeLocalVolatile()
char __ovld __cnfn min(char x, char y)
Returns y if y < x, otherwise it returns x.
Defines the clang::TypeLoc interface and its subclasses.
const ParmVarDecl * getParamDecl(unsigned i) const
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char, signed char, short, int, long..], or an enum decl which has a signed representation.
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
Expr * getElement(unsigned Index)
getElement - Return the Element at the specified index.
static void CheckNonNullArguments(Sema &S, const NamedDecl *FDecl, const FunctionProtoType *Proto, ArrayRef< const Expr *> Args, SourceLocation CallSiteLoc)
void setValueKind(ExprValueKind Cat)
setValueKind - Set the value kind produced by this expression.
bool fixType(QualType QT, const LangOptions &LangOpt, ASTContext &Ctx, bool IsObjCLiteral)
Changes the specifier and length according to a QualType, retaining any flags or options.
virtual bool validateCpuSupports(StringRef Name) const
static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call)
An expression that sends a message to the given Objective-C object or class.
SourceLocation getRBracketLoc() const
SourceLocation getEnd() const
UnaryOperator - This represents the unary-expression's (except sizeof and alignof), the postinc/postdec operators from postfix-expression, and various extensions.
static void 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)
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Represents a GCC generic vector type.
ReceiverKind getReceiverKind() const
Determine the kind of receiver that this message is being sent to.
static OpenCLAccessAttr * getOpenCLArgAccess(const Decl *D)
Returns OpenCL access qual.
ArraySizeModifier getSizeModifier() const
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
unsigned getNumArgs() const
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
bool capturesVariable(const VarDecl *var) const
Expr * getTrueExpr() const
APSInt & getComplexIntImag()
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
unsigned getPresumedLineNumber(SourceLocation Loc, bool *Invalid=nullptr) const
static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, SourceLocation CContext, unsigned diag, bool pruneControlFlow=false)
Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style cast in C++ (C++ [expr.cast]), which uses the syntax (Type)expr.
QualType withoutLocalFastQualifiers() const
bool isNull() const
Return true if this QualType doesn't point to a type yet.
ImplicitParamDecl * getSelfDecl() const
static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, const NamedDecl *ND)
Check whether this array fits the idiom of a size-one tail padded array member of a struct...
static StringRef getIdentifier(const Token &Tok)
static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, bool IsPolyUnsigned, bool IsInt64Long)
getNeonEltType - Return the QualType corresponding to the elements of the vector type specified by th...
CanQualType getNSIntegerType() const
CallingConv
CallingConv - Specifies the calling convention that a function uses.
static const Expr * getStrlenExprArg(const Expr *E)
static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall)
SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, ASTContext &Context)
static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, const ValueDecl **VD, uint64_t *MagicValue)
Given a type tag expression find the type tag itself.
static CharSourceRange getCharRange(SourceRange R)
bool isVoidPointerType() const
bool isConstQualified() const
Determine whether this type is const-qualified.
static const Expr * EvalAddr(const Expr *E, SmallVectorImpl< const DeclRefExpr *> &refVars, const Decl *ParentDecl)
EvalAddr - EvalAddr and EvalVal are mutually recursive functions that check if the expression in a re...
RecordDecl * getDecl() const
std::pair< const IdentifierInfo *, uint64_t > TypeTagMagicValue
A pair of ArgumentKind identifier and magic value.
static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn)
Check that the user is calling the appropriate va_start builtin for the target and calling convention...
static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call)
SourceLocation getLocStart() const LLVM_READONLY
EltType getEltType() const
Defines the clang::OpenCLOptions class.
static bool IsStdFunction(const FunctionDecl *FDecl, const char(&Str)[StrLen])
There is no lifetime qualification on this type.
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class...
Enumerates target-specific builtins in their own namespaces within namespace clang.
ConvertVectorExpr - Clang builtin function __builtin_convertvector This AST node provides support for...
unsigned getNumArgs() const
Return the number of actual arguments in this message, not counting the receiver. ...
Assigning into this object requires the old value to be released and the new value to be retained...
QualType getCanonicalType() const
not a target-specific vector type
ActionResult - This structure is used while parsing/acting on expressions, stmts, etc...
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
bool isImplicitProperty() const
bool isInstantiationDependent() const
Whether this expression is instantiation-dependent, meaning that it depends in some way on a template...
void DiagnoseMisalignedMembers()
Diagnoses the current set of gathered accesses.
static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2)
Check if two standard-layout structs are layout-compatible.
void RefersToMemberWithReducedAlignment(Expr *E, llvm::function_ref< void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> Action)
This function calls Action when it determines that E designates a misaligned member due to the packed...
ASTContext & getASTContext() const
static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner)
Consider whether capturing the given variable can possibly lead to a retain cycle.
static void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType, Expr *Element, unsigned ElementKind)
Check a single element within a collection literal against the target element type.
NullPointerConstantKind isNullPointerConstant(ASTContext &Ctx, NullPointerConstantValueDependence NPC) const
isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to a Null pointer constant...
Encodes a location in the source.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
static void CheckConditionalOperator(Sema &S, ConditionalOperator *E, SourceLocation CC, QualType T)
bool CheckParmsForFunctionDef(ArrayRef< ParmVarDecl *> Parameters, bool CheckParameterNames)
Helpers for dealing with blocks and functions.
static const Expr * getSizeOfExprArg(const Expr *E)
If E is a sizeof expression, returns its argument expression, otherwise returns NULL.
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums...
SourceLocation getOperatorLoc() const
std::pair< SourceLocation, SourceLocation > getImmediateExpansionRange(SourceLocation Loc) const
Return the start/end of the expansion information for an expansion location.
LangAS getAddressSpace() const
Return the address space of this type.
Expression is not a Null pointer constant.
VarArgKind isValidVarArgType(const QualType &Ty)
Determine the degree of POD-ness for an expression.
Expr * getSubExpr() const
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
void checkRetainCycles(ObjCMessageExpr *msg)
checkRetainCycles - Check whether an Objective-C message send might create an obvious retain cycle...
bool hasValidSpacePrefix() const
static const Expr * ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx)
CastKind getCastKind() const
std::string getNameAsString() const
getNameAsString - Get a human-readable name for the declaration, even if it is one of the special kin...
unsigned getNumElements() const
getNumElements - Return number of elements of objective-c dictionary literal.
ExprObjectKind
A further classification of the kind of object referenced by an l-value or x-value.
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Represents a static or instance method of a struct/union/class.
static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool)
const ConstantArrayType * getAsConstantArrayType(QualType T) const
ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall)
SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
static bool CheckNonNullExpr(Sema &S, const Expr *Expr)
Checks if a the given expression evaluates to null.
SourceLocation getSuperLoc() const
Retrieve the location of the 'super' keyword for a class or instance message to 'super', otherwise an invalid source location.
const ParmVarDecl * getParamDecl(unsigned i) const
static void checkObjCArrayLiteral(Sema &S, QualType TargetType, ObjCArrayLiteral *ArrayLiteral)
Check an Objective-C array literal being converted to the given target type.
static void DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, const NamedDecl *FDecl, Expr **Args, unsigned NumArgs)
Diagnose use of s directive in an NSString which is being passed as formatting string to formatting m...
static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, SourceLocation CC, bool &ICContext)
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*, __atomic_load, __atomic_store, and __atomic_compare_exchange_*, for the similarly-named C++11 instructions, and __c11 variants for <stdatomic.h>, and corresponding __opencl_atomic_* for OpenCL 2.0.
Specifies that a value-dependent expression should be considered to never be a null pointer constant...
static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC)
CheckBoolLikeConversion - Check conversion of given expression to boolean.
bool isValueDependent() const
isValueDependent - Determines whether this expression is value-dependent (C++ [temp.dep.constexpr]).
Look up any declaration with any name.
bool isKnownToHaveBooleanValue() const
isKnownToHaveBooleanValue - Return true if this is an integer expression that is known to return 0 or...
bool isObjCObjectPointerType() const
bool isAnyPointerType() const
static std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range)
static bool isBlockPointer(Expr *Arg)
bool FormatStringHasSArg(const StringLiteral *FExpr)
Represents one property declaration in an Objective-C interface.
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
bool isFunctionProtoType() const
void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, uint64_t MagicValue, QualType Type, bool LayoutCompatible, bool MustBeNull)
Register a magic integral constant to be used as a type tag.
TypeClass getTypeClass() const
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
static bool isLogicalOp(Opcode Opc)
bool hasCStrMethod(const Expr *E)
Check to see if a given expression could have '.c_str()' called on it.
const ObjCMethodDecl * getMethodDecl() const
static bool IsEnumConstOrFromMacro(Sema &S, Expr *E)
bool isVectorType() const
virtual bool validateCpuIs(StringRef Name) const
Assigning into this object requires a lifetime extension.
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
SourceLocation getLocStart() const LLVM_READONLY
static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call)
We are currently in the filter expression of an SEH except block.
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
LLVM_READONLY bool isLowercase(unsigned char c)
Return true if this character is a lowercase ASCII letter: [a-z].
static StringRef getImmediateMacroName(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Retrieve the name of the immediate macro expansion.
static StringRef getImmediateMacroNameForDiagnostics(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Retrieve the name of the immediate macro expansion.
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
const llvm::fltSemantics & getFloatTypeSemantics(QualType T) const
Return the APFloat 'semantics' for the specified scalar floating point type.
const PrintfConversionSpecifier & getConversionSpecifier() const
CompoundAssignOperator - For compound assignments (e.g.
Defines various enumerations that describe declaration and type specifiers.
StringRef getName() const
Return the actual identifier string.
Expr * getInstanceReceiver()
Returns the object expression (receiver) for an instance message, or null for a message that is not a...
CanQualType UnsignedShortTy
QualType getTypedefType(const TypedefNameDecl *Decl, QualType Canon=QualType()) const
Return the unique reference to the type for the specified typedef-name decl.
Base class for declarations which introduce a typedef-name.
QualType withVolatile() const
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
NullStmt - This is the null statement ";": C99 6.8.3p3.
Dataflow Directional Tag Classes.
bool isValid() const
Return true if this is a valid SourceLocation object.
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
SourceLocation getLocation() const
EvalResult is a struct with detailed info about an evaluated expression.
PropertyAttributeKind getPropertyAttributesAsWritten() const
static bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx)
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
const Scope * getParent() const
getParent - Return the scope that this is nested in.
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return 0.
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_RValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CCK_ImplicitConversion)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
ArrayRef< QualType > getTypeArgs() const
Retrieve the type arguments for this type.
bool isSEHExceptScope() const
Determine whether this scope is a SEH '__except' block.
static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, SourceLocation InitLoc)
Analyzes an attempt to assign the given value to a bitfield.
ObjCLiteralKind CheckLiteralKind(Expr *FromE)
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the current evaluation context.
BinaryOperator::Opcode getOpcode(const SymExpr *SE)
CanQualType UnsignedLongLongTy
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
static QualType getAbsoluteValueArgumentType(ASTContext &Context, unsigned AbsType)
SourceLocation getSemiLoc() const
bool areArgsDestroyedLeftToRightInCallee() const
Are arguments to a call destroyed left to right in the callee? This is a fundamental language change...
DeclarationName - The name of a declaration.
StmtClass getStmtClass() const
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
bool isBooleanType() const
bool isListInitialization() const
Whether this constructor call was written as list-initialization.
Expression is a Null pointer constant built from a zero integer expression that is not a simple...
U cast(CodeGen::Address addr)
static bool isSetterLikeSelector(Selector sel)
Check for a keyword selector that starts with the word 'add' or 'set'.
A set of unresolved declarations.
SourceLocation getLocStart() const LLVM_READONLY
SourceLocation getLocStart() const LLVM_READONLY
EnumDecl - Represents an enum.
Expression is a C++11 nullptr.
bool isIntegerConstantExpr(llvm::APSInt &Result, const ASTContext &Ctx, SourceLocation *Loc=nullptr, bool isEvaluated=true) const
isIntegerConstantExpr - Return true if this expression is a valid integer constant expression...
const OptionalFlag & isPrivate() const
Flags to identify the types for overloaded Neon builtins.
QualType getCallReturnType(const ASTContext &Ctx) const
getCallReturnType - Get the return type of the call expr.
void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange)
CheckCastAlign - Implements -Wcast-align, which warns when a pointer cast increases the alignment req...
static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner)
static bool IsSameCharType(QualType T1, QualType T2)
specific_decl_iterator - Iterates over a subrange of declarations stored in a DeclContext, providing only those that are of type SpecificDecl (or a class derived from it).
virtual bool hasFeature(StringRef Feature) const
Determine whether the given target has the given feature.
ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
SemaConvertVectorExpr - Handle __builtin_convertvector.
Expr * IgnoreParenImpCasts() LLVM_READONLY
IgnoreParenImpCasts - Ignore parentheses and implicit casts.
param_iterator param_end()
static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall)
llvm::APInt getValue() const
Represents a pointer to an Objective C object.
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
bool hasValidAlternativeForm() const
unsigned getByteLength() const
FileID getFileID(SourceLocation SpellingLoc) const
Return the FileID for a SourceLocation.
unsigned getIntWidth(QualType T) const
static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, CallExpr *Call)
static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, unsigned AbsFunctionKind)
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Complex values, per C99 6.2.5p11.
bool isMacroArgExpansion(SourceLocation Loc, SourceLocation *StartLoc=nullptr) const
Tests whether the given source location represents a macro argument's expansion into the function-lik...
static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call)
bool hasValidFieldWidth() const
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
QualType getCanonicalTypeInternal() const
unsigned getNumElements() const
getNumElements - Return number of elements of objective-c array literal.
AbstractConditionalOperator - An abstract base class for ConditionalOperator and BinaryConditionalOpe...
bool isReserveIDT() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntType)
Diagnose integer type and any valid implicit conversion to it.
CanQualType UnsignedLongTy
static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call)
bool hasNonTrivialObjCLifetime() const
const llvm::APInt & getSize() const
uint64_t getCharWidth() const
Return the size of the character type, in bits.
FunctionDecl * getCurFunctionDecl()
getCurFunctionDecl - If inside of a function body, this returns a pointer to the function decl for th...
bool isAtomicType() const
static bool isKnownToHaveUnsignedValue(Expr *E)
bool isFunctionType() const
static unsigned RFT(unsigned t, bool shift=false, bool ForceQuad=false)
bool isObjCQualifiedIdType() const
SourceLocation getLocStart() const LLVM_READONLY
TypeSourceInfo * getTypeSourceInfo() const
static void checkObjCDictionaryLiteral(Sema &S, QualType TargetType, ObjCDictionaryLiteral *DictionaryLiteral)
Check an Objective-C dictionary literal being converted to the given target type. ...
const OptionalAmount & getPrecision() const
static bool isAdditiveOp(Opcode Opc)
static bool IsSameFloatAfterCast(const llvm::APFloat &value, const llvm::fltSemantics &Src, const llvm::fltSemantics &Tgt)
Checks whether the given value, which currently has the given source semantics, has the same value wh...
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
ObjCInterfaceDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this Objective-C class.
static bool GetMatchingCType(const IdentifierInfo *ArgumentKind, const Expr *TypeExpr, const ASTContext &Ctx, const llvm::DenseMap< Sema::TypeTagMagicValue, Sema::TypeTagData > *MagicValues, bool &FoundWrongKind, Sema::TypeTagData &TypeInfo)
Retrieve the C type corresponding to type tag TypeExpr.
The template argument is a type.
static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, BinaryOperatorKind BinOpKind, bool AddendIsRight)
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
const OptionalFlag & isPublic() const
ObjCInterfaceDecl * NSArrayDecl
The declaration of the Objective-C NSArray class.
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream...
SourceLocation getLocEnd() const LLVM_READONLY
const Expr * getBase() const
SourceLocation getExprLoc() const LLVM_READONLY
Optional< NullabilityKind > getNullability(const ASTContext &context) const
Determine the nullability of the given type.
static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, unsigned AbsKind, QualType ArgType)
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat]...
static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, SourceLocation CC)
Represents a base class of a C++ class.
char __ovld __cnfn max(char x, char y)
Returns y if x < y, otherwise it returns x.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex)
checkBuiltinArgument - Given a call to a builtin function, perform normal type-checking on the given ...
ObjCIvarRefExpr - A reference to an ObjC instance variable.
void DiscardMisalignedMemberAddress(const Type *T, Expr *E)
This function checks if the expression is in the sef of potentially misaligned members and it is conv...
bool isObjCObjectType() const
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types...
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
const OptionalFlag & hasSpacePrefix() const
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
static void CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC, bool *ICContext=nullptr)
uint64_t getFieldOffset(const ValueDecl *FD) const
Get the offset of a FieldDecl or IndirectFieldDecl, in bits.
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
Reading or writing from this object requires a barrier call.
static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate.h) and friends (in DeclFriend.h).
QualType getParamType(unsigned i) const
Expression is a Null pointer constant built from a literal zero.
bool typesAreCompatible(QualType T1, QualType T2, bool CompareUnqualified=false)
Compatibility predicates used to check assignment expressions.
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)
static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, Scope::ScopeFlags NeededScopeFlags, unsigned DiagID)
void DiagnoseEmptyStmtBody(SourceLocation StmtLoc, const Stmt *Body, unsigned DiagID)
Emit DiagID if statement located on StmtLoc has a suspicious null statement as a Body, and it is located on the same line.
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
static bool HasEnumType(Expr *E)
Defines the clang::SourceLocation class and associated facilities.
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Provides definitions for the atomic synchronization scopes.
SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL, unsigned ByteNo) const
bool hasUnaligned() const
APFloat & getComplexFloatImag()
bool hasSignedIntegerRepresentation() const
Determine whether this type has an signed integer representation of some sort, e.g., it is an signed integer type or a vector.
Represents a C++ struct/union/class.
Compatible - the types are compatible according to the standard.
Expr * getTrueExpr() const
unsigned getBuiltinID() const
Returns a value indicating whether this function corresponds to a builtin function.
static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr, SourceLocation CallSiteLoc)
bool hasIntegerRepresentation() const
Determine whether this type has an integer representation of some sort, e.g., it is an integer type o...
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
unsigned getNumNegativeBits() const
Returns the width in bits required to store all the negative enumerators of this enum.
bool consumesDataArgument() const
ObjCIvarDecl - Represents an ObjC instance variable.
WhileStmt - This represents a 'while' stmt.
static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall)
SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
Builtin::Context & BuiltinInfo
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC)
AnalyzeImplicitConversions - Find and report any interesting implicit conversions in the given expres...
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string...
This class is used for builtin types like 'int'.
static QualType getSizeOfArgType(const Expr *E)
If E is a sizeof expression, returns its argument type.
SourceManager & getSourceManager() const
QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error, unsigned *IntegerConstantArgs=nullptr) const
Return the type for the specified builtin.
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
StringLiteral - This represents a string literal expression, e.g.
Defines the clang::TargetInfo interface.
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
QualType getIntegerType() const
getIntegerType - Return the integer type this enum decl corresponds to.
StringRef getName() const
getName - Get the name of identifier for this declaration as a StringRef.
static Decl::Kind getKind(const Decl *D)
void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, SourceLocation OpLoc)
Warn if a value is moved to itself.
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
A reference to a declared variable, function, enum, etc.
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl)
static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall)
Check that the argument to __builtin_addressof is a glvalue, and set the result type to the correspon...
bool isPointerType() const
SourceManager & SourceMgr
bool isTSBuiltin(unsigned ID) const
Return true if this function is a target-specific builtin.
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS)
checkUnsafeExprAssigns - Check whether +1 expr is being assigned to weak/__unsafe_unretained expressi...
bool isInSystemMacro(SourceLocation loc) const
Returns whether Loc is expanded from a macro in a system header.
bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS)
checkUnsafeAssigns - Check whether +1 expr is being assigned to weak/__unsafe_unretained type...
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
An l-value expression is a reference to an object with independent storage.
static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc)
bool isFloatingType() const
const Expr * getBase() const
A trivial tuple used to represent a source range.
NamedDecl - This represents a decl with a name.
static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction)
void DiagnoseAlwaysNonNullPointer(Expr *E, Expr::NullPointerConstantKind NullType, bool IsEqual, SourceRange Range)
Diagnose pointers that are always non-null.
static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth)
Pseudo-evaluate the given integer expression, estimating the range of values it might take...
static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, Expr *RHS, bool isProperty)
bool isConstant(const ASTContext &Ctx) const
static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth)
static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall)
Check that the first argument to __builtin_annotation is an integer and the second argument is a non-...
Describes an entity that is being initialized.
bool isFunctionPointerType() const
bool isInStdNamespace() const
bool isInstanceMessage() const
Determine whether this is an instance message to either a computed object or to super.
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
SourceLocation getLocStart() const LLVM_READONLY
static bool isComparisonOp(Opcode Opc)
SourceLocation getBegin() const
const LangOptions & getLangOpts() const
static Expr * findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner)
Check whether the given argument is a block which captures a variable.
static Optional< int > GetNSMutableDictionaryArgumentIndex(Sema &S, ObjCMessageExpr *Message)
static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall)
bool AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const
Represents the canonical version of C arrays with a specified constant size.
This class handles loading and caching of source files into memory.
bool isUnsignedInteger() const
bool isObjC(ID Id)
isObjC - Is this an "ObjC" input (Obj-C and Obj-C++ sources and headers).
NullPointerConstantKind
Enumeration used to describe the kind of Null pointer constant returned from isNullPointerConstant()...
Attr - This represents one attribute.
SourceLocation getLocation() const
Represents a shadow declaration introduced into a scope by a (resolved) using declaration.
QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc)
CheckAddressOfOperand - The operand of & must be either a function designator or an lvalue designatin...
QualType getType() const
Return the type wrapped by this type source info.
CanQualType OCLClkEventTy
ArrayRef< ParmVarDecl * > parameters() const
Helper class that creates diagnostics with optional template instantiation stacks.
Expr * IgnoreParens() LLVM_READONLY
IgnoreParens - Ignore parentheses.
static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, SourceLocation StmtLoc, const NullStmt *Body)
CanQualType UnsignedIntTy
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign, ASTContext &Context)
A helper function to get the alignment of a Decl referred to by DeclRefExpr or MemberExpr.
Expr * getBase()
An array section can be written only as Base[LowerBound:Length].
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
unsigned getVectorLength() const