36 #include "llvm/ADT/STLExtras.h"
37 #include "llvm/ADT/SmallBitVector.h"
38 #include "llvm/ADT/SmallString.h"
39 #include "llvm/Support/Format.h"
40 #include "llvm/Support/Locale.h"
41 #include "llvm/Support/ConvertUTF.h"
42 #include "llvm/Support/raw_ostream.h"
45 using namespace clang;
49 unsigned ByteNo)
const {
58 if (argCount == desiredArgCount)
return false;
60 if (argCount < desiredArgCount)
61 return S.
Diag(call->
getLocEnd(), diag::err_typecheck_call_too_few_args)
62 << 0 << desiredArgCount << argCount
63 << call->getSourceRange();
67 call->
getArg(argCount - 1)->getLocEnd());
69 return S.
Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
70 << 0 << desiredArgCount << argCount
71 << call->
getArg(1)->getSourceRange();
84 S.
Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
85 << ValArg->getSourceRange();
92 if (!Literal || !Literal->
isAscii()) {
93 S.
Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
94 << StrArg->getSourceRange();
110 if (ResultType.isNull())
113 TheCall->
setArg(0, Arg.get());
123 for (
unsigned I = 0;
I < 2; ++
I) {
127 S.
Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int)
128 << Ty << Arg->getSourceRange();
140 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
141 !PtrTy->getPointeeType().isConstQualified())) {
142 S.
Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int)
143 << Ty << Arg->getSourceRange();
152 CallExpr *TheCall,
unsigned SizeIdx,
153 unsigned DstSizeIdx) {
158 const Expr *SizeArg = TheCall->
getArg(SizeIdx);
159 const Expr *DstSizeArg = TheCall->
getArg(DstSizeIdx);
161 llvm::APSInt Size, DstSize;
168 if (Size.ule(DstSize))
176 S.
Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
188 if (Call->getStmtClass() != Stmt::CallExprClass) {
189 S.
Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
190 << Call->getSourceRange();
194 auto CE = cast<CallExpr>(Call);
195 if (CE->getCallee()->getType()->isBlockPointerType()) {
196 S.
Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
197 << Call->getSourceRange();
201 const Decl *TargetDecl = CE->getCalleeDecl();
202 if (
const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
203 if (FD->getBuiltinID()) {
204 S.
Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
205 << Call->getSourceRange();
209 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
210 S.
Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
211 << Call->getSourceRange();
219 S.
Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
220 << Chain->getSourceRange();
233 BuiltinCall->
setType(CE->getType());
237 BuiltinCall->
setArg(1, ChainResult.
get());
254 if (!S || !(S->
getFlags() & NeededScopeFlags)) {
257 << DRE->getDecl()->getIdentifier();
273 ArrayRef<QualType> Params =
275 unsigned ArgCounter = 0;
276 bool IllegalParams =
false;
280 I !=
E; ++
I, ++ArgCounter) {
281 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
282 (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
288 if (isa<BlockExpr>(BlockArg)) {
289 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
291 }
else if (isa<DeclRefExpr>(BlockArg)) {
292 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getLocStart();
295 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
296 IllegalParams =
true;
300 return IllegalParams;
312 S.
Diag(BlockArg->getLocStart(),
313 diag::err_opencl_enqueue_kernel_expected_type) <<
"block";
320 unsigned Start,
unsigned End);
326 unsigned NumNonVarArgs) {
329 unsigned NumBlockParams =
331 unsigned TotalNumArgs = TheCall->
getNumArgs();
335 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
337 diag::err_opencl_enqueue_kernel_local_size_args);
388 diag::err_opencl_enqueue_kernel_expected_type)
396 diag::err_opencl_enqueue_kernel_expected_type)
397 <<
"'kernel_enqueue_flags_t' (i.e. uint)";
404 diag::err_opencl_enqueue_kernel_expected_type)
414 S.
Diag(Arg3->getLocStart(), diag::err_opencl_enqueue_kernel_expected_type)
422 S.
Diag(Arg3->getLocStart(),
423 diag::err_opencl_enqueue_kernel_blocks_no_args);
437 S.
Diag(Arg6->getLocStart(), diag::err_opencl_enqueue_kernel_expected_type)
447 diag::err_opencl_enqueue_kernel_expected_type)
458 diag::err_opencl_enqueue_kernel_expected_type)
467 diag::err_opencl_enqueue_kernel_expected_type)
480 diag::err_opencl_enqueue_kernel_incorrect_args);
486 return D->getAttr<OpenCLAccessAttr>();
498 OpenCLAccessAttr *AccessQual =
505 case Builtin::BIread_pipe:
506 case Builtin::BIreserve_read_pipe:
507 case Builtin::BIcommit_read_pipe:
508 case Builtin::BIwork_group_reserve_read_pipe:
509 case Builtin::BIsub_group_reserve_read_pipe:
510 case Builtin::BIwork_group_commit_read_pipe:
511 case Builtin::BIsub_group_commit_read_pipe:
512 if (!(!AccessQual || AccessQual->isReadOnly())) {
513 S.
Diag(Arg0->getLocStart(),
514 diag::err_opencl_builtin_pipe_invalid_access_modifier)
515 <<
"read_only" << Arg0->getSourceRange();
519 case Builtin::BIwrite_pipe:
520 case Builtin::BIreserve_write_pipe:
521 case Builtin::BIcommit_write_pipe:
522 case Builtin::BIwork_group_reserve_write_pipe:
523 case Builtin::BIsub_group_reserve_write_pipe:
524 case Builtin::BIwork_group_commit_write_pipe:
525 case Builtin::BIsub_group_commit_write_pipe:
526 if (!(AccessQual && AccessQual->isWriteOnly())) {
527 S.
Diag(Arg0->getLocStart(),
528 diag::err_opencl_builtin_pipe_invalid_access_modifier)
529 <<
"write_only" << Arg0->getSourceRange();
553 << ArgIdx->
getType() << ArgIdx->getSourceRange();
596 << Arg2->
getType() << Arg2->getSourceRange();
692 if (!RT->isPointerType() || RT->getPointeeType()
694 S.
Diag(Call->
getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg)
699 RT = RT->getPointeeType();
700 auto Qual = RT.getQualifiers();
702 case Builtin::BIto_global:
705 case Builtin::BIto_local:
709 Qual.removeAddressSpace();
712 RT.getUnqualifiedType(), Qual)));
718 Sema::CheckBuiltinFunctionCall(
FunctionDecl *FDecl,
unsigned BuiltinID,
723 unsigned ICEArguments = 0;
730 for (
unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
732 if ((ICEArguments & (1 << ArgNo)) == 0)
continue;
735 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
737 ICEArguments &= ~(1 << ArgNo);
741 case Builtin::BI__builtin___CFStringMakeConstantString:
743 "Wrong # arguments to builtin CFStringMakeConstantString");
744 if (CheckObjCString(TheCall->
getArg(0)))
747 case Builtin::BI__builtin_stdarg_start:
748 case Builtin::BI__builtin_va_start:
749 if (SemaBuiltinVAStart(TheCall))
752 case Builtin::BI__va_start: {
754 case llvm::Triple::arm:
755 case llvm::Triple::thumb:
756 if (SemaBuiltinVAStartARM(TheCall))
760 if (SemaBuiltinVAStart(TheCall))
766 case Builtin::BI__builtin_isgreater:
767 case Builtin::BI__builtin_isgreaterequal:
768 case Builtin::BI__builtin_isless:
769 case Builtin::BI__builtin_islessequal:
770 case Builtin::BI__builtin_islessgreater:
771 case Builtin::BI__builtin_isunordered:
772 if (SemaBuiltinUnorderedCompare(TheCall))
775 case Builtin::BI__builtin_fpclassify:
776 if (SemaBuiltinFPClassification(TheCall, 6))
779 case Builtin::BI__builtin_isfinite:
780 case Builtin::BI__builtin_isinf:
781 case Builtin::BI__builtin_isinf_sign:
782 case Builtin::BI__builtin_isnan:
783 case Builtin::BI__builtin_isnormal:
784 if (SemaBuiltinFPClassification(TheCall, 1))
787 case Builtin::BI__builtin_shufflevector:
788 return SemaBuiltinShuffleVector(TheCall);
791 case Builtin::BI__builtin_prefetch:
792 if (SemaBuiltinPrefetch(TheCall))
795 case Builtin::BI__assume:
796 case Builtin::BI__builtin_assume:
797 if (SemaBuiltinAssume(TheCall))
800 case Builtin::BI__builtin_assume_aligned:
801 if (SemaBuiltinAssumeAligned(TheCall))
804 case Builtin::BI__builtin_object_size:
805 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
808 case Builtin::BI__builtin_longjmp:
809 if (SemaBuiltinLongjmp(TheCall))
812 case Builtin::BI__builtin_setjmp:
813 if (SemaBuiltinSetjmp(TheCall))
816 case Builtin::BI_setjmp:
817 case Builtin::BI_setjmpex:
822 case Builtin::BI__builtin_classify_type:
826 case Builtin::BI__builtin_constant_p:
830 case Builtin::BI__sync_fetch_and_add:
831 case Builtin::BI__sync_fetch_and_add_1:
832 case Builtin::BI__sync_fetch_and_add_2:
833 case Builtin::BI__sync_fetch_and_add_4:
834 case Builtin::BI__sync_fetch_and_add_8:
835 case Builtin::BI__sync_fetch_and_add_16:
836 case Builtin::BI__sync_fetch_and_sub:
837 case Builtin::BI__sync_fetch_and_sub_1:
838 case Builtin::BI__sync_fetch_and_sub_2:
839 case Builtin::BI__sync_fetch_and_sub_4:
840 case Builtin::BI__sync_fetch_and_sub_8:
841 case Builtin::BI__sync_fetch_and_sub_16:
842 case Builtin::BI__sync_fetch_and_or:
843 case Builtin::BI__sync_fetch_and_or_1:
844 case Builtin::BI__sync_fetch_and_or_2:
845 case Builtin::BI__sync_fetch_and_or_4:
846 case Builtin::BI__sync_fetch_and_or_8:
847 case Builtin::BI__sync_fetch_and_or_16:
848 case Builtin::BI__sync_fetch_and_and:
849 case Builtin::BI__sync_fetch_and_and_1:
850 case Builtin::BI__sync_fetch_and_and_2:
851 case Builtin::BI__sync_fetch_and_and_4:
852 case Builtin::BI__sync_fetch_and_and_8:
853 case Builtin::BI__sync_fetch_and_and_16:
854 case Builtin::BI__sync_fetch_and_xor:
855 case Builtin::BI__sync_fetch_and_xor_1:
856 case Builtin::BI__sync_fetch_and_xor_2:
857 case Builtin::BI__sync_fetch_and_xor_4:
858 case Builtin::BI__sync_fetch_and_xor_8:
859 case Builtin::BI__sync_fetch_and_xor_16:
860 case Builtin::BI__sync_fetch_and_nand:
861 case Builtin::BI__sync_fetch_and_nand_1:
862 case Builtin::BI__sync_fetch_and_nand_2:
863 case Builtin::BI__sync_fetch_and_nand_4:
864 case Builtin::BI__sync_fetch_and_nand_8:
865 case Builtin::BI__sync_fetch_and_nand_16:
866 case Builtin::BI__sync_add_and_fetch:
867 case Builtin::BI__sync_add_and_fetch_1:
868 case Builtin::BI__sync_add_and_fetch_2:
869 case Builtin::BI__sync_add_and_fetch_4:
870 case Builtin::BI__sync_add_and_fetch_8:
871 case Builtin::BI__sync_add_and_fetch_16:
872 case Builtin::BI__sync_sub_and_fetch:
873 case Builtin::BI__sync_sub_and_fetch_1:
874 case Builtin::BI__sync_sub_and_fetch_2:
875 case Builtin::BI__sync_sub_and_fetch_4:
876 case Builtin::BI__sync_sub_and_fetch_8:
877 case Builtin::BI__sync_sub_and_fetch_16:
878 case Builtin::BI__sync_and_and_fetch:
879 case Builtin::BI__sync_and_and_fetch_1:
880 case Builtin::BI__sync_and_and_fetch_2:
881 case Builtin::BI__sync_and_and_fetch_4:
882 case Builtin::BI__sync_and_and_fetch_8:
883 case Builtin::BI__sync_and_and_fetch_16:
884 case Builtin::BI__sync_or_and_fetch:
885 case Builtin::BI__sync_or_and_fetch_1:
886 case Builtin::BI__sync_or_and_fetch_2:
887 case Builtin::BI__sync_or_and_fetch_4:
888 case Builtin::BI__sync_or_and_fetch_8:
889 case Builtin::BI__sync_or_and_fetch_16:
890 case Builtin::BI__sync_xor_and_fetch:
891 case Builtin::BI__sync_xor_and_fetch_1:
892 case Builtin::BI__sync_xor_and_fetch_2:
893 case Builtin::BI__sync_xor_and_fetch_4:
894 case Builtin::BI__sync_xor_and_fetch_8:
895 case Builtin::BI__sync_xor_and_fetch_16:
896 case Builtin::BI__sync_nand_and_fetch:
897 case Builtin::BI__sync_nand_and_fetch_1:
898 case Builtin::BI__sync_nand_and_fetch_2:
899 case Builtin::BI__sync_nand_and_fetch_4:
900 case Builtin::BI__sync_nand_and_fetch_8:
901 case Builtin::BI__sync_nand_and_fetch_16:
902 case Builtin::BI__sync_val_compare_and_swap:
903 case Builtin::BI__sync_val_compare_and_swap_1:
904 case Builtin::BI__sync_val_compare_and_swap_2:
905 case Builtin::BI__sync_val_compare_and_swap_4:
906 case Builtin::BI__sync_val_compare_and_swap_8:
907 case Builtin::BI__sync_val_compare_and_swap_16:
908 case Builtin::BI__sync_bool_compare_and_swap:
909 case Builtin::BI__sync_bool_compare_and_swap_1:
910 case Builtin::BI__sync_bool_compare_and_swap_2:
911 case Builtin::BI__sync_bool_compare_and_swap_4:
912 case Builtin::BI__sync_bool_compare_and_swap_8:
913 case Builtin::BI__sync_bool_compare_and_swap_16:
914 case Builtin::BI__sync_lock_test_and_set:
915 case Builtin::BI__sync_lock_test_and_set_1:
916 case Builtin::BI__sync_lock_test_and_set_2:
917 case Builtin::BI__sync_lock_test_and_set_4:
918 case Builtin::BI__sync_lock_test_and_set_8:
919 case Builtin::BI__sync_lock_test_and_set_16:
920 case Builtin::BI__sync_lock_release:
921 case Builtin::BI__sync_lock_release_1:
922 case Builtin::BI__sync_lock_release_2:
923 case Builtin::BI__sync_lock_release_4:
924 case Builtin::BI__sync_lock_release_8:
925 case Builtin::BI__sync_lock_release_16:
926 case Builtin::BI__sync_swap:
927 case Builtin::BI__sync_swap_1:
928 case Builtin::BI__sync_swap_2:
929 case Builtin::BI__sync_swap_4:
930 case Builtin::BI__sync_swap_8:
931 case Builtin::BI__sync_swap_16:
932 return SemaBuiltinAtomicOverloaded(TheCallResult);
933 case Builtin::BI__builtin_nontemporal_load:
934 case Builtin::BI__builtin_nontemporal_store:
935 return SemaBuiltinNontemporalOverloaded(TheCallResult);
936 #define BUILTIN(ID, TYPE, ATTRS)
937 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
938 case Builtin::BI##ID: \
939 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
940 #include "clang/Basic/Builtins.def"
941 case Builtin::BI__builtin_annotation:
945 case Builtin::BI__builtin_addressof:
949 case Builtin::BI__builtin_add_overflow:
950 case Builtin::BI__builtin_sub_overflow:
951 case Builtin::BI__builtin_mul_overflow:
955 case Builtin::BI__builtin_operator_new:
956 case Builtin::BI__builtin_operator_delete:
959 << (BuiltinID == Builtin::BI__builtin_operator_new
960 ?
"__builtin_operator_new"
961 :
"__builtin_operator_delete")
967 DeclareGlobalNewDelete();
972 case Builtin::BI__builtin___memcpy_chk:
973 case Builtin::BI__builtin___memmove_chk:
974 case Builtin::BI__builtin___memset_chk:
975 case Builtin::BI__builtin___strlcat_chk:
976 case Builtin::BI__builtin___strlcpy_chk:
977 case Builtin::BI__builtin___strncat_chk:
978 case Builtin::BI__builtin___strncpy_chk:
979 case Builtin::BI__builtin___stpncpy_chk:
982 case Builtin::BI__builtin___memccpy_chk:
985 case Builtin::BI__builtin___snprintf_chk:
986 case Builtin::BI__builtin___vsnprintf_chk:
989 case Builtin::BI__builtin_call_with_static_chain:
993 case Builtin::BI__exception_code:
994 case Builtin::BI_exception_code:
996 diag::err_seh___except_block))
999 case Builtin::BI__exception_info:
1000 case Builtin::BI_exception_info:
1002 diag::err_seh___except_filter))
1005 case Builtin::BI__GetExceptionInfo:
1009 if (CheckCXXThrowOperand(
1018 case Builtin::BIread_pipe:
1019 case Builtin::BIwrite_pipe:
1025 case Builtin::BIreserve_read_pipe:
1026 case Builtin::BIreserve_write_pipe:
1027 case Builtin::BIwork_group_reserve_read_pipe:
1028 case Builtin::BIwork_group_reserve_write_pipe:
1029 case Builtin::BIsub_group_reserve_read_pipe:
1030 case Builtin::BIsub_group_reserve_write_pipe:
1038 case Builtin::BIcommit_read_pipe:
1039 case Builtin::BIcommit_write_pipe:
1040 case Builtin::BIwork_group_commit_read_pipe:
1041 case Builtin::BIwork_group_commit_write_pipe:
1042 case Builtin::BIsub_group_commit_read_pipe:
1043 case Builtin::BIsub_group_commit_write_pipe:
1047 case Builtin::BIget_pipe_num_packets:
1048 case Builtin::BIget_pipe_max_packets:
1052 case Builtin::BIto_global:
1053 case Builtin::BIto_local:
1054 case Builtin::BIto_private:
1059 case Builtin::BIenqueue_kernel:
1063 case Builtin::BIget_kernel_work_group_size:
1064 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1073 case llvm::Triple::arm:
1074 case llvm::Triple::armeb:
1075 case llvm::Triple::thumb:
1076 case llvm::Triple::thumbeb:
1077 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1080 case llvm::Triple::aarch64:
1081 case llvm::Triple::aarch64_be:
1082 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
1085 case llvm::Triple::mips:
1086 case llvm::Triple::mipsel:
1087 case llvm::Triple::mips64:
1088 case llvm::Triple::mips64el:
1089 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1092 case llvm::Triple::systemz:
1093 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1096 case llvm::Triple::x86:
1097 case llvm::Triple::x86_64:
1098 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1101 case llvm::Triple::ppc:
1102 case llvm::Triple::ppc64:
1103 case llvm::Triple::ppc64le:
1104 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1112 return TheCallResult;
1116 static unsigned RFT(
unsigned t,
bool shift =
false,
bool ForceQuad =
false) {
1118 int IsQuad = ForceQuad ?
true : Type.
isQuad();
1122 return shift ? 7 : (8 << IsQuad) - 1;
1125 return shift ? 15 : (4 << IsQuad) - 1;
1127 return shift ? 31 : (2 << IsQuad) - 1;
1130 return shift ? 63 : (1 << IsQuad) - 1;
1132 return shift ? 127 : (1 << IsQuad) - 1;
1134 assert(!shift &&
"cannot shift float types!");
1135 return (4 << IsQuad) - 1;
1137 assert(!shift &&
"cannot shift float types!");
1138 return (2 << IsQuad) - 1;
1140 assert(!shift &&
"cannot shift float types!");
1141 return (1 << IsQuad) - 1;
1143 llvm_unreachable(
"Invalid NeonTypeFlag!");
1150 bool IsPolyUnsigned,
bool IsInt64Long) {
1182 llvm_unreachable(
"Invalid NeonTypeFlag!");
1185 bool Sema::CheckNeonBuiltinFunctionCall(
unsigned BuiltinID,
CallExpr *TheCall) {
1186 llvm::APSInt Result;
1190 bool HasConstPtr =
false;
1191 switch (BuiltinID) {
1192 #define GET_NEON_OVERLOAD_CHECK
1193 #include "clang/Basic/arm_neon.inc"
1194 #undef GET_NEON_OVERLOAD_CHECK
1201 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1204 TV = Result.getLimitedValue(64);
1205 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1207 << TheCall->
getArg(ImmArg)->getSourceRange();
1210 if (PtrArgNum >= 0) {
1214 Arg = ICE->getSubExpr();
1215 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1219 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
1227 AssignConvertType ConvTy;
1228 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1231 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
1232 RHS.
get(), AA_Assigning))
1238 unsigned i = 0, l = 0, u = 0;
1239 switch (BuiltinID) {
1242 #define GET_NEON_IMMEDIATE_CHECK
1243 #include "clang/Basic/arm_neon.inc"
1244 #undef GET_NEON_IMMEDIATE_CHECK
1247 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1250 bool Sema::CheckARMBuiltinExclusiveCall(
unsigned BuiltinID,
CallExpr *TheCall,
1251 unsigned MaxWidth) {
1252 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
1253 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1254 BuiltinID == ARM::BI__builtin_arm_strex ||
1255 BuiltinID == ARM::BI__builtin_arm_stlex ||
1256 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1257 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1258 BuiltinID == AArch64::BI__builtin_arm_strex ||
1259 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
1260 "unexpected ARM builtin");
1261 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
1262 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1263 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1264 BuiltinID == AArch64::BI__builtin_arm_ldaex;
1276 Expr *PointerArg = TheCall->
getArg(IsLdrex ? 0 : 1);
1277 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1280 PointerArg = PointerArgRes.
get();
1285 << PointerArg->
getType() << PointerArg->getSourceRange();
1300 CastNeeded = CK_BitCast;
1301 Diag(DRE->
getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1304 << AA_Passing << PointerArg->getSourceRange();
1309 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1312 PointerArg = PointerArgRes.
get();
1314 TheCall->
setArg(IsLdrex ? 0 : 1, PointerArg);
1319 Diag(DRE->
getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1320 << PointerArg->
getType() << PointerArg->getSourceRange();
1326 assert(MaxWidth == 64 &&
"Diagnostic unexpectedly inaccurate");
1327 Diag(DRE->
getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1328 << PointerArg->
getType() << PointerArg->getSourceRange();
1342 << ValType << PointerArg->getSourceRange();
1355 ValArg = PerformCopyInitialization(Entity,
SourceLocation(), ValArg);
1366 bool Sema::CheckARMBuiltinFunctionCall(
unsigned BuiltinID,
CallExpr *TheCall) {
1367 llvm::APSInt Result;
1369 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
1370 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1371 BuiltinID == ARM::BI__builtin_arm_strex ||
1372 BuiltinID == ARM::BI__builtin_arm_stlex) {
1373 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
1376 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1377 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1378 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1381 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1382 BuiltinID == ARM::BI__builtin_arm_wsr64)
1383 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3,
false);
1385 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1386 BuiltinID == ARM::BI__builtin_arm_rsrp ||
1387 BuiltinID == ARM::BI__builtin_arm_wsr ||
1388 BuiltinID == ARM::BI__builtin_arm_wsrp)
1389 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5,
true);
1391 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1396 unsigned i = 0, l = 0, u = 0;
1397 switch (BuiltinID) {
1398 default:
return false;
1399 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31;
break;
1400 case ARM::BI__builtin_arm_usat: i = 1; u = 31;
break;
1401 case ARM::BI__builtin_arm_vcvtr_f:
1402 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1;
break;
1403 case ARM::BI__builtin_arm_dmb:
1404 case ARM::BI__builtin_arm_dsb:
1405 case ARM::BI__builtin_arm_isb:
1406 case ARM::BI__builtin_arm_dbg: l = 0; u = 15;
break;
1410 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1413 bool Sema::CheckAArch64BuiltinFunctionCall(
unsigned BuiltinID,
1415 llvm::APSInt Result;
1417 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1418 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1419 BuiltinID == AArch64::BI__builtin_arm_strex ||
1420 BuiltinID == AArch64::BI__builtin_arm_stlex) {
1421 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1424 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1425 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1426 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1427 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1428 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1431 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1432 BuiltinID == AArch64::BI__builtin_arm_wsr64)
1433 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5,
true);
1435 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1436 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1437 BuiltinID == AArch64::BI__builtin_arm_wsr ||
1438 BuiltinID == AArch64::BI__builtin_arm_wsrp)
1439 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5,
true);
1441 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1446 unsigned i = 0, l = 0, u = 0;
1447 switch (BuiltinID) {
1448 default:
return false;
1449 case AArch64::BI__builtin_arm_dmb:
1450 case AArch64::BI__builtin_arm_dsb:
1451 case AArch64::BI__builtin_arm_isb: l = 0; u = 15;
break;
1454 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1457 bool Sema::CheckMipsBuiltinFunctionCall(
unsigned BuiltinID,
CallExpr *TheCall) {
1458 unsigned i = 0, l = 0, u = 0;
1459 switch (BuiltinID) {
1460 default:
return false;
1461 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63;
break;
1462 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63;
break;
1463 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31;
break;
1464 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3;
break;
1465 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31;
break;
1466 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31;
break;
1467 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31;
break;
1470 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1473 bool Sema::CheckPPCBuiltinFunctionCall(
unsigned BuiltinID,
CallExpr *TheCall) {
1474 unsigned i = 0, l = 0, u = 0;
1475 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
1476 BuiltinID == PPC::BI__builtin_divdeu ||
1477 BuiltinID == PPC::BI__builtin_bpermd;
1481 .getIntPtrType()) == 64;
1482 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
1483 BuiltinID == PPC::BI__builtin_divweu ||
1484 BuiltinID == PPC::BI__builtin_divde ||
1485 BuiltinID == PPC::BI__builtin_divdeu;
1487 if (Is64BitBltin && !IsTarget64Bit)
1488 return Diag(TheCall->
getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
1489 << TheCall->getSourceRange();
1492 (BuiltinID == PPC::BI__builtin_bpermd &&
1494 return Diag(TheCall->
getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
1495 << TheCall->getSourceRange();
1497 switch (BuiltinID) {
1498 default:
return false;
1499 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1500 case PPC::BI__builtin_altivec_crypto_vshasigmad:
1501 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1502 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1503 case PPC::BI__builtin_tbegin:
1504 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1;
break;
1505 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7;
break;
1506 case PPC::BI__builtin_tabortwc:
1507 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31;
break;
1508 case PPC::BI__builtin_tabortwci:
1509 case PPC::BI__builtin_tabortdci:
1510 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1511 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
1513 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1516 bool Sema::CheckSystemZBuiltinFunctionCall(
unsigned BuiltinID,
1518 if (BuiltinID == SystemZ::BI__builtin_tabort) {
1520 llvm::APSInt AbortCode(32);
1522 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1523 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1524 << Arg->getSourceRange();
1529 unsigned i = 0, l = 0, u = 0;
1530 switch (BuiltinID) {
1531 default:
return false;
1532 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15;
break;
1533 case SystemZ::BI__builtin_s390_verimb:
1534 case SystemZ::BI__builtin_s390_verimh:
1535 case SystemZ::BI__builtin_s390_verimf:
1536 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255;
break;
1537 case SystemZ::BI__builtin_s390_vfaeb:
1538 case SystemZ::BI__builtin_s390_vfaeh:
1539 case SystemZ::BI__builtin_s390_vfaef:
1540 case SystemZ::BI__builtin_s390_vfaebs:
1541 case SystemZ::BI__builtin_s390_vfaehs:
1542 case SystemZ::BI__builtin_s390_vfaefs:
1543 case SystemZ::BI__builtin_s390_vfaezb:
1544 case SystemZ::BI__builtin_s390_vfaezh:
1545 case SystemZ::BI__builtin_s390_vfaezf:
1546 case SystemZ::BI__builtin_s390_vfaezbs:
1547 case SystemZ::BI__builtin_s390_vfaezhs:
1548 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15;
break;
1549 case SystemZ::BI__builtin_s390_vfidb:
1550 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1551 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1552 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095;
break;
1553 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15;
break;
1554 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15;
break;
1555 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15;
break;
1556 case SystemZ::BI__builtin_s390_vstrcb:
1557 case SystemZ::BI__builtin_s390_vstrch:
1558 case SystemZ::BI__builtin_s390_vstrcf:
1559 case SystemZ::BI__builtin_s390_vstrczb:
1560 case SystemZ::BI__builtin_s390_vstrczh:
1561 case SystemZ::BI__builtin_s390_vstrczf:
1562 case SystemZ::BI__builtin_s390_vstrcbs:
1563 case SystemZ::BI__builtin_s390_vstrchs:
1564 case SystemZ::BI__builtin_s390_vstrcfs:
1565 case SystemZ::BI__builtin_s390_vstrczbs:
1566 case SystemZ::BI__builtin_s390_vstrczhs:
1567 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15;
break;
1569 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1580 return S.
Diag(TheCall->
getLocStart(), diag::err_expr_not_string_literal)
1581 << Arg->getSourceRange();
1588 << Arg->getSourceRange();
1592 bool Sema::CheckX86BuiltinFunctionCall(
unsigned BuiltinID,
CallExpr *TheCall) {
1593 int i = 0, l = 0, u = 0;
1594 switch (BuiltinID) {
1597 case X86::BI__builtin_cpu_supports:
1599 case X86::BI__builtin_ms_va_start:
1600 return SemaBuiltinMSVAStart(TheCall);
1601 case X86::BI__builtin_ia32_extractf64x4_mask:
1602 case X86::BI__builtin_ia32_extracti64x4_mask:
1603 case X86::BI__builtin_ia32_extractf32x8_mask:
1604 case X86::BI__builtin_ia32_extracti32x8_mask:
1605 case X86::BI__builtin_ia32_extractf64x2_256_mask:
1606 case X86::BI__builtin_ia32_extracti64x2_256_mask:
1607 case X86::BI__builtin_ia32_extractf32x4_256_mask:
1608 case X86::BI__builtin_ia32_extracti32x4_256_mask:
1609 i = 1; l = 0; u = 1;
1611 case X86::BI_mm_prefetch:
1612 case X86::BI__builtin_ia32_extractf32x4_mask:
1613 case X86::BI__builtin_ia32_extracti32x4_mask:
1614 case X86::BI__builtin_ia32_extractf64x2_512_mask:
1615 case X86::BI__builtin_ia32_extracti64x2_512_mask:
1616 i = 1; l = 0; u = 3;
1618 case X86::BI__builtin_ia32_insertf32x8_mask:
1619 case X86::BI__builtin_ia32_inserti32x8_mask:
1620 case X86::BI__builtin_ia32_insertf64x4_mask:
1621 case X86::BI__builtin_ia32_inserti64x4_mask:
1622 case X86::BI__builtin_ia32_insertf64x2_256_mask:
1623 case X86::BI__builtin_ia32_inserti64x2_256_mask:
1624 case X86::BI__builtin_ia32_insertf32x4_256_mask:
1625 case X86::BI__builtin_ia32_inserti32x4_256_mask:
1626 i = 2; l = 0; u = 1;
1628 case X86::BI__builtin_ia32_sha1rnds4:
1629 case X86::BI__builtin_ia32_shuf_f32x4_256_mask:
1630 case X86::BI__builtin_ia32_shuf_f64x2_256_mask:
1631 case X86::BI__builtin_ia32_shuf_i32x4_256_mask:
1632 case X86::BI__builtin_ia32_shuf_i64x2_256_mask:
1633 case X86::BI__builtin_ia32_insertf64x2_512_mask:
1634 case X86::BI__builtin_ia32_inserti64x2_512_mask:
1635 case X86::BI__builtin_ia32_insertf32x4_mask:
1636 case X86::BI__builtin_ia32_inserti32x4_mask:
1637 i = 2; l = 0; u = 3;
1639 case X86::BI__builtin_ia32_vpermil2pd:
1640 case X86::BI__builtin_ia32_vpermil2pd256:
1641 case X86::BI__builtin_ia32_vpermil2ps:
1642 case X86::BI__builtin_ia32_vpermil2ps256:
1643 i = 3; l = 0; u = 3;
1645 case X86::BI__builtin_ia32_cmpb128_mask:
1646 case X86::BI__builtin_ia32_cmpw128_mask:
1647 case X86::BI__builtin_ia32_cmpd128_mask:
1648 case X86::BI__builtin_ia32_cmpq128_mask:
1649 case X86::BI__builtin_ia32_cmpb256_mask:
1650 case X86::BI__builtin_ia32_cmpw256_mask:
1651 case X86::BI__builtin_ia32_cmpd256_mask:
1652 case X86::BI__builtin_ia32_cmpq256_mask:
1653 case X86::BI__builtin_ia32_cmpb512_mask:
1654 case X86::BI__builtin_ia32_cmpw512_mask:
1655 case X86::BI__builtin_ia32_cmpd512_mask:
1656 case X86::BI__builtin_ia32_cmpq512_mask:
1657 case X86::BI__builtin_ia32_ucmpb128_mask:
1658 case X86::BI__builtin_ia32_ucmpw128_mask:
1659 case X86::BI__builtin_ia32_ucmpd128_mask:
1660 case X86::BI__builtin_ia32_ucmpq128_mask:
1661 case X86::BI__builtin_ia32_ucmpb256_mask:
1662 case X86::BI__builtin_ia32_ucmpw256_mask:
1663 case X86::BI__builtin_ia32_ucmpd256_mask:
1664 case X86::BI__builtin_ia32_ucmpq256_mask:
1665 case X86::BI__builtin_ia32_ucmpb512_mask:
1666 case X86::BI__builtin_ia32_ucmpw512_mask:
1667 case X86::BI__builtin_ia32_ucmpd512_mask:
1668 case X86::BI__builtin_ia32_ucmpq512_mask:
1669 case X86::BI__builtin_ia32_vpcomub:
1670 case X86::BI__builtin_ia32_vpcomuw:
1671 case X86::BI__builtin_ia32_vpcomud:
1672 case X86::BI__builtin_ia32_vpcomuq:
1673 case X86::BI__builtin_ia32_vpcomb:
1674 case X86::BI__builtin_ia32_vpcomw:
1675 case X86::BI__builtin_ia32_vpcomd:
1676 case X86::BI__builtin_ia32_vpcomq:
1677 i = 2; l = 0; u = 7;
1679 case X86::BI__builtin_ia32_roundps:
1680 case X86::BI__builtin_ia32_roundpd:
1681 case X86::BI__builtin_ia32_roundps256:
1682 case X86::BI__builtin_ia32_roundpd256:
1683 i = 1; l = 0; u = 15;
1685 case X86::BI__builtin_ia32_roundss:
1686 case X86::BI__builtin_ia32_roundsd:
1687 case X86::BI__builtin_ia32_rangepd128_mask:
1688 case X86::BI__builtin_ia32_rangepd256_mask:
1689 case X86::BI__builtin_ia32_rangepd512_mask:
1690 case X86::BI__builtin_ia32_rangeps128_mask:
1691 case X86::BI__builtin_ia32_rangeps256_mask:
1692 case X86::BI__builtin_ia32_rangeps512_mask:
1693 case X86::BI__builtin_ia32_getmantsd_round_mask:
1694 case X86::BI__builtin_ia32_getmantss_round_mask:
1695 i = 2; l = 0; u = 15;
1697 case X86::BI__builtin_ia32_cmpps:
1698 case X86::BI__builtin_ia32_cmpss:
1699 case X86::BI__builtin_ia32_cmppd:
1700 case X86::BI__builtin_ia32_cmpsd:
1701 case X86::BI__builtin_ia32_cmpps256:
1702 case X86::BI__builtin_ia32_cmppd256:
1703 case X86::BI__builtin_ia32_cmpps128_mask:
1704 case X86::BI__builtin_ia32_cmppd128_mask:
1705 case X86::BI__builtin_ia32_cmpps256_mask:
1706 case X86::BI__builtin_ia32_cmppd256_mask:
1707 case X86::BI__builtin_ia32_cmpps512_mask:
1708 case X86::BI__builtin_ia32_cmppd512_mask:
1709 case X86::BI__builtin_ia32_cmpsd_mask:
1710 case X86::BI__builtin_ia32_cmpss_mask:
1711 i = 2; l = 0; u = 31;
1713 case X86::BI__builtin_ia32_xabort:
1714 i = 0; l = -128; u = 255;
1716 case X86::BI__builtin_ia32_pshufw:
1717 case X86::BI__builtin_ia32_aeskeygenassist128:
1718 i = 1; l = -128; u = 255;
1720 case X86::BI__builtin_ia32_vcvtps2ph:
1721 case X86::BI__builtin_ia32_vcvtps2ph256:
1722 case X86::BI__builtin_ia32_rndscaleps_128_mask:
1723 case X86::BI__builtin_ia32_rndscalepd_128_mask:
1724 case X86::BI__builtin_ia32_rndscaleps_256_mask:
1725 case X86::BI__builtin_ia32_rndscalepd_256_mask:
1726 case X86::BI__builtin_ia32_rndscaleps_mask:
1727 case X86::BI__builtin_ia32_rndscalepd_mask:
1728 case X86::BI__builtin_ia32_reducepd128_mask:
1729 case X86::BI__builtin_ia32_reducepd256_mask:
1730 case X86::BI__builtin_ia32_reducepd512_mask:
1731 case X86::BI__builtin_ia32_reduceps128_mask:
1732 case X86::BI__builtin_ia32_reduceps256_mask:
1733 case X86::BI__builtin_ia32_reduceps512_mask:
1734 case X86::BI__builtin_ia32_prold512_mask:
1735 case X86::BI__builtin_ia32_prolq512_mask:
1736 case X86::BI__builtin_ia32_prold128_mask:
1737 case X86::BI__builtin_ia32_prold256_mask:
1738 case X86::BI__builtin_ia32_prolq128_mask:
1739 case X86::BI__builtin_ia32_prolq256_mask:
1740 case X86::BI__builtin_ia32_prord128_mask:
1741 case X86::BI__builtin_ia32_prord256_mask:
1742 case X86::BI__builtin_ia32_prorq128_mask:
1743 case X86::BI__builtin_ia32_prorq256_mask:
1744 case X86::BI__builtin_ia32_psllwi512_mask:
1745 case X86::BI__builtin_ia32_psllwi128_mask:
1746 case X86::BI__builtin_ia32_psllwi256_mask:
1747 case X86::BI__builtin_ia32_psrldi128_mask:
1748 case X86::BI__builtin_ia32_psrldi256_mask:
1749 case X86::BI__builtin_ia32_psrldi512_mask:
1750 case X86::BI__builtin_ia32_psrlqi128_mask:
1751 case X86::BI__builtin_ia32_psrlqi256_mask:
1752 case X86::BI__builtin_ia32_psrlqi512_mask:
1753 case X86::BI__builtin_ia32_psrawi512_mask:
1754 case X86::BI__builtin_ia32_psrawi128_mask:
1755 case X86::BI__builtin_ia32_psrawi256_mask:
1756 case X86::BI__builtin_ia32_psrlwi512_mask:
1757 case X86::BI__builtin_ia32_psrlwi128_mask:
1758 case X86::BI__builtin_ia32_psrlwi256_mask:
1759 case X86::BI__builtin_ia32_psradi128_mask:
1760 case X86::BI__builtin_ia32_psradi256_mask:
1761 case X86::BI__builtin_ia32_psradi512_mask:
1762 case X86::BI__builtin_ia32_psraqi128_mask:
1763 case X86::BI__builtin_ia32_psraqi256_mask:
1764 case X86::BI__builtin_ia32_psraqi512_mask:
1765 case X86::BI__builtin_ia32_pslldi128_mask:
1766 case X86::BI__builtin_ia32_pslldi256_mask:
1767 case X86::BI__builtin_ia32_pslldi512_mask:
1768 case X86::BI__builtin_ia32_psllqi128_mask:
1769 case X86::BI__builtin_ia32_psllqi256_mask:
1770 case X86::BI__builtin_ia32_psllqi512_mask:
1771 case X86::BI__builtin_ia32_fpclasspd128_mask:
1772 case X86::BI__builtin_ia32_fpclasspd256_mask:
1773 case X86::BI__builtin_ia32_fpclassps128_mask:
1774 case X86::BI__builtin_ia32_fpclassps256_mask:
1775 case X86::BI__builtin_ia32_fpclassps512_mask:
1776 case X86::BI__builtin_ia32_fpclasspd512_mask:
1777 case X86::BI__builtin_ia32_fpclasssd_mask:
1778 case X86::BI__builtin_ia32_fpclassss_mask:
1779 i = 1; l = 0; u = 255;
1781 case X86::BI__builtin_ia32_palignr:
1782 case X86::BI__builtin_ia32_insertps128:
1783 case X86::BI__builtin_ia32_dpps:
1784 case X86::BI__builtin_ia32_dppd:
1785 case X86::BI__builtin_ia32_dpps256:
1786 case X86::BI__builtin_ia32_mpsadbw128:
1787 case X86::BI__builtin_ia32_mpsadbw256:
1788 case X86::BI__builtin_ia32_pcmpistrm128:
1789 case X86::BI__builtin_ia32_pcmpistri128:
1790 case X86::BI__builtin_ia32_pcmpistria128:
1791 case X86::BI__builtin_ia32_pcmpistric128:
1792 case X86::BI__builtin_ia32_pcmpistrio128:
1793 case X86::BI__builtin_ia32_pcmpistris128:
1794 case X86::BI__builtin_ia32_pcmpistriz128:
1795 case X86::BI__builtin_ia32_pclmulqdq128:
1796 case X86::BI__builtin_ia32_vperm2f128_pd256:
1797 case X86::BI__builtin_ia32_vperm2f128_ps256:
1798 case X86::BI__builtin_ia32_vperm2f128_si256:
1799 case X86::BI__builtin_ia32_permti256:
1800 i = 2; l = -128; u = 255;
1802 case X86::BI__builtin_ia32_palignr128:
1803 case X86::BI__builtin_ia32_palignr256:
1804 case X86::BI__builtin_ia32_palignr128_mask:
1805 case X86::BI__builtin_ia32_palignr256_mask:
1806 case X86::BI__builtin_ia32_palignr512_mask:
1807 case X86::BI__builtin_ia32_alignq512_mask:
1808 case X86::BI__builtin_ia32_alignd512_mask:
1809 case X86::BI__builtin_ia32_alignd128_mask:
1810 case X86::BI__builtin_ia32_alignd256_mask:
1811 case X86::BI__builtin_ia32_alignq128_mask:
1812 case X86::BI__builtin_ia32_alignq256_mask:
1813 case X86::BI__builtin_ia32_vcomisd:
1814 case X86::BI__builtin_ia32_vcomiss:
1815 case X86::BI__builtin_ia32_shuf_f32x4_mask:
1816 case X86::BI__builtin_ia32_shuf_f64x2_mask:
1817 case X86::BI__builtin_ia32_shuf_i32x4_mask:
1818 case X86::BI__builtin_ia32_shuf_i64x2_mask:
1819 case X86::BI__builtin_ia32_dbpsadbw128_mask:
1820 case X86::BI__builtin_ia32_dbpsadbw256_mask:
1821 case X86::BI__builtin_ia32_dbpsadbw512_mask:
1822 i = 2; l = 0; u = 255;
1824 case X86::BI__builtin_ia32_fixupimmpd512_mask:
1825 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
1826 case X86::BI__builtin_ia32_fixupimmps512_mask:
1827 case X86::BI__builtin_ia32_fixupimmps512_maskz:
1828 case X86::BI__builtin_ia32_fixupimmsd_mask:
1829 case X86::BI__builtin_ia32_fixupimmsd_maskz:
1830 case X86::BI__builtin_ia32_fixupimmss_mask:
1831 case X86::BI__builtin_ia32_fixupimmss_maskz:
1832 case X86::BI__builtin_ia32_fixupimmpd128_mask:
1833 case X86::BI__builtin_ia32_fixupimmpd128_maskz:
1834 case X86::BI__builtin_ia32_fixupimmpd256_mask:
1835 case X86::BI__builtin_ia32_fixupimmpd256_maskz:
1836 case X86::BI__builtin_ia32_fixupimmps128_mask:
1837 case X86::BI__builtin_ia32_fixupimmps128_maskz:
1838 case X86::BI__builtin_ia32_fixupimmps256_mask:
1839 case X86::BI__builtin_ia32_fixupimmps256_maskz:
1840 case X86::BI__builtin_ia32_pternlogd512_mask:
1841 case X86::BI__builtin_ia32_pternlogd512_maskz:
1842 case X86::BI__builtin_ia32_pternlogq512_mask:
1843 case X86::BI__builtin_ia32_pternlogq512_maskz:
1844 case X86::BI__builtin_ia32_pternlogd128_mask:
1845 case X86::BI__builtin_ia32_pternlogd128_maskz:
1846 case X86::BI__builtin_ia32_pternlogd256_mask:
1847 case X86::BI__builtin_ia32_pternlogd256_maskz:
1848 case X86::BI__builtin_ia32_pternlogq128_mask:
1849 case X86::BI__builtin_ia32_pternlogq128_maskz:
1850 case X86::BI__builtin_ia32_pternlogq256_mask:
1851 case X86::BI__builtin_ia32_pternlogq256_maskz:
1852 i = 3; l = 0; u = 255;
1854 case X86::BI__builtin_ia32_pcmpestrm128:
1855 case X86::BI__builtin_ia32_pcmpestri128:
1856 case X86::BI__builtin_ia32_pcmpestria128:
1857 case X86::BI__builtin_ia32_pcmpestric128:
1858 case X86::BI__builtin_ia32_pcmpestrio128:
1859 case X86::BI__builtin_ia32_pcmpestris128:
1860 case X86::BI__builtin_ia32_pcmpestriz128:
1861 i = 4; l = -128; u = 255;
1863 case X86::BI__builtin_ia32_rndscalesd_round_mask:
1864 case X86::BI__builtin_ia32_rndscaless_round_mask:
1865 i = 4; l = 0; u = 255;
1868 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1875 bool Sema::getFormatStringInfo(
const FormatAttr *Format,
bool IsCXXMember,
1876 FormatStringInfo *FSI) {
1877 FSI->HasVAListArg = Format->getFirstArg() == 0;
1878 FSI->FormatIdx = Format->getFormatIdx() - 1;
1879 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
1885 if(FSI->FormatIdx == 0)
1888 if (FSI->FirstDataArg != 0)
1889 --FSI->FirstDataArg;
1899 if (
auto nullability
1908 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
1910 dyn_cast<CompoundLiteralExpr>(Expr))
1912 dyn_cast<InitListExpr>(CLE->getInitializer()))
1913 Expr = ILE->getInit(0);
1923 const Expr *ArgExpr,
1927 S.
PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
1931 FormatStringInfo FSI;
1932 if ((GetFormatStringType(Format) == FST_NSString) &&
1933 getFormatStringInfo(Format,
false, &FSI)) {
1934 Idx = FSI.FormatIdx;
1947 bool Format =
false;
1954 for (
const auto *
I : FDecl->specific_attrs<FormatAttr>()) {
1960 if (!Format || NumArgs <= Idx)
1962 const Expr *FormatExpr = Args[Idx];
1963 if (
const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
1964 FormatExpr = CSCE->getSubExpr();
1974 S.
Diag(FormatExpr->
getExprLoc(), diag::warn_objc_cdirective_format_string)
1976 S.
Diag(FDecl->getLocation(), diag::note_entity_declared_at)
1992 ArrayRef<const Expr *> Args,
1994 assert((FDecl || Proto) &&
"Need a function declaration or prototype");
1997 llvm::SmallBitVector NonNullArgs;
2000 for (
const auto *
NonNull : FDecl->specific_attrs<NonNullAttr>()) {
2003 for (
const auto *Arg : Args)
2009 for (
unsigned Val :
NonNull->args()) {
2010 if (Val >= Args.size())
2012 if (NonNullArgs.empty())
2013 NonNullArgs.resize(Args.size());
2014 NonNullArgs.set(Val);
2019 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
2022 ArrayRef<ParmVarDecl*> parms;
2023 if (
const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
2024 parms = FD->parameters();
2026 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
2028 unsigned ParamIndex = 0;
2030 I !=
E; ++
I, ++ParamIndex) {
2032 if (PVD->hasAttr<NonNullAttr>() ||
2034 if (NonNullArgs.empty())
2035 NonNullArgs.resize(Args.size());
2037 NonNullArgs.set(ParamIndex);
2044 if (
const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
2063 if (NonNullArgs.empty())
2064 NonNullArgs.resize(Args.size());
2066 NonNullArgs.set(Index);
2075 for (
unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
2076 ArgIndex != ArgIndexEnd; ++ArgIndex) {
2077 if (NonNullArgs[ArgIndex])
2085 ArrayRef<const Expr *> Args,
bool IsMemberFunction,
2087 VariadicCallType CallType) {
2089 if (CurContext->isDependentContext())
2093 llvm::SmallBitVector CheckedVarArgs;
2095 for (
const auto *
I : FDecl->specific_attrs<FormatAttr>()) {
2097 CheckedVarArgs.resize(Args.size());
2099 CheckFormatArguments(
I, Args, IsMemberFunction, CallType, Loc, Range,
2106 if (CallType != VariadicDoesNotApply) {
2108 : FDecl && isa<FunctionDecl>(FDecl)
2109 ? cast<FunctionDecl>(FDecl)->getNumParams()
2110 : FDecl && isa<ObjCMethodDecl>(FDecl)
2111 ? cast<ObjCMethodDecl>(FDecl)->param_size()
2114 for (
unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
2116 if (
const Expr *Arg = Args[ArgIdx]) {
2117 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
2118 checkVariadicArgument(Arg, CallType);
2123 if (FDecl || Proto) {
2128 for (
const auto *
I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
2129 CheckArgumentWithTypeTag(
I, Args.data());
2137 ArrayRef<const Expr *> Args,
2140 VariadicCallType CallType =
2141 Proto->
isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
2142 checkCall(FDecl, Proto, Args,
true, Loc,
SourceRange(),
2150 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
2151 isa<CXXMethodDecl>(FDecl);
2152 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
2153 IsMemberOperatorCall;
2154 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
2158 if (IsMemberOperatorCall) {
2165 checkCall(FDecl, Proto, llvm::makeArrayRef(Args, NumArgs),
2167 TheCall->
getCallee()->getSourceRange(), CallType);
2175 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
2176 if (getLangOpts().ObjC1)
2184 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
2185 CheckStrlcpycatArguments(TheCall, FnInfo);
2186 else if (CMId == Builtin::BIstrncat)
2187 CheckStrncatArguments(TheCall, FnInfo);
2189 CheckMemaccessArguments(TheCall, CMId, FnInfo);
2195 ArrayRef<const Expr *> Args) {
2196 VariadicCallType CallType =
2197 Method->
isVariadic() ? VariadicMethod : VariadicDoesNotApply;
2199 checkCall(Method,
nullptr, Args,
2209 if (
const auto *V = dyn_cast<VarDecl>(NDecl))
2210 Ty = V->getType().getNonReferenceType();
2211 else if (
const auto *F = dyn_cast<FieldDecl>(NDecl))
2212 Ty = F->getType().getNonReferenceType();
2220 VariadicCallType CallType;
2222 CallType = VariadicDoesNotApply;
2224 CallType = VariadicBlock;
2226 CallType = VariadicFunction;
2229 checkCall(NDecl, Proto,
2232 TheCall->
getCallee()->getSourceRange(), CallType);
2240 VariadicCallType CallType = getVariadicCallType(
nullptr, Proto,
2242 checkCall(
nullptr, Proto,
2245 TheCall->
getCallee()->getSourceRange(), CallType);
2251 if (!llvm::isValidAtomicOrderingCABI(Ordering))
2254 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
2256 case AtomicExpr::AO__c11_atomic_init:
2257 llvm_unreachable(
"There is no ordering argument for an init");
2259 case AtomicExpr::AO__c11_atomic_load:
2260 case AtomicExpr::AO__atomic_load_n:
2261 case AtomicExpr::AO__atomic_load:
2262 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
2263 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
2265 case AtomicExpr::AO__c11_atomic_store:
2266 case AtomicExpr::AO__atomic_store:
2267 case AtomicExpr::AO__atomic_store_n:
2268 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
2269 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
2270 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
2279 CallExpr *TheCall = cast<CallExpr>(TheCallResult.
get());
2303 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
2304 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
2312 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
2313 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
2314 AtomicExpr::AO__atomic_load,
2315 "need to update code for modified C11 atomics");
2316 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
2317 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
2318 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
2319 Op == AtomicExpr::AO__atomic_store_n ||
2320 Op == AtomicExpr::AO__atomic_exchange_n ||
2321 Op == AtomicExpr::AO__atomic_compare_exchange_n;
2322 bool IsAddSub =
false;
2325 case AtomicExpr::AO__c11_atomic_init:
2329 case AtomicExpr::AO__c11_atomic_load:
2330 case AtomicExpr::AO__atomic_load_n:
2334 case AtomicExpr::AO__atomic_load:
2338 case AtomicExpr::AO__c11_atomic_store:
2339 case AtomicExpr::AO__atomic_store:
2340 case AtomicExpr::AO__atomic_store_n:
2344 case AtomicExpr::AO__c11_atomic_fetch_add:
2345 case AtomicExpr::AO__c11_atomic_fetch_sub:
2346 case AtomicExpr::AO__atomic_fetch_add:
2347 case AtomicExpr::AO__atomic_fetch_sub:
2348 case AtomicExpr::AO__atomic_add_fetch:
2349 case AtomicExpr::AO__atomic_sub_fetch:
2352 case AtomicExpr::AO__c11_atomic_fetch_and:
2353 case AtomicExpr::AO__c11_atomic_fetch_or:
2354 case AtomicExpr::AO__c11_atomic_fetch_xor:
2355 case AtomicExpr::AO__atomic_fetch_and:
2356 case AtomicExpr::AO__atomic_fetch_or:
2357 case AtomicExpr::AO__atomic_fetch_xor:
2358 case AtomicExpr::AO__atomic_fetch_nand:
2359 case AtomicExpr::AO__atomic_and_fetch:
2360 case AtomicExpr::AO__atomic_or_fetch:
2361 case AtomicExpr::AO__atomic_xor_fetch:
2362 case AtomicExpr::AO__atomic_nand_fetch:
2366 case AtomicExpr::AO__c11_atomic_exchange:
2367 case AtomicExpr::AO__atomic_exchange_n:
2371 case AtomicExpr::AO__atomic_exchange:
2375 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
2376 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
2380 case AtomicExpr::AO__atomic_compare_exchange:
2381 case AtomicExpr::AO__atomic_compare_exchange_n:
2388 Diag(TheCall->
getLocEnd(), diag::err_typecheck_call_too_few_args)
2389 << 0 << NumArgs[Form] << TheCall->
getNumArgs()
2390 << TheCall->
getCallee()->getSourceRange();
2392 }
else if (TheCall->
getNumArgs() > NumArgs[Form]) {
2393 Diag(TheCall->
getArg(NumArgs[Form])->getLocStart(),
2394 diag::err_typecheck_call_too_many_args)
2395 << 0 << NumArgs[Form] << TheCall->
getNumArgs()
2396 << TheCall->
getCallee()->getSourceRange();
2402 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
2406 Ptr = ConvertedPtr.
get();
2409 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
2410 << Ptr->
getType() << Ptr->getSourceRange();
2419 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
2420 << Ptr->
getType() << Ptr->getSourceRange();
2424 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
2425 << Ptr->
getType() << Ptr->getSourceRange();
2429 }
else if (Form != Load && Form != LoadCopy) {
2431 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
2432 << Ptr->
getType() << Ptr->getSourceRange();
2438 if (Form == Arithmetic) {
2441 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
2442 << IsC11 << Ptr->
getType() << Ptr->getSourceRange();
2446 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
2447 << IsC11 << Ptr->
getType() << Ptr->getSourceRange();
2451 RequireCompleteType(Ptr->getLocStart(), ValType->
getPointeeType(),
2452 diag::err_incomplete_type)) {
2458 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
2459 << IsC11 << Ptr->
getType() << Ptr->getSourceRange();
2467 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
2468 << Ptr->
getType() << Ptr->getSourceRange();
2483 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
2484 << ValType << Ptr->getSourceRange();
2494 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init)
2496 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
2508 for (
unsigned i = 1; i != NumArgs[Form]; ++i) {
2510 if (i < NumVals[Form] + 1) {
2517 assert(Form != Load);
2518 if (Form == Init || (Form == Arithmetic && ValType->
isIntegerType()))
2520 else if (Form == Copy || Form == Xchg)
2522 else if (Form == Arithmetic)
2530 AS = PtrTy->getPointeeType().getAddressSpace();
2562 SubExprs.push_back(Ptr);
2566 SubExprs.push_back(TheCall->
getArg(1));
2569 SubExprs.push_back(TheCall->
getArg(1));
2575 SubExprs.push_back(TheCall->
getArg(2));
2576 SubExprs.push_back(TheCall->
getArg(1));
2580 SubExprs.push_back(TheCall->
getArg(3));
2581 SubExprs.push_back(TheCall->
getArg(1));
2582 SubExprs.push_back(TheCall->
getArg(2));
2585 SubExprs.push_back(TheCall->
getArg(3));
2586 SubExprs.push_back(TheCall->
getArg(1));
2587 SubExprs.push_back(TheCall->
getArg(4));
2588 SubExprs.push_back(TheCall->
getArg(2));
2591 SubExprs.push_back(TheCall->
getArg(4));
2592 SubExprs.push_back(TheCall->
getArg(1));
2593 SubExprs.push_back(TheCall->
getArg(5));
2594 SubExprs.push_back(TheCall->
getArg(2));
2595 SubExprs.push_back(TheCall->
getArg(3));
2599 if (SubExprs.size() >= 2 && Form != Init) {
2600 llvm::APSInt Result(32);
2601 if (SubExprs[1]->isIntegerConstantExpr(Result,
Context) &&
2603 Diag(SubExprs[1]->getLocStart(),
2604 diag::warn_atomic_op_has_invalid_memory_order)
2605 << SubExprs[1]->getSourceRange();
2609 SubExprs, ResultType, Op,
2612 if ((Op == AtomicExpr::AO__c11_atomic_load ||
2613 (Op == AtomicExpr::AO__c11_atomic_store)) &&
2616 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
2630 assert(Fn &&
"builtin call without direct callee!");
2654 Sema::SemaBuiltinAtomicOverloaded(
ExprResult TheCallResult) {
2661 Diag(TheCall->
getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
2663 << TheCall->
getCallee()->getSourceRange();
2673 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
2676 FirstArg = FirstArgResult.
get();
2677 TheCall->
setArg(0, FirstArg);
2682 << FirstArg->
getType() << FirstArg->getSourceRange();
2689 Diag(DRE->
getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
2690 << FirstArg->
getType() << FirstArg->getSourceRange();
2704 << ValType << FirstArg->getSourceRange();
2718 #define BUILTIN_ROW(x) \
2719 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
2720 Builtin::BI##x##_8, Builtin::BI##x##_16 }
2722 static const unsigned BuiltinIndices[][5] = {
2748 case 1: SizeIndex = 0;
break;
2749 case 2: SizeIndex = 1;
break;
2750 case 4: SizeIndex = 2;
break;
2751 case 8: SizeIndex = 3;
break;
2752 case 16: SizeIndex = 4;
break;
2755 << FirstArg->
getType() << FirstArg->getSourceRange();
2763 unsigned BuiltinID = FDecl->getBuiltinID();
2764 unsigned BuiltinIndex, NumFixed = 1;
2765 bool WarnAboutSemanticsChange =
false;
2766 switch (BuiltinID) {
2767 default: llvm_unreachable(
"Unknown overloaded atomic builtin!");
2768 case Builtin::BI__sync_fetch_and_add:
2769 case Builtin::BI__sync_fetch_and_add_1:
2770 case Builtin::BI__sync_fetch_and_add_2:
2771 case Builtin::BI__sync_fetch_and_add_4:
2772 case Builtin::BI__sync_fetch_and_add_8:
2773 case Builtin::BI__sync_fetch_and_add_16:
2777 case Builtin::BI__sync_fetch_and_sub:
2778 case Builtin::BI__sync_fetch_and_sub_1:
2779 case Builtin::BI__sync_fetch_and_sub_2:
2780 case Builtin::BI__sync_fetch_and_sub_4:
2781 case Builtin::BI__sync_fetch_and_sub_8:
2782 case Builtin::BI__sync_fetch_and_sub_16:
2786 case Builtin::BI__sync_fetch_and_or:
2787 case Builtin::BI__sync_fetch_and_or_1:
2788 case Builtin::BI__sync_fetch_and_or_2:
2789 case Builtin::BI__sync_fetch_and_or_4:
2790 case Builtin::BI__sync_fetch_and_or_8:
2791 case Builtin::BI__sync_fetch_and_or_16:
2795 case Builtin::BI__sync_fetch_and_and:
2796 case Builtin::BI__sync_fetch_and_and_1:
2797 case Builtin::BI__sync_fetch_and_and_2:
2798 case Builtin::BI__sync_fetch_and_and_4:
2799 case Builtin::BI__sync_fetch_and_and_8:
2800 case Builtin::BI__sync_fetch_and_and_16:
2804 case Builtin::BI__sync_fetch_and_xor:
2805 case Builtin::BI__sync_fetch_and_xor_1:
2806 case Builtin::BI__sync_fetch_and_xor_2:
2807 case Builtin::BI__sync_fetch_and_xor_4:
2808 case Builtin::BI__sync_fetch_and_xor_8:
2809 case Builtin::BI__sync_fetch_and_xor_16:
2813 case Builtin::BI__sync_fetch_and_nand:
2814 case Builtin::BI__sync_fetch_and_nand_1:
2815 case Builtin::BI__sync_fetch_and_nand_2:
2816 case Builtin::BI__sync_fetch_and_nand_4:
2817 case Builtin::BI__sync_fetch_and_nand_8:
2818 case Builtin::BI__sync_fetch_and_nand_16:
2820 WarnAboutSemanticsChange =
true;
2823 case Builtin::BI__sync_add_and_fetch:
2824 case Builtin::BI__sync_add_and_fetch_1:
2825 case Builtin::BI__sync_add_and_fetch_2:
2826 case Builtin::BI__sync_add_and_fetch_4:
2827 case Builtin::BI__sync_add_and_fetch_8:
2828 case Builtin::BI__sync_add_and_fetch_16:
2832 case Builtin::BI__sync_sub_and_fetch:
2833 case Builtin::BI__sync_sub_and_fetch_1:
2834 case Builtin::BI__sync_sub_and_fetch_2:
2835 case Builtin::BI__sync_sub_and_fetch_4:
2836 case Builtin::BI__sync_sub_and_fetch_8:
2837 case Builtin::BI__sync_sub_and_fetch_16:
2841 case Builtin::BI__sync_and_and_fetch:
2842 case Builtin::BI__sync_and_and_fetch_1:
2843 case Builtin::BI__sync_and_and_fetch_2:
2844 case Builtin::BI__sync_and_and_fetch_4:
2845 case Builtin::BI__sync_and_and_fetch_8:
2846 case Builtin::BI__sync_and_and_fetch_16:
2850 case Builtin::BI__sync_or_and_fetch:
2851 case Builtin::BI__sync_or_and_fetch_1:
2852 case Builtin::BI__sync_or_and_fetch_2:
2853 case Builtin::BI__sync_or_and_fetch_4:
2854 case Builtin::BI__sync_or_and_fetch_8:
2855 case Builtin::BI__sync_or_and_fetch_16:
2859 case Builtin::BI__sync_xor_and_fetch:
2860 case Builtin::BI__sync_xor_and_fetch_1:
2861 case Builtin::BI__sync_xor_and_fetch_2:
2862 case Builtin::BI__sync_xor_and_fetch_4:
2863 case Builtin::BI__sync_xor_and_fetch_8:
2864 case Builtin::BI__sync_xor_and_fetch_16:
2868 case Builtin::BI__sync_nand_and_fetch:
2869 case Builtin::BI__sync_nand_and_fetch_1:
2870 case Builtin::BI__sync_nand_and_fetch_2:
2871 case Builtin::BI__sync_nand_and_fetch_4:
2872 case Builtin::BI__sync_nand_and_fetch_8:
2873 case Builtin::BI__sync_nand_and_fetch_16:
2875 WarnAboutSemanticsChange =
true;
2878 case Builtin::BI__sync_val_compare_and_swap:
2879 case Builtin::BI__sync_val_compare_and_swap_1:
2880 case Builtin::BI__sync_val_compare_and_swap_2:
2881 case Builtin::BI__sync_val_compare_and_swap_4:
2882 case Builtin::BI__sync_val_compare_and_swap_8:
2883 case Builtin::BI__sync_val_compare_and_swap_16:
2888 case Builtin::BI__sync_bool_compare_and_swap:
2889 case Builtin::BI__sync_bool_compare_and_swap_1:
2890 case Builtin::BI__sync_bool_compare_and_swap_2:
2891 case Builtin::BI__sync_bool_compare_and_swap_4:
2892 case Builtin::BI__sync_bool_compare_and_swap_8:
2893 case Builtin::BI__sync_bool_compare_and_swap_16:
2899 case Builtin::BI__sync_lock_test_and_set:
2900 case Builtin::BI__sync_lock_test_and_set_1:
2901 case Builtin::BI__sync_lock_test_and_set_2:
2902 case Builtin::BI__sync_lock_test_and_set_4:
2903 case Builtin::BI__sync_lock_test_and_set_8:
2904 case Builtin::BI__sync_lock_test_and_set_16:
2908 case Builtin::BI__sync_lock_release:
2909 case Builtin::BI__sync_lock_release_1:
2910 case Builtin::BI__sync_lock_release_2:
2911 case Builtin::BI__sync_lock_release_4:
2912 case Builtin::BI__sync_lock_release_8:
2913 case Builtin::BI__sync_lock_release_16:
2919 case Builtin::BI__sync_swap:
2920 case Builtin::BI__sync_swap_1:
2921 case Builtin::BI__sync_swap_2:
2922 case Builtin::BI__sync_swap_4:
2923 case Builtin::BI__sync_swap_8:
2924 case Builtin::BI__sync_swap_16:
2932 Diag(TheCall->
getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
2934 << TheCall->
getCallee()->getSourceRange();
2938 if (WarnAboutSemanticsChange) {
2939 Diag(TheCall->
getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
2940 << TheCall->
getCallee()->getSourceRange();
2945 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
2948 if (NewBuiltinID == BuiltinID)
2949 NewBuiltinDecl = FDecl;
2954 LookupName(Res, TUScope,
true);
2955 assert(Res.getFoundDecl());
2956 NewBuiltinDecl = dyn_cast<
FunctionDecl>(Res.getFoundDecl());
2957 if (!NewBuiltinDecl)
2964 for (
unsigned i = 0; i != NumFixed; ++i) {
3001 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
3002 CK_BuiltinFnToFnPtr);
3010 return TheCallResult;
3024 unsigned BuiltinID = FDecl->getBuiltinID();
3025 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
3026 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
3027 "Unexpected nontemporal load/store builtin!");
3028 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
3029 unsigned numArgs = isStore ? 2 : 1;
3039 Expr *PointerArg = TheCall->
getArg(numArgs - 1);
3041 DefaultFunctionArrayLvalueConversion(PointerArg);
3045 PointerArg = PointerArgResult.
get();
3046 TheCall->
setArg(numArgs - 1, PointerArg);
3050 Diag(DRE->
getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
3051 << PointerArg->
getType() << PointerArg->getSourceRange();
3063 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
3064 << PointerArg->
getType() << PointerArg->getSourceRange();
3070 return TheCallResult;
3075 Context, ValType,
false);
3076 ValArg = PerformCopyInitialization(Entity,
SourceLocation(), ValArg);
3082 return TheCallResult;
3089 bool Sema::CheckObjCString(
Expr *Arg) {
3093 if (!Literal || !Literal->
isAscii()) {
3094 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
3095 << Arg->getSourceRange();
3100 StringRef String = Literal->
getString();
3101 unsigned NumBytes = String.size();
3103 const UTF8 *FromPtr = (
const UTF8 *)String.data();
3104 UTF16 *ToPtr = &ToBuf[0];
3106 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
3107 &ToPtr, ToPtr + NumBytes,
3110 if (Result != conversionOK)
3111 Diag(Arg->getLocStart(),
3112 diag::warn_cfstring_truncated) << Arg->getSourceRange();
3120 bool Sema::SemaBuiltinVAStartImpl(
CallExpr *TheCall) {
3124 diag::err_typecheck_call_too_many_args)
3126 << Fn->getSourceRange()
3128 (*(TheCall->
arg_end()-1))->getLocEnd());
3134 diag::err_typecheck_call_too_few_args_at_least)
3148 isVariadic = FD->isVariadic();
3150 isVariadic = getCurMethodDecl()->isVariadic();
3153 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
3159 bool SecondArgIsLastNamedArgument =
false;
3166 bool IsCRegister =
false;
3168 if (
const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
3169 if (
const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
3176 LastArg = FD->parameters().back();
3178 LastArg = getCurMethodDecl()->parameters().back();
3179 SecondArgIsLastNamedArgument = PV == LastArg;
3181 Type = PV->getType();
3182 ParamLoc = PV->getLocation();
3184 PV->getStorageClass() ==
SC_Register && !getLangOpts().CPlusPlus;
3188 if (!SecondArgIsLastNamedArgument)
3190 diag::warn_second_arg_of_va_start_not_last_named_param);
3194 unsigned Reason = 0;
3196 else if (IsCRegister) Reason = 2;
3197 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
3198 Diag(ParamLoc, diag::note_parameter_type) << Type;
3208 bool Sema::SemaBuiltinVAStart(
CallExpr *TheCall) {
3217 CC = FD->getType()->getAs<
FunctionType>()->getCallConv();
3221 diag::err_va_start_used_in_wrong_abi_function)
3222 << (OS != llvm::Triple::Win32);
3224 return SemaBuiltinVAStartImpl(TheCall);
3230 bool Sema::SemaBuiltinMSVAStart(
CallExpr *TheCall) {
3234 if (TT.getArch() != llvm::Triple::x86_64)
3235 return Diag(Callee->getLocStart(), diag::err_x86_builtin_32_bit_tgt);
3239 CC = FD->getType()->getAs<
FunctionType>()->getCallConv();
3242 return Diag(Callee->getLocStart(),
3243 diag::err_ms_va_start_used_in_sysv_function);
3244 return SemaBuiltinVAStartImpl(TheCall);
3247 bool Sema::SemaBuiltinVAStartARM(
CallExpr *Call) {
3255 diag::err_typecheck_call_too_few_args_at_least)
3263 IsVariadic = FD->isVariadic();
3265 IsVariadic = MD->isVariadic();
3267 llvm_unreachable(
"unexpected statement type");
3270 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
3281 } ArgumentTypes[] = {
3286 for (
const auto &AT : ArgumentTypes) {
3290 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
3291 << Arg->
getType() << AT.Type << 1
3293 << AT.ArgNo + 1 << Arg->
getType() << AT.Type;
3301 bool Sema::SemaBuiltinUnorderedCompare(
CallExpr *TheCall) {
3303 return Diag(TheCall->
getLocEnd(), diag::err_typecheck_call_too_few_args)
3306 return Diag(TheCall->
getArg(2)->getLocStart(),
3307 diag::err_typecheck_call_too_many_args)
3310 (*(TheCall->
arg_end()-1))->getLocEnd());
3317 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1,
false);
3318 if (OrigArg0.isInvalid() || OrigArg1.
isInvalid())
3324 TheCall->
setArg(0, OrigArg0.get());
3333 return Diag(OrigArg0.get()->getLocStart(),
3334 diag::err_typecheck_call_invalid_ordered_compare)
3335 << OrigArg0.get()->getType() << OrigArg1.
get()->
getType()
3336 <<
SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.
get()->getLocEnd());
3345 bool Sema::SemaBuiltinFPClassification(
CallExpr *TheCall,
unsigned NumArgs) {
3347 return Diag(TheCall->
getLocEnd(), diag::err_typecheck_call_too_few_args)
3350 return Diag(TheCall->
getArg(NumArgs)->getLocStart(),
3351 diag::err_typecheck_call_too_many_args)
3354 (*(TheCall->
arg_end()-1))->getLocEnd());
3358 if (OrigArg->isTypeDependent())
3362 if (!OrigArg->getType()->isRealFloatingType())
3363 return Diag(OrigArg->getLocStart(),
3364 diag::err_typecheck_call_invalid_unary_fp)
3365 << OrigArg->getType() << OrigArg->getSourceRange();
3369 Expr *CastArg = Cast->getSubExpr();
3371 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
3372 "promotion from float to double is the only expected cast here");
3373 Cast->setSubExpr(
nullptr);
3374 TheCall->
setArg(NumArgs-1, CastArg);
3386 diag::err_typecheck_call_too_few_args_at_least)
3388 << TheCall->getSourceRange());
3394 unsigned numElements = 0;
3403 diag::err_shufflevector_non_vector)
3405 TheCall->
getArg(1)->getLocEnd()));
3408 unsigned numResElements = TheCall->
getNumArgs() - 2;
3417 diag::err_shufflevector_incompatible_vector)
3419 TheCall->
getArg(1)->getLocEnd()));
3422 diag::err_shufflevector_incompatible_vector)
3424 TheCall->
getArg(1)->getLocEnd()));
3425 }
else if (numElements != numResElements) {
3432 for (
unsigned i = 2; i < TheCall->
getNumArgs(); i++) {
3437 llvm::APSInt Result(32);
3440 diag::err_shufflevector_nonconstant_argument)
3441 << TheCall->
getArg(i)->getSourceRange());
3444 if (Result.isSigned() && Result.isAllOnesValue())
3447 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
3449 diag::err_shufflevector_argument_too_large)
3450 << TheCall->
getArg(i)->getSourceRange());
3455 for (
unsigned i = 0, e = TheCall->
getNumArgs(); i != e; i++) {
3456 exprs.push_back(TheCall->
getArg(i));
3457 TheCall->
setArg(i,
nullptr);
3476 diag::err_convertvector_non_vector)
3477 << E->getSourceRange());
3480 diag::err_convertvector_non_vector_type));
3485 if (SrcElts != DstElts)
3487 diag::err_convertvector_incompatible_vector)
3488 << E->getSourceRange());
3498 bool Sema::SemaBuiltinPrefetch(
CallExpr *TheCall) {
3503 diag::err_typecheck_call_too_many_args_at_most)
3504 << 0 << 3 << NumArgs
3505 << TheCall->getSourceRange();
3509 for (
unsigned i = 1; i !=
NumArgs; ++i)
3510 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
3519 bool Sema::SemaBuiltinAssume(
CallExpr *TheCall) {
3524 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
3525 << Arg->getSourceRange()
3533 bool Sema::SemaBuiltinAssumeAligned(
CallExpr *TheCall) {
3538 diag::err_typecheck_call_too_many_args_at_most)
3539 << 0 << 3 << NumArgs
3540 << TheCall->getSourceRange();
3547 llvm::APSInt Result;
3548 if (SemaBuiltinConstantArg(TheCall, 1, Result))
3551 if (!Result.isPowerOf2())
3553 diag::err_alignment_not_power_of_two)
3554 << Arg->getSourceRange();
3562 if (Arg.isInvalid())
return true;
3563 TheCall->
setArg(2, Arg.get());
3571 bool Sema::SemaBuiltinConstantArg(
CallExpr *TheCall,
int ArgNum,
3572 llvm::APSInt &Result) {
3580 return Diag(TheCall->
getLocStart(), diag::err_constant_integer_arg_type)
3581 << FDecl->getDeclName() << Arg->getSourceRange();
3588 bool Sema::SemaBuiltinConstantArgRange(
CallExpr *TheCall,
int ArgNum,
3589 int Low,
int High) {
3590 llvm::APSInt Result;
3598 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3601 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
3603 << Low << High << Arg->getSourceRange();
3610 bool Sema::SemaBuiltinARMSpecialReg(
unsigned BuiltinID,
CallExpr *TheCall,
3611 int ArgNum,
unsigned ExpectedFieldNum,
3613 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
3614 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
3615 BuiltinID == ARM::BI__builtin_arm_rsr ||
3616 BuiltinID == ARM::BI__builtin_arm_rsrp ||
3617 BuiltinID == ARM::BI__builtin_arm_wsr ||
3618 BuiltinID == ARM::BI__builtin_arm_wsrp;
3619 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
3620 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
3621 BuiltinID == AArch64::BI__builtin_arm_rsr ||
3622 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
3623 BuiltinID == AArch64::BI__builtin_arm_wsr ||
3624 BuiltinID == AArch64::BI__builtin_arm_wsrp;
3625 assert((IsARMBuiltin || IsAArch64Builtin) &&
"Unexpected ARM builtin.");
3634 return Diag(TheCall->
getLocStart(), diag::err_expr_not_string_literal)
3635 << Arg->getSourceRange();
3640 Reg.split(Fields,
":");
3642 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
3644 << Arg->getSourceRange();
3650 if (Fields.size() > 1) {
3651 bool FiveFields = Fields.size() == 5;
3653 bool ValidString =
true;
3655 ValidString &= Fields[0].startswith_lower(
"cp") ||
3656 Fields[0].startswith_lower(
"p");
3659 Fields[0].drop_front(Fields[0].startswith_lower(
"cp") ? 2 : 1);
3661 ValidString &= Fields[2].startswith_lower(
"c");
3663 Fields[2] = Fields[2].drop_front(1);
3666 ValidString &= Fields[3].startswith_lower(
"c");
3668 Fields[3] = Fields[3].drop_front(1);
3674 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 7, 15, 15});
3676 Ranges.append({15, 7, 15});
3678 for (
unsigned i=0; i<Fields.size(); ++i) {
3680 ValidString &= !Fields[i].getAsInteger(10, IntField);
3681 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
3686 << Arg->getSourceRange();
3688 }
else if (IsAArch64Builtin && Fields.size() == 1) {
3698 std::string RegLower = Reg.lower();
3699 if (RegLower !=
"spsel" && RegLower !=
"daifset" && RegLower !=
"daifclr" &&
3700 RegLower !=
"pan" && RegLower !=
"uao")
3703 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
3712 bool Sema::SemaBuiltinLongjmp(
CallExpr *TheCall) {
3714 return Diag(TheCall->
getLocStart(), diag::err_builtin_longjmp_unsupported)
3718 llvm::APSInt Result;
3721 if (SemaBuiltinConstantArg(TheCall, 1, Result))
3725 return Diag(TheCall->
getLocStart(), diag::err_builtin_longjmp_invalid_val)
3726 <<
SourceRange(Arg->getLocStart(), Arg->getLocEnd());
3733 bool Sema::SemaBuiltinSetjmp(
CallExpr *TheCall) {
3735 return Diag(TheCall->
getLocStart(), diag::err_builtin_setjmp_unsupported)
3741 class UncoveredArgHandler {
3742 enum {
Unknown = -1, AllCovered = -2 };
3743 signed FirstUncoveredArg;
3747 UncoveredArgHandler() : FirstUncoveredArg(
Unknown) { }
3749 bool hasUncoveredArg()
const {
3750 return (FirstUncoveredArg >= 0);
3753 unsigned getUncoveredArg()
const {
3754 assert(hasUncoveredArg() &&
"no uncovered argument");
3755 return FirstUncoveredArg;
3758 void setAllCovered() {
3761 DiagnosticExprs.clear();
3762 FirstUncoveredArg = AllCovered;
3765 void Update(
signed NewFirstUncoveredArg,
const Expr *StrExpr) {
3766 assert(NewFirstUncoveredArg >= 0 &&
"Outside range");
3769 if (FirstUncoveredArg == AllCovered)
3774 if (NewFirstUncoveredArg == FirstUncoveredArg)
3775 DiagnosticExprs.push_back(StrExpr);
3776 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
3777 DiagnosticExprs.clear();
3778 DiagnosticExprs.push_back(StrExpr);
3779 FirstUncoveredArg = NewFirstUncoveredArg;
3783 void Diagnose(
Sema &
S,
bool IsFunctionCall,
const Expr *ArgExpr);
3788 SLCT_UncheckedLiteral,
3794 const Expr *OrigFormatExpr,
3795 ArrayRef<const Expr *> Args,
3796 bool HasVAListArg,
unsigned format_idx,
3797 unsigned firstDataArg,
3799 bool inFunctionCall,
3801 llvm::SmallBitVector &CheckedVarArgs,
3802 UncoveredArgHandler &UncoveredArg);
3810 bool HasVAListArg,
unsigned format_idx,
3813 llvm::SmallBitVector &CheckedVarArgs,
3814 UncoveredArgHandler &UncoveredArg) {
3817 return SLCT_NotALiteral;
3826 return SLCT_UncheckedLiteral;
3828 switch (E->getStmtClass()) {
3829 case Stmt::BinaryConditionalOperatorClass:
3830 case Stmt::ConditionalOperatorClass: {
3834 cast<AbstractConditionalOperator>(
E);
3839 bool CheckLeft =
true, CheckRight =
true;
3851 Left = SLCT_UncheckedLiteral;
3854 HasVAListArg, format_idx, firstDataArg,
3855 Type, CallType, InFunctionCall,
3856 CheckedVarArgs, UncoveredArg);
3857 if (Left == SLCT_NotALiteral || !CheckRight)
3863 HasVAListArg, format_idx, firstDataArg,
3864 Type, CallType, InFunctionCall, CheckedVarArgs,
3867 return (CheckLeft && Left < Right) ? Left : Right;
3870 case Stmt::ImplicitCastExprClass: {
3871 E = cast<ImplicitCastExpr>(
E)->getSubExpr();
3875 case Stmt::OpaqueValueExprClass:
3876 if (
const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
3880 return SLCT_NotALiteral;
3882 case Stmt::PredefinedExprClass:
3886 return SLCT_UncheckedLiteral;
3888 case Stmt::DeclRefExprClass: {
3894 bool isConstant =
false;
3898 isConstant = AT->getElementType().isConstant(S.
Context);
3901 PT->getPointeeType().isConstant(S.
Context);
3909 if (
const Expr *Init = VD->getAnyInitializer()) {
3911 if (
const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
3912 if (InitList->isStringLiteralInit())
3913 Init = InitList->getInit(0)->IgnoreParenImpCasts();
3916 HasVAListArg, format_idx,
3917 firstDataArg, Type, CallType,
3918 false, CheckedVarArgs,
3938 if (
const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
3939 if (
const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
3940 int PVIndex = PV->getFunctionScopeIndex() + 1;
3941 for (
const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
3944 if (MD->isInstance())
3948 if (PVIndex == PVFormat->getFormatIdx() &&
3950 return SLCT_UncheckedLiteral;
3957 return SLCT_NotALiteral;
3960 case Stmt::CallExprClass:
3961 case Stmt::CXXMemberCallExprClass: {
3964 if (
const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
3965 unsigned ArgIndex = FA->getFormatIdx();
3967 if (MD->isInstance())
3972 HasVAListArg, format_idx, firstDataArg,
3973 Type, CallType, InFunctionCall,
3974 CheckedVarArgs, UncoveredArg);
3975 }
else if (
const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
3976 unsigned BuiltinID = FD->getBuiltinID();
3977 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
3978 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
3981 HasVAListArg, format_idx,
3982 firstDataArg, Type, CallType,
3983 InFunctionCall, CheckedVarArgs,
3989 return SLCT_NotALiteral;
3991 case Stmt::ObjCStringLiteralClass:
3992 case Stmt::StringLiteralClass: {
3998 StrE = cast<StringLiteral>(
E);
4002 firstDataArg, Type, InFunctionCall, CallType,
4003 CheckedVarArgs, UncoveredArg);
4004 return SLCT_CheckedLiteral;
4007 return SLCT_NotALiteral;
4011 return SLCT_NotALiteral;
4016 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
4017 .Case(
"scanf", FST_Scanf)
4018 .Cases(
"printf",
"printf0", FST_Printf)
4019 .Cases(
"NSString",
"CFString", FST_NSString)
4020 .Case(
"strftime", FST_Strftime)
4021 .Case(
"strfmon", FST_Strfmon)
4022 .Cases(
"kprintf",
"cmn_err",
"vcmn_err",
"zcmn_err", FST_Kprintf)
4023 .Case(
"freebsd_kprintf", FST_FreeBSDKPrintf)
4024 .Case(
"os_trace", FST_OSTrace)
4025 .Default(FST_Unknown);
4031 bool Sema::CheckFormatArguments(
const FormatAttr *Format,
4034 VariadicCallType CallType,
4036 llvm::SmallBitVector &CheckedVarArgs) {
4037 FormatStringInfo FSI;
4038 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
4039 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
4040 FSI.FirstDataArg, GetFormatStringType(Format),
4041 CallType, Loc, Range, CheckedVarArgs);
4045 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
4046 bool HasVAListArg,
unsigned format_idx,
4047 unsigned firstDataArg, FormatStringType Type,
4048 VariadicCallType CallType,
4050 llvm::SmallBitVector &CheckedVarArgs) {
4052 if (format_idx >= Args.size()) {
4053 Diag(Loc, diag::warn_missing_format_string) << Range;
4071 UncoveredArgHandler UncoveredArg;
4074 format_idx, firstDataArg, Type, CallType,
4075 true, CheckedVarArgs,
4079 if (UncoveredArg.hasUncoveredArg()) {
4080 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
4081 assert(ArgIdx < Args.size() &&
"ArgIdx outside bounds");
4082 UncoveredArg.Diagnose(*
this,
true, Args[ArgIdx]);
4085 if (CT != SLCT_NotALiteral)
4087 return CT == SLCT_CheckedLiteral;
4091 if (Type == FST_Strftime)
4099 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
4104 if (Args.size() == firstDataArg) {
4105 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
4106 << OrigFormatExpr->getSourceRange();
4111 case FST_FreeBSDKPrintf:
4113 Diag(FormatLoc, diag::note_format_security_fixit)
4117 Diag(FormatLoc, diag::note_format_security_fixit)
4122 Diag(FormatLoc, diag::warn_format_nonliteral)
4123 << OrigFormatExpr->getSourceRange();
4133 const Expr *OrigFormatExpr;
4134 const unsigned FirstDataArg;
4135 const unsigned NumDataArgs;
4137 const bool HasVAListArg;
4138 ArrayRef<const Expr *> Args;
4140 llvm::SmallBitVector CoveredArgs;
4141 bool usesPositionalArgs;
4143 bool inFunctionCall;
4145 llvm::SmallBitVector &CheckedVarArgs;
4146 UncoveredArgHandler &UncoveredArg;
4150 const Expr *origFormatExpr,
unsigned firstDataArg,
4151 unsigned numDataArgs,
const char *beg,
bool hasVAListArg,
4152 ArrayRef<const Expr *> Args,
4153 unsigned formatIdx,
bool inFunctionCall,
4155 llvm::SmallBitVector &CheckedVarArgs,
4156 UncoveredArgHandler &UncoveredArg)
4157 :
S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
4158 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
4159 Beg(beg), HasVAListArg(hasVAListArg),
4160 Args(Args), FormatIdx(formatIdx),
4161 usesPositionalArgs(
false), atFirstArg(
true),
4162 inFunctionCall(inFunctionCall), CallType(callType),
4163 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
4164 CoveredArgs.resize(numDataArgs);
4165 CoveredArgs.reset();
4168 void DoneProcessing();
4170 void HandleIncompleteSpecifier(
const char *startSpecifier,
4171 unsigned specifierLen)
override;
4173 void HandleInvalidLengthModifier(
4176 const char *startSpecifier,
unsigned specifierLen,
4179 void HandleNonStandardLengthModifier(
4181 const char *startSpecifier,
unsigned specifierLen);
4183 void HandleNonStandardConversionSpecifier(
4185 const char *startSpecifier,
unsigned specifierLen);
4187 void HandlePosition(
const char *startPos,
unsigned posLen)
override;
4189 void HandleInvalidPosition(
const char *startSpecifier,
4190 unsigned specifierLen,
4193 void HandleZeroPosition(
const char *startPos,
unsigned posLen)
override;
4195 void HandleNullChar(
const char *nullCharacter)
override;
4197 template <
typename Range>
4199 EmitFormatDiagnostic(
Sema &
S,
bool inFunctionCall,
const Expr *ArgumentExpr,
4201 bool IsStringLocation, Range StringRange,
4202 ArrayRef<FixItHint> Fixit = None);
4205 bool HandleInvalidConversionSpecifier(
unsigned argIndex,
SourceLocation Loc,
4206 const char *startSpec,
4207 unsigned specifierLen,
4208 const char *csStart,
unsigned csLen);
4211 const char *startSpec,
4212 unsigned specifierLen);
4216 unsigned specifierLen);
4219 const Expr *getDataArg(
unsigned i)
const;
4223 const char *startSpecifier,
unsigned specifierLen,
4226 template <
typename Range>
4228 bool IsStringLocation, Range StringRange,
4229 ArrayRef<FixItHint> Fixit = None);
4233 SourceRange CheckFormatHandler::getFormatStringRange() {
4234 return OrigFormatExpr->getSourceRange();
4238 getSpecifierRange(
const char *startSpecifier,
unsigned specifierLen) {
4248 SourceLocation CheckFormatHandler::getLocationOfByte(
const char *x) {
4252 void CheckFormatHandler::HandleIncompleteSpecifier(
const char *startSpecifier,
4253 unsigned specifierLen){
4254 EmitFormatDiagnostic(
S.
PDiag(diag::warn_printf_incomplete_specifier),
4255 getLocationOfByte(startSpecifier),
4257 getSpecifierRange(startSpecifier, specifierLen));
4260 void CheckFormatHandler::HandleInvalidLengthModifier(
4263 const char *startSpecifier,
unsigned specifierLen,
unsigned DiagID) {
4264 using namespace analyze_format_string;
4267 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
4272 EmitFormatDiagnostic(
S.
PDiag(DiagID) << LM.toString() << CS.
toString(),
4273 getLocationOfByte(LM.getStart()),
4275 getSpecifierRange(startSpecifier, specifierLen));
4277 S.
Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
4278 << FixedLM->toString()
4283 if (DiagID == diag::warn_format_nonsensical_length)
4286 EmitFormatDiagnostic(
S.
PDiag(DiagID) << LM.toString() << CS.
toString(),
4287 getLocationOfByte(LM.getStart()),
4289 getSpecifierRange(startSpecifier, specifierLen),
4294 void CheckFormatHandler::HandleNonStandardLengthModifier(
4296 const char *startSpecifier,
unsigned specifierLen) {
4297 using namespace analyze_format_string;
4300 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
4305 EmitFormatDiagnostic(
S.
PDiag(diag::warn_format_non_standard)
4306 << LM.toString() << 0,
4307 getLocationOfByte(LM.getStart()),
4309 getSpecifierRange(startSpecifier, specifierLen));
4311 S.
Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
4312 << FixedLM->toString()
4316 EmitFormatDiagnostic(
S.
PDiag(diag::warn_format_non_standard)
4317 << LM.toString() << 0,
4318 getLocationOfByte(LM.getStart()),
4320 getSpecifierRange(startSpecifier, specifierLen));
4324 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
4326 const char *startSpecifier,
unsigned specifierLen) {
4327 using namespace analyze_format_string;
4332 EmitFormatDiagnostic(
S.
PDiag(diag::warn_format_non_standard)
4336 getSpecifierRange(startSpecifier, specifierLen));
4339 S.
Diag(getLocationOfByte(CS.
getStart()), diag::note_format_fix_specifier)
4340 << FixedCS->toString()
4343 EmitFormatDiagnostic(
S.
PDiag(diag::warn_format_non_standard)
4347 getSpecifierRange(startSpecifier, specifierLen));
4351 void CheckFormatHandler::HandlePosition(
const char *startPos,
4353 EmitFormatDiagnostic(
S.
PDiag(diag::warn_format_non_standard_positional_arg),
4354 getLocationOfByte(startPos),
4356 getSpecifierRange(startPos, posLen));
4360 CheckFormatHandler::HandleInvalidPosition(
const char *startPos,
unsigned posLen,
4362 EmitFormatDiagnostic(
S.
PDiag(diag::warn_format_invalid_positional_specifier)
4364 getLocationOfByte(startPos),
true,
4365 getSpecifierRange(startPos, posLen));
4368 void CheckFormatHandler::HandleZeroPosition(
const char *startPos,
4370 EmitFormatDiagnostic(
S.
PDiag(diag::warn_format_zero_positional_specifier),
4371 getLocationOfByte(startPos),
4373 getSpecifierRange(startPos, posLen));
4376 void CheckFormatHandler::HandleNullChar(
const char *nullCharacter) {
4377 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
4379 EmitFormatDiagnostic(
4380 S.
PDiag(diag::warn_printf_format_string_contains_null_char),
4381 getLocationOfByte(nullCharacter),
true,
4382 getFormatStringRange());
4388 const Expr *CheckFormatHandler::getDataArg(
unsigned i)
const {
4389 return Args[FirstDataArg + i];
4392 void CheckFormatHandler::DoneProcessing() {
4395 if (!HasVAListArg) {
4398 signed notCoveredArg = CoveredArgs.find_first();
4399 if (notCoveredArg >= 0) {
4400 assert((
unsigned)notCoveredArg < NumDataArgs);
4401 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
4403 UncoveredArg.setAllCovered();
4408 void UncoveredArgHandler::Diagnose(
Sema &
S,
bool IsFunctionCall,
4409 const Expr *ArgExpr) {
4410 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
4422 for (
auto E : DiagnosticExprs)
4423 PDiag <<
E->getSourceRange();
4425 CheckFormatHandler::EmitFormatDiagnostic(
4426 S, IsFunctionCall, DiagnosticExprs[0],
4432 CheckFormatHandler::HandleInvalidConversionSpecifier(
unsigned argIndex,
4434 const char *startSpec,
4435 unsigned specifierLen,
4436 const char *csStart,
4438 bool keepGoing =
true;
4439 if (argIndex < NumDataArgs) {
4442 CoveredArgs.set(argIndex);
4453 StringRef Specifier(csStart, csLen);
4458 std::string CodePointStr;
4459 if (!llvm::sys::locale::isPrint(*csStart)) {
4461 const UTF8 **B =
reinterpret_cast<const UTF8 **
>(&csStart);
4463 reinterpret_cast<const UTF8 *
>(csStart + csLen);
4464 ConversionResult Result =
4465 llvm::convertUTF8Sequence(B, E, &CodePoint, strictConversion);
4467 if (Result != conversionOK) {
4468 unsigned char FirstChar = *csStart;
4469 CodePoint = (UTF32)FirstChar;
4472 llvm::raw_string_ostream OS(CodePointStr);
4473 if (CodePoint < 256)
4474 OS <<
"\\x" << llvm::format(
"%02x", CodePoint);
4475 else if (CodePoint <= 0xFFFF)
4476 OS <<
"\\u" << llvm::format(
"%04x", CodePoint);
4478 OS <<
"\\U" << llvm::format(
"%08x", CodePoint);
4480 Specifier = CodePointStr;
4483 EmitFormatDiagnostic(
4484 S.
PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
4485 true, getSpecifierRange(startSpec, specifierLen));
4491 CheckFormatHandler::HandlePositionalNonpositionalArgs(
SourceLocation Loc,
4492 const char *startSpec,
4493 unsigned specifierLen) {
4494 EmitFormatDiagnostic(
4495 S.
PDiag(diag::warn_format_mix_positional_nonpositional_args),
4496 Loc,
true, getSpecifierRange(startSpec, specifierLen));
4500 CheckFormatHandler::CheckNumArgs(
4503 const char *startSpecifier,
unsigned specifierLen,
unsigned argIndex) {
4505 if (argIndex >= NumDataArgs) {
4507 ? (S.
PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
4508 << (argIndex+1) << NumDataArgs)
4509 : S.
PDiag(diag::warn_printf_insufficient_data_args);
4510 EmitFormatDiagnostic(
4511 PDiag, getLocationOfByte(CS.
getStart()),
true,
4512 getSpecifierRange(startSpecifier, specifierLen));
4516 UncoveredArg.setAllCovered();
4522 template<
typename Range>
4525 bool IsStringLocation,
4527 ArrayRef<FixItHint>
FixIt) {
4528 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
4529 Loc, IsStringLocation, StringRange, FixIt);
4559 template <
typename Range>
4560 void CheckFormatHandler::EmitFormatDiagnostic(
4561 Sema &S,
bool InFunctionCall,
const Expr *ArgumentExpr,
4563 Range StringRange, ArrayRef<FixItHint>
FixIt) {
4564 if (InFunctionCall) {
4569 S.
Diag(IsStringLocation ? ArgumentExpr->
getExprLoc() : Loc, PDiag)
4570 << ArgumentExpr->getSourceRange();
4573 S.
Diag(IsStringLocation ? Loc : StringRange.getBegin(),
4574 diag::note_format_string_defined);
4576 Note << StringRange;
4584 class CheckPrintfHandler :
public CheckFormatHandler {
4589 const Expr *origFormatExpr,
unsigned firstDataArg,
4590 unsigned numDataArgs,
bool isObjC,
4591 const char *beg,
bool hasVAListArg,
4592 ArrayRef<const Expr *> Args,
4593 unsigned formatIdx,
bool inFunctionCall,
4595 llvm::SmallBitVector &CheckedVarArgs,
4596 UncoveredArgHandler &UncoveredArg)
4597 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
4598 numDataArgs, beg, hasVAListArg, Args,
4599 formatIdx, inFunctionCall, CallType, CheckedVarArgs,
4604 bool HandleInvalidPrintfConversionSpecifier(
4606 const char *startSpecifier,
4607 unsigned specifierLen)
override;
4610 const char *startSpecifier,
4611 unsigned specifierLen)
override;
4613 const char *StartSpecifier,
4614 unsigned SpecifierLen,
4618 const char *startSpecifier,
unsigned specifierLen);
4620 const analyze_printf::OptionalAmount &Amt,
4622 const char *startSpecifier,
unsigned specifierLen);
4624 const analyze_printf::OptionalFlag &flag,
4625 const char *startSpecifier,
unsigned specifierLen);
4627 const analyze_printf::OptionalFlag &ignoredFlag,
4628 const analyze_printf::OptionalFlag &flag,
4629 const char *startSpecifier,
unsigned specifierLen);
4630 bool checkForCStrMembers(
const analyze_printf::ArgType &AT,
4633 void HandleEmptyObjCModifierFlag(
const char *startFlag,
4634 unsigned flagLen)
override;
4636 void HandleInvalidObjCModifierFlag(
const char *startFlag,
4637 unsigned flagLen)
override;
4639 void HandleObjCFlagsWithNonObjCConversion(
const char *flagsStart,
4640 const char *flagsEnd,
4641 const char *conversionPosition)
4646 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
4648 const char *startSpecifier,
4649 unsigned specifierLen) {
4653 return HandleInvalidConversionSpecifier(FS.
getArgIndex(),
4655 startSpecifier, specifierLen,
4659 bool CheckPrintfHandler::HandleAmount(
4661 unsigned k,
const char *startSpecifier,
4662 unsigned specifierLen) {
4664 if (!HasVAListArg) {
4666 if (argIndex >= NumDataArgs) {
4667 EmitFormatDiagnostic(S.
PDiag(diag::warn_printf_asterisk_missing_arg)
4671 getSpecifierRange(startSpecifier, specifierLen));
4681 CoveredArgs.set(argIndex);
4682 const Expr *Arg = getDataArg(argIndex);
4689 assert(AT.isValid());
4691 if (!AT.matchesType(S.
Context, T)) {
4692 EmitFormatDiagnostic(S.
PDiag(diag::warn_printf_asterisk_wrong_type)
4693 << k << AT.getRepresentativeTypeName(S.
Context)
4694 << T << Arg->getSourceRange(),
4697 getSpecifierRange(startSpecifier, specifierLen));
4707 void CheckPrintfHandler::HandleInvalidAmount(
4709 const analyze_printf::OptionalAmount &Amt,
4711 const char *startSpecifier,
4712 unsigned specifierLen) {
4717 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
4719 Amt.getConstantLength()))
4722 EmitFormatDiagnostic(S.
PDiag(diag::warn_printf_nonsensical_optional_amount)
4724 getLocationOfByte(Amt.getStart()),
4726 getSpecifierRange(startSpecifier, specifierLen),
4731 const analyze_printf::OptionalFlag &flag,
4732 const char *startSpecifier,
4733 unsigned specifierLen) {
4737 EmitFormatDiagnostic(S.
PDiag(diag::warn_printf_nonsensical_flag)
4738 << flag.toString() << CS.
toString(),
4739 getLocationOfByte(flag.getPosition()),
4741 getSpecifierRange(startSpecifier, specifierLen),
4743 getSpecifierRange(flag.getPosition(), 1)));
4746 void CheckPrintfHandler::HandleIgnoredFlag(
4748 const analyze_printf::OptionalFlag &ignoredFlag,
4749 const analyze_printf::OptionalFlag &flag,
4750 const char *startSpecifier,
4751 unsigned specifierLen) {
4753 EmitFormatDiagnostic(S.
PDiag(diag::warn_printf_ignored_flag)
4754 << ignoredFlag.toString() << flag.toString(),
4755 getLocationOfByte(ignoredFlag.getPosition()),
4757 getSpecifierRange(startSpecifier, specifierLen),
4759 getSpecifierRange(ignoredFlag.getPosition(), 1)));
4766 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(
const char *startFlag,
4769 EmitFormatDiagnostic(S.
PDiag(diag::warn_printf_empty_objc_flag),
4770 getLocationOfByte(startFlag),
4772 getSpecifierRange(startFlag, flagLen));
4775 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(
const char *startFlag,
4778 auto Range = getSpecifierRange(startFlag, flagLen);
4779 StringRef flag(startFlag, flagLen);
4780 EmitFormatDiagnostic(S.
PDiag(diag::warn_printf_invalid_objc_flag) << flag,
4781 getLocationOfByte(startFlag),
4786 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
4787 const char *flagsStart,
const char *flagsEnd,
const char *conversionPosition) {
4789 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
4790 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
4791 EmitFormatDiagnostic(S.
PDiag(diag) << StringRef(conversionPosition, 1),
4792 getLocationOfByte(conversionPosition),
4800 template<
typename MemberKind>
4801 static llvm::SmallPtrSet<MemberKind*, 1>
4804 llvm::SmallPtrSet<MemberKind*, 1> Results;
4821 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
4832 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
4834 CXXRecordMembersNamed<CXXMethodDecl>(
"c_str", *
this, E->
getType());
4837 if ((*MI)->getMinRequiredArguments() == 0)
4845 bool CheckPrintfHandler::checkForCStrMembers(
4846 const analyze_printf::ArgType &AT,
const Expr *E) {
4847 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
4850 CXXRecordMembersNamed<CXXMethodDecl>(
"c_str",
S, E->
getType());
4859 S.Diag(E->getLocStart(), diag::note_printf_c_str)
4872 const char *startSpecifier,
4873 unsigned specifierLen) {
4874 using namespace analyze_format_string;
4875 using namespace analyze_printf;
4884 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.
getStart()),
4885 startSpecifier, specifierLen);
4893 startSpecifier, specifierLen)) {
4898 startSpecifier, specifierLen)) {
4910 if (argIndex < NumDataArgs) {
4914 CoveredArgs.set(argIndex);
4918 if (CS.
getKind() == ConversionSpecifier::FreeBSDbArg ||
4919 CS.
getKind() == ConversionSpecifier::FreeBSDDArg) {
4921 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
4925 CoveredArgs.set(argIndex + 1);
4928 const Expr *Ex = getDataArg(argIndex);
4929 const analyze_printf::ArgType &AT =
4930 (CS.
getKind() == ConversionSpecifier::FreeBSDbArg) ?
4931 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
4932 if (AT.isValid() && !AT.matchesType(S.Context, Ex->
getType()))
4933 EmitFormatDiagnostic(
4934 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4935 << AT.getRepresentativeTypeName(S.Context) << Ex->
getType()
4936 <<
false << Ex->getSourceRange(),
4937 Ex->getLocStart(),
false,
4938 getSpecifierRange(startSpecifier, specifierLen));
4941 Ex = getDataArg(argIndex + 1);
4942 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
4943 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
4944 EmitFormatDiagnostic(
4945 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4946 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
4947 <<
false << Ex->getSourceRange(),
4948 Ex->getLocStart(),
false,
4949 getSpecifierRange(startSpecifier, specifierLen));
4957 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
4964 startSpecifier, specifierLen);
4970 startSpecifier, specifierLen);
4979 HandleFlag(FS, FS.
hasPlusPrefix(), startSpecifier, specifierLen);
4981 HandleFlag(FS, FS.
hasSpacePrefix(), startSpecifier, specifierLen);
4990 startSpecifier, specifierLen);
4993 startSpecifier, specifierLen);
4997 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4998 diag::warn_format_nonsensical_length);
5000 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
5002 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5003 diag::warn_format_non_standard_conversion_spec);
5006 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
5012 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
5015 const Expr *Arg = getDataArg(argIndex);
5019 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
5030 switch (Inside->getStmtClass()) {
5031 case Stmt::ArraySubscriptExprClass:
5032 case Stmt::CallExprClass:
5033 case Stmt::CharacterLiteralClass:
5034 case Stmt::CXXBoolLiteralExprClass:
5035 case Stmt::DeclRefExprClass:
5036 case Stmt::FloatingLiteralClass:
5037 case Stmt::IntegerLiteralClass:
5038 case Stmt::MemberExprClass:
5039 case Stmt::ObjCArrayLiteralClass:
5040 case Stmt::ObjCBoolLiteralExprClass:
5041 case Stmt::ObjCBoxedExprClass:
5042 case Stmt::ObjCDictionaryLiteralClass:
5043 case Stmt::ObjCEncodeExprClass:
5044 case Stmt::ObjCIvarRefExprClass:
5045 case Stmt::ObjCMessageExprClass:
5046 case Stmt::ObjCPropertyRefExprClass:
5047 case Stmt::ObjCStringLiteralClass:
5048 case Stmt::ObjCSubscriptRefExprClass:
5049 case Stmt::ParenExprClass:
5050 case Stmt::StringLiteralClass:
5051 case Stmt::UnaryOperatorClass:
5058 static std::pair<QualType, StringRef>
5067 .Case(
"NSInteger", Context.
LongTy)
5069 .Case(
"SInt32", Context.
IntTy)
5074 return std::make_pair(CastTy, Name);
5076 TyTy = UserTy->desugar();
5080 if (
const ParenExpr *PE = dyn_cast<ParenExpr>(E))
5082 PE->getSubExpr()->getType(),
5091 StringRef TrueName, FalseName;
5093 std::tie(TrueTy, TrueName) =
5095 CO->getTrueExpr()->getType(),
5097 std::tie(FalseTy, FalseName) =
5099 CO->getFalseExpr()->getType(),
5100 CO->getFalseExpr());
5102 if (TrueTy == FalseTy)
5103 return std::make_pair(TrueTy, TrueName);
5104 else if (TrueTy.
isNull())
5105 return std::make_pair(FalseTy, FalseName);
5106 else if (FalseTy.
isNull())
5107 return std::make_pair(TrueTy, TrueName);
5110 return std::make_pair(
QualType(), StringRef());
5115 const char *StartSpecifier,
5116 unsigned SpecifierLen,
5118 using namespace analyze_format_string;
5119 using namespace analyze_printf;
5122 const analyze_printf::ArgType &AT = FS.
getArgType(S.Context,
5128 while (
const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
5129 ExprTy = TET->getUnderlyingExpr()->getType();
5132 analyze_printf::ArgType::MatchKind
match = AT.matchesType(S.Context, ExprTy);
5134 if (
match == analyze_printf::ArgType::Match) {
5143 if (ICE->getCastKind() == CK_IntegralCast ||
5144 ICE->getCastKind() == CK_FloatingCast) {
5145 E = ICE->getSubExpr();
5151 if (ICE->getType() == S.Context.IntTy ||
5152 ICE->getType() == S.Context.UnsignedIntTy) {
5154 if (AT.matchesType(S.Context, ExprTy))
5162 if (ExprTy == S.Context.IntTy)
5163 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
5164 ExprTy = S.Context.CharTy;
5168 bool IsEnum =
false;
5169 if (
auto EnumTy = ExprTy->getAs<
EnumType>()) {
5170 ExprTy = EnumTy->getDecl()->getIntegerType();
5180 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
5181 !ExprTy->isCharType()) {
5184 IntendedTy = S.Context.UnsignedShortTy;
5189 const llvm::APInt &V = IL->getValue();
5190 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
5194 LookupResult Result(S, &S.Context.Idents.get(
"unichar"), E->getLocStart(),
5196 if (S.LookupName(Result, S.getCurScope())) {
5199 if (TD->getUnderlyingType() == IntendedTy)
5200 IntendedTy = S.Context.getTypedefType(TD);
5207 bool ShouldNotPrintDirectly =
false; StringRef CastTyName;
5208 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
5212 IntendedTy = CastTy;
5213 ShouldNotPrintDirectly =
true;
5218 PrintfSpecifier fixedFS = FS;
5219 bool success = fixedFS.
fixType(IntendedTy, S.getLangOpts(),
5220 S.Context, ObjCContext);
5225 llvm::raw_svector_ostream os(buf);
5226 fixedFS.toString(os);
5228 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
5230 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
5231 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5233 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5237 EmitFormatDiagnostic(S.PDiag(diag)
5238 << AT.getRepresentativeTypeName(S.Context)
5239 << IntendedTy << IsEnum << E->getSourceRange(),
5252 llvm::raw_svector_ostream CastFix(CastBuf);
5254 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
5258 if (!AT.matchesType(S.Context, IntendedTy))
5263 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
5281 if (ShouldNotPrintDirectly) {
5286 if (
const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
5287 Name = TypedefTy->getDecl()->
getName();
5290 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
5291 << Name << IntendedTy << IsEnum
5292 << E->getSourceRange(),
5293 E->getLocStart(),
false,
5299 EmitFormatDiagnostic(
5300 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5301 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
5302 << E->getSourceRange(),
5303 E->getLocStart(),
false,
5313 switch (S.isValidVarArgType(ExprTy)) {
5316 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5317 if (
match == analyze_printf::ArgType::NoMatchPedantic) {
5318 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5321 EmitFormatDiagnostic(
5322 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
5323 << IsEnum << CSR << E->getSourceRange(),
5324 E->getLocStart(),
false, CSR);
5329 EmitFormatDiagnostic(
5330 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
5331 << S.getLangOpts().CPlusPlus11
5334 << AT.getRepresentativeTypeName(S.Context)
5336 << E->getSourceRange(),
5337 E->getLocStart(),
false, CSR);
5338 checkForCStrMembers(AT, E);
5342 if (ExprTy->isObjCObjectType())
5343 EmitFormatDiagnostic(
5344 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
5345 << S.getLangOpts().CPlusPlus11
5348 << AT.getRepresentativeTypeName(S.Context)
5350 << E->getSourceRange(),
5351 E->getLocStart(),
false, CSR);
5355 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
5356 << isa<InitListExpr>(E) << ExprTy << CallType
5357 << AT.getRepresentativeTypeName(S.Context)
5358 << E->getSourceRange();
5362 assert(FirstDataArg + FS.
getArgIndex() < CheckedVarArgs.size() &&
5363 "format string specifier index out of range");
5364 CheckedVarArgs[FirstDataArg + FS.
getArgIndex()] =
true;
5373 class CheckScanfHandler :
public CheckFormatHandler {
5376 const Expr *origFormatExpr,
unsigned firstDataArg,
5377 unsigned numDataArgs,
const char *beg,
bool hasVAListArg,
5378 ArrayRef<const Expr *> Args,
5379 unsigned formatIdx,
bool inFunctionCall,
5381 llvm::SmallBitVector &CheckedVarArgs,
5382 UncoveredArgHandler &UncoveredArg)
5383 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
5384 numDataArgs, beg, hasVAListArg,
5385 Args, formatIdx, inFunctionCall, CallType,
5386 CheckedVarArgs, UncoveredArg)
5390 const char *startSpecifier,
5391 unsigned specifierLen)
override;
5393 bool HandleInvalidScanfConversionSpecifier(
5395 const char *startSpecifier,
5396 unsigned specifierLen)
override;
5398 void HandleIncompleteScanList(
const char *start,
const char *
end)
override;
5402 void CheckScanfHandler::HandleIncompleteScanList(
const char *start,
5404 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
5405 getLocationOfByte(end),
true,
5406 getSpecifierRange(start, end - start));
5409 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
5411 const char *startSpecifier,
5412 unsigned specifierLen) {
5417 return HandleInvalidConversionSpecifier(FS.
getArgIndex(),
5419 startSpecifier, specifierLen,
5423 bool CheckScanfHandler::HandleScanfSpecifier(
5425 const char *startSpecifier,
5426 unsigned specifierLen) {
5427 using namespace analyze_scanf;
5428 using namespace analyze_format_string;
5440 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.
getStart()),
5441 startSpecifier, specifierLen);
5448 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
5449 if (Amt.getConstantAmount() == 0) {
5451 Amt.getConstantLength());
5452 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
5453 getLocationOfByte(Amt.getStart()),
5455 FixItHint::CreateRemoval(R));
5467 if (argIndex < NumDataArgs) {
5471 CoveredArgs.set(argIndex);
5476 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5477 diag::warn_format_nonsensical_length);
5479 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
5481 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5482 diag::warn_format_non_standard_conversion_spec);
5485 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
5491 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
5495 const Expr *Ex = getDataArg(argIndex);
5501 if (!AT.isValid()) {
5506 AT.matchesType(S.Context, Ex->getType());
5511 ScanfSpecifier fixedFS = FS;
5512 bool success = fixedFS.
fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
5513 S.getLangOpts(), S.Context);
5515 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5517 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5523 llvm::raw_svector_ostream os(buf);
5524 fixedFS.toString(os);
5526 EmitFormatDiagnostic(
5527 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
5528 << Ex->getType() <<
false << Ex->getSourceRange(),
5531 getSpecifierRange(startSpecifier, specifierLen),
5533 getSpecifierRange(startSpecifier, specifierLen), os.str()));
5535 EmitFormatDiagnostic(S.PDiag(diag)
5536 << AT.getRepresentativeTypeName(S.Context)
5537 << Ex->getType() <<
false << Ex->getSourceRange(),
5540 getSpecifierRange(startSpecifier, specifierLen));
5547 const Expr *OrigFormatExpr,
5548 ArrayRef<const Expr *> Args,
5549 bool HasVAListArg,
unsigned format_idx,
5550 unsigned firstDataArg,
5552 bool inFunctionCall,
5554 llvm::SmallBitVector &CheckedVarArgs,
5555 UncoveredArgHandler &UncoveredArg) {
5558 CheckFormatHandler::EmitFormatDiagnostic(
5559 S, inFunctionCall, Args[format_idx],
5561 true, OrigFormatExpr->getSourceRange());
5567 const char *Str = StrRef.data();
5571 assert(T &&
"String literal not of constant array type!");
5572 size_t TypeSize = T->
getSize().getZExtValue();
5573 size_t StrLen =
std::min(
std::max(TypeSize,
size_t(1)) - 1, StrRef.size());
5574 const unsigned numDataArgs = Args.size() - firstDataArg;
5578 if (TypeSize <= StrRef.size() &&
5579 StrRef.substr(0, TypeSize).find(
'\0') == StringRef::npos) {
5580 CheckFormatHandler::EmitFormatDiagnostic(
5581 S, inFunctionCall, Args[format_idx],
5582 S.
PDiag(diag::warn_printf_format_string_not_null_terminated),
5584 true, OrigFormatExpr->getSourceRange());
5589 if (StrLen == 0 && numDataArgs > 0) {
5590 CheckFormatHandler::EmitFormatDiagnostic(
5591 S, inFunctionCall, Args[format_idx],
5593 true, OrigFormatExpr->getSourceRange());
5599 CheckPrintfHandler H(S, FExpr, OrigFormatExpr, firstDataArg,
5602 Str, HasVAListArg, Args, format_idx,
5603 inFunctionCall, CallType, CheckedVarArgs,
5612 CheckScanfHandler H(S, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
5613 Str, HasVAListArg, Args, format_idx,
5614 inFunctionCall, CallType, CheckedVarArgs,
5627 const char *Str = StrRef.data();
5630 assert(T &&
"String literal not of constant array type!");
5631 size_t TypeSize = T->
getSize().getZExtValue();
5632 size_t StrLen =
std::min(
std::max(TypeSize,
size_t(1)) - 1, StrRef.size());
5643 switch (AbsFunction) {
5647 case Builtin::BI__builtin_abs:
5648 return Builtin::BI__builtin_labs;
5649 case Builtin::BI__builtin_labs:
5650 return Builtin::BI__builtin_llabs;
5651 case Builtin::BI__builtin_llabs:
5654 case Builtin::BI__builtin_fabsf:
5655 return Builtin::BI__builtin_fabs;
5656 case Builtin::BI__builtin_fabs:
5657 return Builtin::BI__builtin_fabsl;
5658 case Builtin::BI__builtin_fabsl:
5661 case Builtin::BI__builtin_cabsf:
5662 return Builtin::BI__builtin_cabs;
5663 case Builtin::BI__builtin_cabs:
5664 return Builtin::BI__builtin_cabsl;
5665 case Builtin::BI__builtin_cabsl:
5668 case Builtin::BIabs:
5669 return Builtin::BIlabs;
5670 case Builtin::BIlabs:
5671 return Builtin::BIllabs;
5672 case Builtin::BIllabs:
5675 case Builtin::BIfabsf:
5676 return Builtin::BIfabs;
5677 case Builtin::BIfabs:
5678 return Builtin::BIfabsl;
5679 case Builtin::BIfabsl:
5682 case Builtin::BIcabsf:
5683 return Builtin::BIcabs;
5684 case Builtin::BIcabs:
5685 return Builtin::BIcabsl;
5686 case Builtin::BIcabsl:
5715 unsigned AbsFunctionKind) {
5716 unsigned BestKind = 0;
5718 for (
unsigned Kind = AbsFunctionKind;
Kind != 0;
5724 else if (Context.
hasSameType(ParamType, ArgType)) {
5747 llvm_unreachable(
"Type not integer, floating, or complex");
5754 switch (ValueKind) {
5759 case Builtin::BI__builtin_fabsf:
5760 case Builtin::BI__builtin_fabs:
5761 case Builtin::BI__builtin_fabsl:
5762 case Builtin::BI__builtin_cabsf:
5763 case Builtin::BI__builtin_cabs:
5764 case Builtin::BI__builtin_cabsl:
5765 return Builtin::BI__builtin_abs;
5766 case Builtin::BIfabsf:
5767 case Builtin::BIfabs:
5768 case Builtin::BIfabsl:
5769 case Builtin::BIcabsf:
5770 case Builtin::BIcabs:
5771 case Builtin::BIcabsl:
5772 return Builtin::BIabs;
5778 case Builtin::BI__builtin_abs:
5779 case Builtin::BI__builtin_labs:
5780 case Builtin::BI__builtin_llabs:
5781 case Builtin::BI__builtin_cabsf:
5782 case Builtin::BI__builtin_cabs:
5783 case Builtin::BI__builtin_cabsl:
5784 return Builtin::BI__builtin_fabsf;
5785 case Builtin::BIabs:
5786 case Builtin::BIlabs:
5787 case Builtin::BIllabs:
5788 case Builtin::BIcabsf:
5789 case Builtin::BIcabs:
5790 case Builtin::BIcabsl:
5791 return Builtin::BIfabsf;
5797 case Builtin::BI__builtin_abs:
5798 case Builtin::BI__builtin_labs:
5799 case Builtin::BI__builtin_llabs:
5800 case Builtin::BI__builtin_fabsf:
5801 case Builtin::BI__builtin_fabs:
5802 case Builtin::BI__builtin_fabsl:
5803 return Builtin::BI__builtin_cabsf;
5804 case Builtin::BIabs:
5805 case Builtin::BIlabs:
5806 case Builtin::BIllabs:
5807 case Builtin::BIfabsf:
5808 case Builtin::BIfabs:
5809 case Builtin::BIfabsl:
5810 return Builtin::BIcabsf;
5813 llvm_unreachable(
"Unable to convert function");
5824 case Builtin::BI__builtin_abs:
5825 case Builtin::BI__builtin_fabs:
5826 case Builtin::BI__builtin_fabsf:
5827 case Builtin::BI__builtin_fabsl:
5828 case Builtin::BI__builtin_labs:
5829 case Builtin::BI__builtin_llabs:
5830 case Builtin::BI__builtin_cabs:
5831 case Builtin::BI__builtin_cabsf:
5832 case Builtin::BI__builtin_cabsl:
5833 case Builtin::BIabs:
5834 case Builtin::BIlabs:
5835 case Builtin::BIllabs:
5836 case Builtin::BIfabs:
5837 case Builtin::BIfabsf:
5838 case Builtin::BIfabsl:
5839 case Builtin::BIcabs:
5840 case Builtin::BIcabsf:
5841 case Builtin::BIcabsl:
5844 llvm_unreachable(
"Unknown Builtin type");
5850 unsigned AbsKind,
QualType ArgType) {
5851 bool EmitHeaderHint =
true;
5852 const char *HeaderName =
nullptr;
5853 const char *FunctionName =
nullptr;
5855 FunctionName =
"std::abs";
5857 HeaderName =
"cstdlib";
5859 HeaderName =
"cmath";
5861 llvm_unreachable(
"Invalid Type");
5867 R.suppressDiagnostics();
5870 for (
const auto *
I : R) {
5873 FDecl = dyn_cast<
FunctionDecl>(UsingD->getTargetDecl());
5890 EmitHeaderHint =
false;
5902 R.suppressDiagnostics();
5905 if (R.isSingleResult()) {
5908 EmitHeaderHint =
false;
5912 }
else if (!R.empty()) {
5918 S.
Diag(Loc, diag::note_replace_abs_function)
5924 if (!EmitHeaderHint)
5927 S.
Diag(Loc, diag::note_include_header_or_declare) << HeaderName
5947 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
5954 void Sema::CheckAbsoluteValueFunction(
const CallExpr *Call,
5962 if (AbsKind == 0 && !IsStdAbs)
5971 const char *FunctionName =
5973 Diag(Call->
getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
5976 << FixItHint::CreateRemoval(Call->
getCallee()->getSourceRange());
5983 unsigned DiagType = 0;
5989 Diag(Call->
getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
6003 if (ArgValueKind == ParamValueKind) {
6009 << FDecl << ArgType << ParamType;
6011 if (NewAbsKind == 0)
6015 Call->
getCallee()->getSourceRange(), NewAbsKind, ArgType);
6024 if (NewAbsKind == 0)
6028 << FDecl << ParamValueKind << ArgValueKind;
6031 Call->
getCallee()->getSourceRange(), NewAbsKind, ArgType);
6054 << SizeRange << FnName;
6055 S.
Diag(FnLoc, diag::note_memsize_comparison_paren)
6059 S.
Diag(SizeRange.
getBegin(), diag::note_memsize_comparison_cast_silence)
6070 bool &IsContained) {
6073 IsContained =
false;
6077 if (!RD || RD->isInvalidDecl())
6086 for (
auto *FD : RD->
fields()) {
6102 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
6112 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
6114 return SizeOf->getTypeOfArgument();
6126 void Sema::CheckMemaccessArguments(
const CallExpr *Call,
6133 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
6137 unsigned LastArg = (BId == Builtin::BImemset ||
6138 BId == Builtin::BIstrndup ? 1 : 2);
6139 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
6149 llvm::FoldingSetNodeID SizeOfArgID;
6151 for (
unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
6170 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
6174 if (SizeOfArgID == llvm::FoldingSetNodeID())
6175 SizeOfArg->Profile(SizeOfArgID, Context,
true);
6176 llvm::FoldingSetNodeID DestID;
6177 Dest->Profile(DestID, Context,
true);
6178 if (DestID == SizeOfArgID) {
6181 unsigned ActionIdx = 0;
6182 StringRef ReadableName = FnName->
getName();
6184 if (
const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
6185 if (UnaryOp->getOpcode() == UO_AddrOf)
6208 DiagRuntimeBehavior(SL, SizeOfArg,
6209 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
6215 DiagRuntimeBehavior(SL, SizeOfArg,
6216 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
6230 DiagRuntimeBehavior(LenExpr->
getExprLoc(), Dest,
6231 PDiag(diag::warn_sizeof_pointer_type_memaccess)
6232 << FnName << SizeOfArgTy << ArgIdx
6233 << PointeeTy << Dest->getSourceRange()
6234 << LenExpr->getSourceRange());
6250 unsigned OperationType = 0;
6253 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
6254 if (BId == Builtin::BImemcpy)
6256 else if(BId == Builtin::BImemmove)
6258 else if (BId == Builtin::BImemcmp)
6262 DiagRuntimeBehavior(
6264 PDiag(diag::warn_dyn_class_memaccess)
6265 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
6266 << FnName << IsContained << ContainedRD << OperationType
6267 << Call->
getCallee()->getSourceRange());
6269 BId != Builtin::BImemset)
6270 DiagRuntimeBehavior(
6272 PDiag(diag::warn_arc_object_memaccess)
6273 << ArgIdx << FnName << PointeeTy
6274 << Call->
getCallee()->getSourceRange());
6278 DiagRuntimeBehavior(
6280 PDiag(diag::note_bad_memaccess_silence)
6300 if (isa<IntegerLiteral>(RHS))
6302 else if (isa<IntegerLiteral>(LHS))
6316 if (CAT->getSize().getSExtValue() <= 1)
6326 void Sema::CheckStrlcpycatArguments(
const CallExpr *Call,
6331 if ((NumArgs != 3) && (NumArgs != 4))
6336 const Expr *CompareWithSrc =
nullptr;
6344 CompareWithSrc = Ex;
6347 if (
const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
6348 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
6349 SizeCall->getNumArgs() == 1)
6354 if (!CompareWithSrc)
6366 if (!CompareWithSrcDRE ||
6370 const Expr *OriginalSizeArg = Call->
getArg(2);
6371 Diag(CompareWithSrcDRE->
getLocStart(), diag::warn_strlcpycat_wrong_size)
6372 << OriginalSizeArg->getSourceRange() << FnName;
6383 llvm::raw_svector_ostream OS(sizeString);
6385 DstArg->printPretty(OS,
nullptr, getPrintingPolicy());
6388 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
6395 if (
const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
6396 if (
const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
6397 return D1->getDecl() == D2->getDecl();
6402 if (
const CallExpr *CE = dyn_cast<CallExpr>(E)) {
6406 return CE->getArg(0)->IgnoreParenCasts();
6414 void Sema::CheckStrncatArguments(
const CallExpr *CE,
6429 unsigned PatternType = 0;
6437 }
else if (
const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
6438 if (BE->getOpcode() == BO_Sub) {
6440 const Expr *R = BE->getRHS()->IgnoreParenCasts();
6451 if (PatternType == 0)
6470 if (!isKnownSizeArray) {
6471 if (PatternType == 1)
6472 Diag(SL, diag::warn_strncat_wrong_size) << SR;
6474 Diag(SL, diag::warn_strncat_src_size) << SR;
6478 if (PatternType == 1)
6479 Diag(SL, diag::warn_strncat_large_size) << SR;
6481 Diag(SL, diag::warn_strncat_src_size) << SR;
6484 llvm::raw_svector_ostream OS(sizeString);
6486 DstArg->printPretty(OS,
nullptr, getPrintingPolicy());
6489 DstArg->printPretty(OS,
nullptr, getPrintingPolicy());
6492 Diag(SL, diag::note_strncat_wrong_size)
6499 SmallVectorImpl<const DeclRefExpr *> &refVars,
6500 const Decl *ParentDecl);
6502 SmallVectorImpl<const DeclRefExpr *> &refVars,
6503 const Decl *ParentDecl);
6511 const Expr *stackE =
nullptr;
6518 stackE =
EvalAddr(RetValExp, refVars,
nullptr);
6520 stackE =
EvalVal(RetValExp, refVars,
nullptr);
6528 for (
auto *DRE : refVars)
6529 if (isa<ParmVarDecl>(DRE->
getDecl()))
6534 if (refVars.empty()) {
6535 diagLoc = stackE->getLocStart();
6536 diagRange = stackE->getSourceRange();
6542 diagLoc = refVars[0]->getLocStart();
6543 diagRange = refVars[0]->getSourceRange();
6546 if (
const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
6549 << DR->getDecl()->getDeclName() << diagRange;
6550 }
else if (isa<BlockExpr>(stackE)) {
6551 S.
Diag(diagLoc, diag::err_ret_local_block) << diagRange;
6552 }
else if (isa<AddrLabelExpr>(stackE)) {
6553 S.
Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
6557 if (
auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
6558 if (ICE->getCastKind() == CK_LValueToRValue) {
6562 S.
Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
6568 for (
unsigned i = 0, e = refVars.size(); i != e; ++i) {
6569 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
6574 : stackE->getSourceRange();
6575 S.
Diag(VD->getLocation(), diag::note_ref_var_local_bind)
6607 SmallVectorImpl<const DeclRefExpr *> &refVars,
6608 const Decl *ParentDecl) {
6616 "EvalAddr only works on pointers");
6623 switch (E->getStmtClass()) {
6624 case Stmt::DeclRefExprClass: {
6634 if (V->hasLocalStorage() &&
6635 V->getType()->isReferenceType() && V->hasInit()) {
6637 refVars.push_back(DR);
6638 return EvalAddr(V->getInit(), refVars, ParentDecl);
6644 case Stmt::UnaryOperatorClass: {
6654 case Stmt::BinaryOperatorClass: {
6660 if (op != BO_Add && op != BO_Sub)
6671 return EvalAddr(Base, refVars, ParentDecl);
6676 case Stmt::ConditionalOperatorClass: {
6683 if (!LHSExpr->getType()->isVoidType())
6684 if (
const Expr *LHS =
EvalAddr(LHSExpr, refVars, ParentDecl))
6695 case Stmt::BlockExprClass:
6696 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
6700 case Stmt::AddrLabelExprClass:
6703 case Stmt::ExprWithCleanupsClass:
6704 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
6709 case Stmt::ImplicitCastExprClass:
6710 case Stmt::CStyleCastExprClass:
6711 case Stmt::CXXFunctionalCastExprClass:
6712 case Stmt::ObjCBridgedCastExprClass:
6713 case Stmt::CXXStaticCastExprClass:
6714 case Stmt::CXXDynamicCastExprClass:
6715 case Stmt::CXXConstCastExprClass:
6716 case Stmt::CXXReinterpretCastExprClass: {
6717 const Expr* SubExpr = cast<CastExpr>(
E)->getSubExpr();
6718 switch (cast<CastExpr>(E)->getCastKind()) {
6719 case CK_LValueToRValue:
6721 case CK_BaseToDerived:
6722 case CK_DerivedToBase:
6723 case CK_UncheckedDerivedToBase:
6725 case CK_CPointerToObjCPointerCast:
6726 case CK_BlockPointerToObjCPointerCast:
6727 case CK_AnyPointerToBlockPointerCast:
6728 return EvalAddr(SubExpr, refVars, ParentDecl);
6730 case CK_ArrayToPointerDecay:
6731 return EvalVal(SubExpr, refVars, ParentDecl);
6737 return EvalAddr(SubExpr, refVars, ParentDecl);
6746 case Stmt::MaterializeTemporaryExprClass:
6747 if (
const Expr *Result =
6748 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
6749 refVars, ParentDecl))
6762 SmallVectorImpl<const DeclRefExpr *> &refVars,
6763 const Decl *ParentDecl) {
6775 switch (E->getStmtClass()) {
6776 case Stmt::ImplicitCastExprClass: {
6785 case Stmt::ExprWithCleanupsClass:
6786 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
6789 case Stmt::DeclRefExprClass: {
6801 if (V == ParentDecl)
6804 if (V->hasLocalStorage()) {
6805 if (!V->getType()->isReferenceType())
6812 refVars.push_back(DR);
6813 return EvalVal(V->getInit(), refVars, V);
6821 case Stmt::UnaryOperatorClass: {
6833 case Stmt::ArraySubscriptExprClass: {
6837 const auto *ASE = cast<ArraySubscriptExpr>(
E);
6838 if (ASE->isTypeDependent())
6840 return EvalAddr(ASE->getBase(), refVars, ParentDecl);
6843 case Stmt::OMPArraySectionExprClass: {
6844 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
6848 case Stmt::ConditionalOperatorClass: {
6856 if (!LHSExpr->getType()->isVoidType())
6857 if (
const Expr *LHS =
EvalVal(LHSExpr, refVars, ParentDecl))
6869 case Stmt::MemberExprClass: {
6885 case Stmt::MaterializeTemporaryExprClass:
6886 if (
const Expr *Result =
6887 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
6888 refVars, ParentDecl))
6905 Sema::CheckReturnValExpr(
Expr *RetValExp,
QualType lhsType,
6913 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
6916 Diag(ReturnLoc, diag::warn_null_ret)
6917 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
6926 if (Op == OO_New || Op == OO_Array_New) {
6931 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
6932 << FD << getLangOpts().CPlusPlus11;
6948 if (
DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
6949 if (
DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
6950 if (DRL->getDecl() == DRR->getDecl())
6958 if (
FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
6962 if (
FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
6967 if (
CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
6968 if (CL->getBuiltinCallee())
6971 if (
CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
6972 if (CR->getBuiltinCallee())
6976 Diag(Loc, diag::warn_floatingpoint_eq)
6977 << LHS->getSourceRange() << RHS->getSourceRange();
6994 IntRange(
unsigned Width,
bool NonNegative)
6995 : Width(Width), NonNegative(NonNegative)
6999 static IntRange forBoolType() {
7000 return IntRange(1,
true);
7005 return forValueOfCanonicalType(C,
7010 static IntRange forValueOfCanonicalType(
ASTContext &C,
const Type *T) {
7013 if (
const VectorType *VT = dyn_cast<VectorType>(T))
7014 T = VT->getElementType().getTypePtr();
7015 if (
const ComplexType *CT = dyn_cast<ComplexType>(T))
7016 T = CT->getElementType().getTypePtr();
7017 if (
const AtomicType *AT = dyn_cast<AtomicType>(T))
7018 T = AT->getValueType().getTypePtr();
7021 if (
const EnumType *ET = dyn_cast<EnumType>(T)) {
7029 if (NumNegative == 0)
7030 return IntRange(NumPositive,
true);
7032 return IntRange(
std::max(NumPositive + 1, NumNegative),
7047 static IntRange forTargetOfCanonicalType(
ASTContext &C,
const Type *T) {
7050 if (
const VectorType *VT = dyn_cast<VectorType>(T))
7051 T = VT->getElementType().getTypePtr();
7052 if (
const ComplexType *CT = dyn_cast<ComplexType>(T))
7053 T = CT->getElementType().getTypePtr();
7054 if (
const AtomicType *AT = dyn_cast<AtomicType>(T))
7055 T = AT->getValueType().getTypePtr();
7056 if (
const EnumType *ET = dyn_cast<EnumType>(T))
7066 static IntRange join(IntRange L, IntRange R) {
7067 return IntRange(
std::max(L.Width, R.Width),
7068 L.NonNegative && R.NonNegative);
7072 static IntRange meet(IntRange L, IntRange R) {
7073 return IntRange(
std::min(L.Width, R.Width),
7074 L.NonNegative || R.NonNegative);
7078 IntRange GetValueRange(
ASTContext &C, llvm::APSInt &value,
unsigned MaxWidth) {
7079 if (value.isSigned() && value.isNegative())
7080 return IntRange(value.getMinSignedBits(),
false);
7082 if (value.getBitWidth() > MaxWidth)
7083 value = value.trunc(MaxWidth);
7087 return IntRange(value.getActiveBits(),
true);
7091 unsigned MaxWidth) {
7093 return GetValueRange(C, result.
getInt(), MaxWidth);
7096 IntRange R = GetValueRange(C, result.
getVectorElt(0), Ty, MaxWidth);
7098 IntRange El = GetValueRange(C, result.
getVectorElt(i), Ty, MaxWidth);
7099 R = IntRange::join(R, El);
7107 return IntRange::join(R, I);
7122 Ty = AtomicRHS->getValueType();
7130 IntRange GetExprRange(
ASTContext &C,
const Expr *E,
unsigned MaxWidth) {
7136 return GetValueRange(C, result.
Val, GetExprType(E), MaxWidth);
7141 if (
const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
7142 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
7143 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
7145 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
7147 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
7148 CE->getCastKind() == CK_BooleanToSignedIntegral;
7152 return OutputTypeRange;
7155 = GetExprRange(C, CE->getSubExpr(),
7156 std::min(MaxWidth, OutputTypeRange.Width));
7159 if (SubRange.Width >= OutputTypeRange.Width)
7160 return OutputTypeRange;
7164 return IntRange(SubRange.Width,
7165 SubRange.NonNegative || OutputTypeRange.NonNegative);
7168 if (
const auto *CO = dyn_cast<ConditionalOperator>(E)) {
7171 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
7172 return GetExprRange(C, CondResult ? CO->getTrueExpr()
7173 : CO->getFalseExpr(),
7177 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
7178 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
7179 return IntRange::join(L, R);
7182 if (
const auto *BO = dyn_cast<BinaryOperator>(E)) {
7183 switch (BO->getOpcode()) {
7194 return IntRange::forBoolType();
7206 return IntRange::forValueOfType(C, GetExprType(E));
7212 return GetExprRange(C, BO->getRHS(), MaxWidth);
7217 return IntRange::forValueOfType(C, GetExprType(E));
7222 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
7223 GetExprRange(C, BO->getRHS(), MaxWidth));
7230 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
7231 if (I->getValue() == 1) {
7232 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
7233 return IntRange(R.Width,
true);
7239 return IntRange::forValueOfType(C, GetExprType(E));
7243 case BO_ShrAssign: {
7244 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
7249 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
7250 shift.isNonNegative()) {
7251 unsigned zext = shift.getZExtValue();
7252 if (zext >= L.Width)
7253 L.Width = (L.NonNegative ? 0 : 1);
7263 return GetExprRange(C, BO->getRHS(), MaxWidth);
7267 if (BO->getLHS()->getType()->isPointerType())
7268 return IntRange::forValueOfType(C, GetExprType(E));
7276 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
7279 llvm::APSInt divisor;
7280 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
7281 unsigned log2 = divisor.logBase2();
7282 if (log2 >= L.Width)
7283 L.Width = (L.NonNegative ? 0 : 1);
7285 L.Width =
std::min(L.Width - log2, MaxWidth);
7290 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
7291 return IntRange(L.Width, L.NonNegative && R.NonNegative);
7299 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
7300 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
7302 IntRange meet = IntRange::meet(L, R);
7303 meet.Width =
std::min(meet.Width, MaxWidth);
7317 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
7318 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
7319 return IntRange::join(L, R);
7322 if (
const auto *UO = dyn_cast<UnaryOperator>(E)) {
7323 switch (UO->getOpcode()) {
7326 return IntRange::forBoolType();
7331 return IntRange::forValueOfType(C, GetExprType(E));
7334 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
7338 if (
const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
7339 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
7342 return IntRange(BitField->getBitWidthValue(C),
7343 BitField->getType()->isUnsignedIntegerOrEnumerationType());
7345 return IntRange::forValueOfType(C, GetExprType(E));
7349 return GetExprRange(C, E, C.
getIntWidth(GetExprType(E)));
7355 bool IsSameFloatAfterCast(
const llvm::APFloat &value,
7356 const llvm::fltSemantics &Src,
7357 const llvm::fltSemantics &Tgt) {
7358 llvm::APFloat truncated = value;
7361 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
7362 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
7364 return truncated.bitwiseIsEqual(value);
7372 bool IsSameFloatAfterCast(
const APValue &value,
7373 const llvm::fltSemantics &Src,
7374 const llvm::fltSemantics &Tgt) {
7376 return IsSameFloatAfterCast(value.
getFloat(), Src, Tgt);
7380 if (!IsSameFloatAfterCast(value.
getVectorElt(i), Src, Tgt))
7396 if (isa<EnumConstantDecl>(DR->getDecl()))
7400 if (E->getLocStart().isMacroID())
7407 bool HasEnumType(
Expr *E) {
7410 if (ICE->getCastKind() != CK_IntegralCast &&
7411 ICE->getCastKind() != CK_NoOp)
7413 E = ICE->getSubExpr();
7428 if (op == BO_LT && IsZero(S, E->
getRHS())) {
7430 <<
"< 0" <<
"false" << HasEnumType(E->
getLHS())
7431 << E->
getLHS()->getSourceRange() << E->
getRHS()->getSourceRange();
7432 }
else if (op == BO_GE && IsZero(S, E->
getRHS())) {
7434 <<
">= 0" <<
"true" << HasEnumType(E->
getLHS())
7435 << E->
getLHS()->getSourceRange() << E->
getRHS()->getSourceRange();
7436 }
else if (op == BO_GT && IsZero(S, E->
getLHS())) {
7438 <<
"0 >" <<
"false" << HasEnumType(E->
getRHS())
7439 << E->
getLHS()->getSourceRange() << E->
getRHS()->getSourceRange();
7440 }
else if (op == BO_LE && IsZero(S, E->
getLHS())) {
7442 <<
"0 <=" <<
"true" << HasEnumType(E->
getRHS())
7443 << E->
getLHS()->getSourceRange() << E->
getRHS()->getSourceRange();
7448 Expr *Other,
const llvm::APSInt &Value,
7458 OtherT = AT->getValueType();
7459 IntRange OtherRange = IntRange::forValueOfType(S.
Context, OtherT);
7460 unsigned OtherWidth = OtherRange.Width;
7465 if ((Value == 0) && (!OtherIsBooleanType))
7473 LiteralConstant = 0,
7476 } LiteralOrBoolConstant = LiteralConstant;
7478 if (!OtherIsBooleanType) {
7485 "comparison with non-integer type");
7490 bool EqualityOnly =
false;
7494 if (!OtherRange.NonNegative) {
7496 if (ConstantSigned) {
7497 if (OtherWidth >= Value.getMinSignedBits())
7500 if (OtherWidth >= Value.getActiveBits() + 1)
7506 if (ConstantSigned) {
7507 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
7510 if (OtherWidth >= Value.getActiveBits())
7515 if (OtherRange.NonNegative) {
7516 if (OtherWidth >= Value.getActiveBits())
7519 assert(!ConstantSigned &&
7520 "Two signed types converted to unsigned types.");
7522 if (OtherWidth > Value.getActiveBits())
7528 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
7533 EqualityOnly =
true;
7537 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
7539 if (op == BO_EQ || op == BO_NE) {
7540 IsTrue = op == BO_NE;
7541 }
else if (EqualityOnly) {
7543 }
else if (RhsConstant) {
7544 if (op == BO_GT || op == BO_GE)
7545 IsTrue = !PositiveConstant;
7547 IsTrue = PositiveConstant;
7549 if (op == BO_LT || op == BO_LE)
7550 IsTrue = !PositiveConstant;
7552 IsTrue = PositiveConstant;
7556 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
7557 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
7558 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
7560 static const struct LinkedConditions {
7561 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
7562 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
7563 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
7564 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
7565 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
7566 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
7571 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
7572 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
7573 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
7574 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
7575 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
7576 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
7579 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
7581 enum ConstantValue ConstVal = Zero;
7582 if (Value.isUnsigned() || Value.isNonNegative()) {
7584 LiteralOrBoolConstant =
7585 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
7587 }
else if (Value == 1) {
7588 LiteralOrBoolConstant =
7589 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
7592 LiteralOrBoolConstant = LiteralConstant;
7599 CompareBoolWithConstantResult CmpRes;
7603 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
7606 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
7609 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
7612 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
7615 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
7618 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
7625 if (CmpRes == AFals) {
7627 }
else if (CmpRes == ATrue) {
7637 if (
const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
7638 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
7641 llvm::raw_svector_ostream OS(PrettySourceValue);
7643 OS <<
'\'' << *ED <<
"' (" << Value <<
")";
7649 S.
PDiag(diag::warn_out_of_range_compare)
7650 << OS.str() << LiteralOrBoolConstant
7651 << OtherT << (OtherIsBooleanType && !OtherT->
isBooleanType()) << IsTrue
7652 << E->
getLHS()->getSourceRange() << E->
getRHS()->getSourceRange());
7672 return AnalyzeImpConvsInComparison(S, E);
7676 return AnalyzeImpConvsInComparison(S, E);
7681 bool IsComparisonConstant =
false;
7686 llvm::APSInt RHSValue;
7687 bool IsRHSIntegralLiteral =
7689 llvm::APSInt LHSValue;
7690 bool IsLHSIntegralLiteral =
7692 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
7693 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue,
true);
7694 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
7695 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue,
false);
7697 IsComparisonConstant =
7698 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
7709 return AnalyzeImpConvsInComparison(S, E);
7713 Expr *signedOperand, *unsignedOperand;
7716 "unsigned comparison between two signed integer expressions?");
7717 signedOperand = LHS;
7718 unsignedOperand = RHS;
7720 signedOperand = RHS;
7721 unsignedOperand = LHS;
7723 CheckTrivialUnsignedComparison(S, E);
7724 return AnalyzeImpConvsInComparison(S, E);
7728 IntRange signedRange = GetExprRange(S.
Context, signedOperand);
7738 if (signedRange.NonNegative)
7739 return CheckTrivialUnsignedComparison(S, E);
7747 IntRange unsignedRange = GetExprRange(S.
Context, unsignedOperand);
7751 assert(unsignedRange.NonNegative &&
"unsigned range includes negative?");
7753 if (unsignedRange.Width < comparisonWidth)
7758 S.
PDiag(diag::warn_mixed_sign_comparison)
7760 << LHS->getSourceRange() << RHS->getSourceRange());
7769 if (Bitfield->isInvalidDecl())
7789 unsigned OriginalWidth = Value.getBitWidth();
7792 if (Value.isSigned() && Value.isNegative())
7793 if (
UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
7794 if (UO->getOpcode() == UO_Minus)
7795 if (isa<IntegerLiteral>(UO->getSubExpr()))
7796 OriginalWidth = Value.getMinSignedBits();
7798 if (OriginalWidth <= FieldWidth)
7802 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
7806 TruncatedValue = TruncatedValue.extend(OriginalWidth);
7807 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
7812 if (FieldWidth == 1 && Value == 1)
7815 std::string PrettyValue = Value.toString(10);
7816 std::string PrettyTrunc = TruncatedValue.toString(10);
7818 S.
Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
7819 << PrettyValue << PrettyTrunc << OriginalInit->
getType()
7820 << Init->getSourceRange();
7834 if (AnalyzeBitFieldAssignment(S, Bitfield, E->
getRHS(),
7848 bool pruneControlFlow =
false) {
7849 if (pruneControlFlow) {
7852 << SourceType << T << E->getSourceRange()
7857 << SourceType << T << E->getSourceRange() <<
SourceRange(CContext);
7862 unsigned diag,
bool pruneControlFlow =
false) {
7863 DiagnoseImpCast(S, E, E->
getType(), T, CContext, diag, pruneControlFlow);
7877 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
7880 const bool IsLiteral =
7881 isa<FloatingLiteral>(
E) || isa<FloatingLiteral>(InnerE);
7883 llvm::APFloat
Value(0.0);
7887 return DiagnoseImpCast(S, E, T, CContext,
7888 diag::warn_impcast_float_integer, PruneWarnings);
7891 bool isExact =
false;
7895 if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
7896 &isExact) == llvm::APFloat::opOK &&
7898 if (IsLiteral)
return;
7899 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
7903 unsigned DiagID = 0;
7906 DiagID = diag::warn_impcast_literal_float_to_integer;
7907 }
else if (IntegerValue == 0) {
7908 if (Value.isZero()) {
7909 return DiagnoseImpCast(S, E, T, CContext,
7910 diag::warn_impcast_float_integer, PruneWarnings);
7913 DiagID = diag::warn_impcast_float_to_integer_zero;
7915 if (IntegerValue.isUnsigned()) {
7916 if (!IntegerValue.isMaxValue()) {
7917 return DiagnoseImpCast(S, E, T, CContext,
7918 diag::warn_impcast_float_integer, PruneWarnings);
7921 if (!IntegerValue.isMaxSignedValue() &&
7922 !IntegerValue.isMinSignedValue()) {
7923 return DiagnoseImpCast(S, E, T, CContext,
7924 diag::warn_impcast_float_integer, PruneWarnings);
7928 DiagID = diag::warn_impcast_float_to_integer;
7937 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
7938 precision = (precision * 59 + 195) / 196;
7939 Value.toString(PrettySourceValue, precision);
7943 PrettyTargetValue = Value.isZero() ?
"false" :
"true";
7945 IntegerValue.toString(PrettyTargetValue);
7947 if (PruneWarnings) {
7951 << PrettySourceValue << PrettyTargetValue
7956 << PrettyTargetValue << E->getSourceRange() <<
SourceRange(CContext);
7960 std::string PrettyPrintInRange(
const llvm::APSInt &Value, IntRange Range) {
7961 if (!Range.Width)
return "0";
7963 llvm::APSInt ValueInRange =
Value;
7964 ValueInRange.setIsSigned(!Range.NonNegative);
7965 ValueInRange = ValueInRange.trunc(Range.Width);
7966 return ValueInRange.toString(10);
7969 bool IsImplicitBoolFloatConversion(
Sema &S,
Expr *Ex,
bool ToBool) {
7970 if (!isa<ImplicitCastExpr>(Ex))
7975 const Type *Source =
7982 const Type *BoolCandidateType = ToBool ? Target : Source;
7984 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
7988 void CheckImplicitArgumentConversions(
Sema &S,
CallExpr *TheCall,
7991 for (
unsigned i = 0; i <
NumArgs; ++i) {
7993 if (!IsImplicitBoolFloatConversion(S, CurrA,
true))
7996 bool IsSwapped = ((i > 0) &&
7997 IsImplicitBoolFloatConversion(S, TheCall->
getArg(i - 1),
false));
7998 IsSwapped |= ((i < (NumArgs - 1)) &&
7999 IsImplicitBoolFloatConversion(S, TheCall->
getArg(i + 1),
false));
8004 diag::warn_impcast_floating_point_to_bool);
8010 if (S.
Diags.
isIgnored(diag::warn_impcast_null_pointer_to_integer,
8015 if (isa<CallExpr>(E))
8044 if (MacroName ==
"NULL")
8052 S.
Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
8058 void checkObjCArrayLiteral(
Sema &S,
QualType TargetType,
8060 void checkObjCDictionaryLiteral(
Sema &S,
QualType TargetType,
8065 void checkObjCCollectionLiteralElement(
Sema &S,
QualType TargetElementType,
8066 Expr *Element,
unsigned ElementKind) {
8068 if (
auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
8069 if (ICE->getCastKind() == CK_BitCast &&
8071 Element = ICE->getSubExpr();
8081 S.
Diag(Element->getLocStart(),
8082 diag::warn_objc_collection_literal_element)
8083 << ElementType << ElementKind << TargetElementType
8084 << Element->getSourceRange();
8087 if (
auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
8088 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
8089 else if (
auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
8090 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
8095 void checkObjCArrayLiteral(
Sema &S,
QualType TargetType,
8104 if (TargetObjCPtr->isUnspecialized() ||
8105 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
8110 if (TypeArgs.size() != 1)
8113 QualType TargetElementType = TypeArgs[0];
8114 for (
unsigned I = 0, N = ArrayLiteral->
getNumElements(); I != N; ++
I) {
8115 checkObjCCollectionLiteralElement(S, TargetElementType,
8123 void checkObjCDictionaryLiteral(
Sema &S,
QualType TargetType,
8132 if (TargetObjCPtr->isUnspecialized() ||
8133 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
8138 if (TypeArgs.size() != 2)
8141 QualType TargetKeyType = TypeArgs[0];
8142 QualType TargetObjectType = TypeArgs[1];
8143 for (
unsigned I = 0, N = DictionaryLiteral->
getNumElements(); I != N; ++
I) {
8145 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
8146 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
8158 const char FirstLiteralCharacter =
8160 if (FirstLiteralCharacter ==
'0')
8167 const char FirstContextCharacter =
8169 if (FirstContextCharacter ==
'{')
8182 if (Source == Target)
return;
8195 if (isa<StringLiteral>(E))
8199 return DiagnoseImpCast(S, E, T, CC,
8200 diag::warn_impcast_string_literal_to_bool);
8201 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(
E) ||
8202 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(
E)) {
8205 return DiagnoseImpCast(S, E, T, CC,
8206 diag::warn_impcast_objective_c_literal_to_bool);
8217 if (
auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
8218 checkObjCArrayLiteral(S,
QualType(Target, 0), ArrayLiteral);
8219 else if (
auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
8220 checkObjCDictionaryLiteral(S,
QualType(Target, 0), DictionaryLiteral);
8223 if (isa<VectorType>(Source)) {
8224 if (!isa<VectorType>(Target)) {
8227 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
8235 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
8236 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
8238 if (
auto VecTy = dyn_cast<VectorType>(Target))
8239 Target = VecTy->getElementType().getTypePtr();
8242 if (isa<ComplexType>(Source)) {
8243 if (!isa<ComplexType>(Target)) {
8247 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
8250 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
8251 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
8260 if (TargetBT && TargetBT->isFloatingPoint()) {
8264 if (SourceBT->
getKind() > TargetBT->getKind()) {
8270 if (IsSameFloatAfterCast(result.
Val,
8279 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
8282 else if (TargetBT->getKind() > SourceBT->
getKind()) {
8286 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
8292 if (TargetBT && TargetBT->isInteger()) {
8296 DiagnoseFloatingImpCast(S, E, T, CC);
8315 if (isa<ImplicitCastExpr>(LastA) &&
8318 DiagnoseImpCast(S, E, T, CC,
8319 diag::warn_impcast_floating_point_to_bool);
8326 DiagnoseNullConversion(S, E, T, CC);
8337 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.
Context, Target);
8339 if (SourceRange.Width > TargetRange.Width) {
8342 llvm::APSInt
Value(32);
8347 std::string PrettySourceValue = Value.toString(10);
8348 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
8351 S.
PDiag(diag::warn_impcast_integer_precision_constant)
8352 << PrettySourceValue << PrettyTargetValue
8353 << E->
getType() << T << E->getSourceRange()
8363 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
8365 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
8368 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
8377 if (isSameWidthConstantConversion(S, E, T, CC)) {
8378 std::string PrettySourceValue = Value.toString(10);
8379 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
8383 S.
PDiag(diag::warn_impcast_integer_precision_constant)
8384 << PrettySourceValue << PrettyTargetValue << E->
getType() << T
8393 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
8394 (!TargetRange.NonNegative && SourceRange.NonNegative &&
8395 SourceRange.Width == TargetRange.Width)) {
8399 unsigned DiagID = diag::warn_impcast_integer_sign;
8407 DiagID = diag::warn_impcast_integer_sign_conditional;
8411 return DiagnoseImpCast(S, E, T, CC, DiagID);
8421 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
8429 if (SourceEnum->getDecl()->hasNameForLinkage() &&
8430 TargetEnum->getDecl()->hasNameForLinkage() &&
8431 SourceEnum != TargetEnum) {
8435 return DiagnoseImpCast(S, E, SourceType, T, CC,
8436 diag::warn_impcast_different_enum_types);
8447 if (isa<ConditionalOperator>(E))
8448 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
8450 AnalyzeImplicitConversions(S, E, CC);
8452 return CheckImplicitConversion(S, E, T, CC, &ICContext);
8459 bool Suspicious =
false;
8460 CheckConditionalOperand(S, E->
getTrueExpr(), T, CC, Suspicious);
8461 CheckConditionalOperand(S, E->
getFalseExpr(), T, CC, Suspicious);
8465 if (!Suspicious)
return;
8468 if (!S.
Diags.
isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
8473 if (E->
getType() == T)
return;
8477 E->
getType(), CC, &Suspicious);
8480 E->
getType(), CC, &Suspicious);
8503 if (isa<ConditionalOperator>(E)) {
8505 CheckConditionalOperator(S, CO, CC, T);
8510 if (
CallExpr *Call = dyn_cast<CallExpr>(E))
8511 CheckImplicitArgumentConversions(S, Call, CC);
8517 CheckImplicitConversion(S, E, T, CC);
8525 for (
auto *SE : POE->semantics())
8526 if (
auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
8527 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
8531 if (isa<ExplicitCastExpr>(E)) {
8533 return AnalyzeImplicitConversions(S, E, CC);
8538 if (BO->isComparisonOp())
8539 return AnalyzeComparison(S, BO);
8542 if (BO->getOpcode() == BO_Assign)
8543 return AnalyzeAssignment(S, BO);
8550 if (isa<StmtExpr>(E))
return;
8553 if (isa<UnaryExprOrTypeTraitExpr>(E))
return;
8558 bool IsLogicalAndOperator = BO && BO->
getOpcode() == BO_LAnd;
8559 for (
Stmt *SubStmt : E->children()) {
8560 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
8564 if (IsLogicalAndOperator &&
8569 AnalyzeImplicitConversions(S, ChildExpr, CC);
8574 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
8575 ::CheckBoolLikeConversion(S, SubExpr, BO->
getExprLoc());
8578 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
8579 ::CheckBoolLikeConversion(S, SubExpr, BO->
getExprLoc());
8583 if (U->getOpcode() == UO_LNot)
8584 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
8590 unsigned Start,
unsigned End) {
8591 bool IllegalParams =
false;
8592 for (
unsigned I = Start; I <=
End; ++
I) {
8599 diag::err_opencl_enqueue_kernel_invalid_local_size_type);
8600 IllegalParams =
true;
8605 TheCall->
getArg(I)->getLocStart());
8607 return IllegalParams;
8618 if (
const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
8621 }
else if (
const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
8622 if (!M->getMemberDecl()->getType()->isReferenceType())
8624 }
else if (
const CallExpr *Call = dyn_cast<CallExpr>(E)) {
8636 SemaRef.
Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
8666 bool IsEqual, SourceRange Range) {
8681 if (isa<CXXThisExpr>(E)) {
8682 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
8683 : diag::warn_this_bool_conversion;
8684 Diag(E->
getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
8688 bool IsAddressOf =
false;
8691 if (UO->getOpcode() != UO_AddrOf)
8694 E = UO->getSubExpr();
8698 unsigned DiagID = IsCompare
8699 ? diag::warn_address_of_reference_null_compare
8700 : diag::warn_address_of_reference_bool_conversion;
8708 auto ComplainAboutNonnullParamOrCall = [&](
const Attr *NonnullAttr) {
8709 bool IsParam = isa<NonNullAttr>(NonnullAttr);
8711 llvm::raw_string_ostream
S(Str);
8712 E->printPretty(S,
nullptr, getPrintingPolicy());
8713 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
8714 : diag::warn_cast_nonnull_to_bool;
8716 << E->getSourceRange() << Range << IsEqual;
8717 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
8723 if (
const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
8724 ComplainAboutNonnullParamOrCall(A);
8734 }
else if (
MemberExpr *M = dyn_cast<MemberExpr>(E)) {
8735 D = M->getMemberDecl();
8743 if (
const auto* PV = dyn_cast<ParmVarDecl>(D)) {
8744 if (getCurFunction() &&
8745 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
8746 if (
const Attr *A = PV->getAttr<NonNullAttr>()) {
8747 ComplainAboutNonnullParamOrCall(A);
8751 if (
const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
8752 auto ParamIter = llvm::find(FD->
parameters(), PV);
8756 for (
const auto *
NonNull : FD->specific_attrs<NonNullAttr>()) {
8758 ComplainAboutNonnullParamOrCall(
NonNull);
8762 for (
unsigned ArgNo :
NonNull->args()) {
8763 if (ArgNo == ParamNo) {
8764 ComplainAboutNonnullParamOrCall(
NonNull);
8778 if (IsAddressOf && IsFunction) {
8783 if (!IsAddressOf && !IsFunction && !IsArray)
8788 llvm::raw_string_ostream
S(Str);
8789 E->printPretty(S,
nullptr, getPrintingPolicy());
8791 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
8792 : diag::warn_impcast_pointer_to_bool;
8799 DiagType = AddressOf;
8800 else if (IsFunction)
8801 DiagType = FunctionPointer;
8803 DiagType = ArrayPointer;
8805 llvm_unreachable(
"Could not determine diagnostic.");
8806 Diag(E->
getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
8807 << Range << IsEqual;
8819 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
8820 if (ReturnType.isNull())
8827 if (!ReturnType->isPointerType()) {
8830 if (!ReturnType->isIntegerType())
8839 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
8855 if (isUnevaluatedContext())
8865 CheckArrayAccess(E);
8868 AnalyzeImplicitConversions(*
this, E, CC);
8874 ::CheckBoolLikeConversion(*
this, E, CC);
8879 void Sema::CheckForIntOverflow (
Expr *E) {
8884 Expr *E = Exprs.pop_back_val();
8891 if (
auto InitList = dyn_cast<InitListExpr>(E))
8892 Exprs.append(InitList->inits().begin(), InitList->inits().end());
8893 }
while (!Exprs.empty());
8907 class SequenceTree {
8909 explicit Value(
unsigned Parent) : Parent(Parent), Merged(
false) {}
8910 unsigned Parent : 31;
8911 unsigned Merged : 1;
8919 explicit Seq(
unsigned N) : Index(N) {}
8921 friend class SequenceTree;
8926 SequenceTree() { Values.push_back(
Value(0)); }
8927 Seq root()
const {
return Seq(0); }
8932 Seq allocate(Seq Parent) {
8933 Values.push_back(
Value(Parent.Index));
8934 return Seq(Values.size() - 1);
8939 Values[S.Index].Merged =
true;
8945 bool isUnsequenced(Seq Cur, Seq Old) {
8946 unsigned C = representative(Cur.Index);
8947 unsigned Target = representative(Old.Index);
8948 while (C >= Target) {
8951 C = Values[
C].Parent;
8958 unsigned representative(
unsigned K) {
8959 if (Values[K].Merged)
8961 return Values[K].Parent = representative(Values[K].Parent);
8981 UK_Count = UK_ModAsSideEffect + 1
8985 Usage() : Use(nullptr), Seq() {}
8987 SequenceTree::Seq Seq;
8991 UsageInfo() : Diagnosed(
false) {}
8992 Usage Uses[UK_Count];
8996 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
9002 UsageInfoMap UsageMap;
9004 SequenceTree::Seq Region;
9007 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
9010 SmallVectorImpl<Expr *> &WorkList;
9017 struct SequencedSubexpression {
9018 SequencedSubexpression(SequenceChecker &Self)
9019 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
9020 Self.ModAsSideEffect = &ModAsSideEffect;
9022 ~SequencedSubexpression() {
9023 for (
auto &M : llvm::reverse(ModAsSideEffect)) {
9024 UsageInfo &U = Self.UsageMap[M.first];
9025 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
9026 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
9027 SideEffectUsage = M.second;
9029 Self.ModAsSideEffect = OldModAsSideEffect;
9032 SequenceChecker &Self;
9034 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
9041 class EvaluationTracker {
9043 EvaluationTracker(SequenceChecker &Self)
9044 : Self(Self), Prev(Self.EvalTracker), EvalOK(
true) {
9045 Self.EvalTracker =
this;
9047 ~EvaluationTracker() {
9048 Self.EvalTracker = Prev;
9050 Prev->EvalOK &= EvalOK;
9053 bool evaluate(
const Expr *E,
bool &Result) {
9061 SequenceChecker &Self;
9062 EvaluationTracker *Prev;
9068 Object getObject(
Expr *E,
bool Mod)
const {
9071 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
9072 return getObject(UO->getSubExpr(), Mod);
9075 return getObject(BO->
getRHS(), Mod);
9077 return getObject(BO->
getLHS(), Mod);
9078 }
else if (
MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
9080 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
9081 return ME->getMemberDecl();
9082 }
else if (
DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9089 void addUsage(UsageInfo &UI, Object O,
Expr *Ref, UsageKind UK) {
9090 Usage &U = UI.Uses[UK];
9091 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
9092 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
9093 ModAsSideEffect->push_back(std::make_pair(O, U));
9099 void checkUsage(Object O, UsageInfo &UI,
Expr *Ref, UsageKind OtherKind,
9104 const Usage &U = UI.Uses[OtherKind];
9105 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
9109 Expr *ModOrUse = Ref;
9110 if (OtherKind == UK_Use)
9111 std::swap(Mod, ModOrUse);
9114 IsModMod ? diag::warn_unsequenced_mod_mod
9115 : diag::warn_unsequenced_mod_use)
9117 UI.Diagnosed =
true;
9120 void notePreUse(Object O,
Expr *Use) {
9121 UsageInfo &U = UsageMap[O];
9123 checkUsage(O, U, Use, UK_ModAsValue,
false);
9125 void notePostUse(Object O,
Expr *Use) {
9126 UsageInfo &U = UsageMap[O];
9127 checkUsage(O, U, Use, UK_ModAsSideEffect,
false);
9128 addUsage(U, O, Use, UK_Use);
9131 void notePreMod(Object O,
Expr *Mod) {
9132 UsageInfo &U = UsageMap[O];
9134 checkUsage(O, U, Mod, UK_ModAsValue,
true);
9135 checkUsage(O, U, Mod, UK_Use,
false);
9137 void notePostMod(Object O,
Expr *Use, UsageKind UK) {
9138 UsageInfo &U = UsageMap[O];
9139 checkUsage(O, U, Use, UK_ModAsSideEffect,
true);
9140 addUsage(U, O, Use, UK);
9144 SequenceChecker(
Sema &S,
Expr *E, SmallVectorImpl<Expr *> &WorkList)
9145 :
Base(S.Context), SemaRef(S), Region(Tree.root()),
9146 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
9150 void VisitStmt(
Stmt *S) {
9154 void VisitExpr(
Expr *E) {
9160 Object O = Object();
9176 SequenceTree::Seq LHS = Tree.allocate(Region);
9177 SequenceTree::Seq RHS = Tree.allocate(Region);
9178 SequenceTree::Seq OldRegion = Region;
9181 SequencedSubexpression SeqLHS(*
this);
9201 Object O = getObject(BO->
getLHS(),
true);
9203 return VisitExpr(BO);
9213 if (isa<CompoundAssignOperator>(BO))
9218 if (isa<CompoundAssignOperator>(BO))
9227 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
9228 : UK_ModAsSideEffect);
9232 VisitBinAssign(CAO);
9235 void VisitUnaryPreInc(
UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
9236 void VisitUnaryPreDec(
UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
9238 Object O = getObject(UO->
getSubExpr(),
true);
9240 return VisitExpr(UO);
9246 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
9247 : UK_ModAsSideEffect);
9250 void VisitUnaryPostInc(
UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
9251 void VisitUnaryPostDec(
UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
9253 Object O = getObject(UO->
getSubExpr(),
true);
9255 return VisitExpr(UO);
9259 notePostMod(O, UO, UK_ModAsSideEffect);
9268 EvaluationTracker Eval(*
this);
9270 SequencedSubexpression Sequenced(*
this);
9275 if (Eval.evaluate(BO->
getLHS(), Result)) {
9285 WorkList.push_back(BO->
getRHS());
9289 EvaluationTracker Eval(*
this);
9291 SequencedSubexpression Sequenced(*
this);
9296 if (Eval.evaluate(BO->
getLHS(), Result)) {
9300 WorkList.push_back(BO->
getRHS());
9307 EvaluationTracker Eval(*
this);
9309 SequencedSubexpression Sequenced(*
this);
9314 if (Eval.evaluate(CO->
getCond(), Result))
9329 SequencedSubexpression Sequenced(*
this);
9330 Base::VisitCallExpr(CE);
9337 SequencedSubexpression Sequenced(*
this);
9340 return VisitExpr(CCE);
9344 SequenceTree::Seq Parent = Region;
9348 Region = Tree.allocate(Parent);
9349 Elts.push_back(Region);
9355 for (
unsigned I = 0; I < Elts.size(); ++
I)
9356 Tree.merge(Elts[I]);
9360 if (!SemaRef.getLangOpts().CPlusPlus11)
9361 return VisitExpr(ILE);
9365 SequenceTree::Seq Parent = Region;
9369 Region = Tree.allocate(Parent);
9370 Elts.push_back(Region);
9376 for (
unsigned I = 0; I < Elts.size(); ++
I)
9377 Tree.merge(Elts[I]);
9382 void Sema::CheckUnsequencedOperations(
Expr *E) {
9384 WorkList.push_back(E);
9385 while (!WorkList.empty()) {
9386 Expr *Item = WorkList.pop_back_val();
9387 SequenceChecker(*
this, Item, WorkList);
9393 CheckImplicitConversions(E, CheckLoc);
9395 CheckUnsequencedOperations(E);
9397 CheckForIntOverflow(E);
9403 (void) AnalyzeBitFieldAssignment(*
this, BitField, Init, InitLoc);
9410 if (
const auto *PointerTy = dyn_cast<PointerType>(PType)) {
9414 if (
const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
9418 if (
const auto *ParenTy = dyn_cast<ParenType>(PType)) {
9432 S.
Diag(Loc, diag::err_array_star_in_function_definition);
9441 bool CheckParameterNames) {
9442 bool HasInvalidParm =
false;
9449 if (!Param->isInvalidDecl() &&
9450 RequireCompleteType(Param->getLocation(), Param->getType(),
9451 diag::err_typecheck_decl_incomplete_type)) {
9452 Param->setInvalidDecl();
9453 HasInvalidParm =
true;
9458 if (CheckParameterNames &&
9459 Param->getIdentifier() ==
nullptr &&
9460 !Param->isImplicit() &&
9461 !getLangOpts().CPlusPlus)
9462 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
9469 QualType PType = Param->getOriginalType();
9481 if (!Param->isInvalidDecl()) {
9483 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
9484 if (!ClassDecl->isInvalidDecl() &&
9488 MarkFunctionReferenced(Param->getLocation(), Destructor);
9489 DiagnoseUseOfDecl(Destructor, Param->getLocation());
9499 if (
const auto *
Attr = Param->getAttr<PassObjectSizeAttr>())
9500 if (!Param->getType().isConstQualified())
9501 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
9505 return HasInvalidParm;
9513 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.
getBegin()))
9522 if (!DestPtr)
return;
9528 if (DestAlign.
isOne())
return;
9532 if (!SrcPtr)
return;
9542 if (SrcAlign >= DestAlign)
return;
9548 << TRange << Op->getSourceRange();
9558 if (Size != 1 || !ND)
return false;
9561 if (!FD)
return false;
9584 if (!RD)
return false;
9585 if (RD->
isUnion())
return false;
9586 if (
const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
9587 if (!CRD->isStandardLayout())
return false;
9592 while ((D = D->getNextDeclInContext()))
9593 if (isa<FieldDecl>(D))
9598 void Sema::CheckArrayAccess(
const Expr *BaseExpr,
const Expr *IndexExpr,
9600 bool AllowOnePastEnd,
bool IndexNegated) {
9605 const Type *EffectiveType =
9620 if (
const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
9621 ND = dyn_cast<NamedDecl>(DRE->
getDecl());
9622 if (
const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
9623 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
9625 if (index.isUnsigned() || !index.isNegative()) {
9626 llvm::APInt size = ArrayTy->
getSize();
9627 if (!size.isStrictlyPositive())
9631 if (BaseType != EffectiveType) {
9633 uint64_t ptrarith_typesize = Context.
getTypeSize(EffectiveType);
9634 uint64_t array_typesize = Context.
getTypeSize(BaseType);
9636 if (!ptrarith_typesize) ptrarith_typesize = 1;
9637 if (ptrarith_typesize != array_typesize) {
9639 uint64_t ratio = array_typesize / ptrarith_typesize;
9642 if (ptrarith_typesize * ratio == array_typesize)
9643 size *= llvm::APInt(size.getBitWidth(), ratio);
9647 if (size.getBitWidth() > index.getBitWidth())
9648 index = index.zext(size.getBitWidth());
9649 else if (size.getBitWidth() < index.getBitWidth())
9650 size = size.zext(index.getBitWidth());
9656 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
9671 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
9673 IndexExpr->getLocStart());
9674 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
9679 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
9681 DiagID = diag::warn_array_index_exceeds_bounds;
9683 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
9684 PDiag(DiagID) << index.toString(10,
true)
9685 << size.toString(10,
true)
9686 << (
unsigned)size.getLimitedValue(~0U)
9687 << IndexExpr->getSourceRange());
9689 unsigned DiagID = diag::warn_array_index_precedes_bounds;
9691 DiagID = diag::warn_ptr_arith_precedes_bounds;
9692 if (index.isNegative()) index = -index;
9695 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
9696 PDiag(DiagID) << index.toString(10,
true)
9697 << IndexExpr->getSourceRange());
9703 dyn_cast<ArraySubscriptExpr>(BaseExpr))
9705 if (
const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
9707 if (
const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
9708 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
9712 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
9713 PDiag(diag::note_array_index_out_of_bounds)
9717 void Sema::CheckArrayAccess(
const Expr *
expr) {
9718 int AllowOnePastEnd = 0;
9721 switch (expr->getStmtClass()) {
9722 case Stmt::ArraySubscriptExprClass: {
9725 AllowOnePastEnd > 0);
9728 case Stmt::OMPArraySectionExprClass: {
9732 nullptr, AllowOnePastEnd > 0);
9735 case Stmt::UnaryOperatorClass: {
9751 case Stmt::ConditionalOperatorClass: {
9754 CheckArrayAccess(lhs);
9756 CheckArrayAccess(rhs);
9768 struct RetainCycleOwner {
9775 void setLocsFrom(
Expr *e) {
9777 Range = e->getSourceRange();
9791 owner.Variable = var;
9793 owner.setLocsFrom(ref);
9801 switch (
cast->getCastKind()) {
9803 case CK_LValueBitCast:
9804 case CK_LValueToRValue:
9805 case CK_ARCReclaimReturnedObject:
9806 e =
cast->getSubExpr();
9823 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
9824 owner.Indirect =
true;
9828 if (
DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
9830 if (!var)
return false;
9834 if (
MemberExpr *member = dyn_cast<MemberExpr>(e)) {
9835 if (member->isArrow())
return false;
9838 e = member->getBase();
9847 if (!pre)
return false;
9850 if (!property->isRetaining() &&
9851 !(
property->getPropertyIvarDecl() &&
9852 property->getPropertyIvarDecl()->getType()
9856 owner.Indirect =
true;
9859 if (!owner.Variable)
9862 owner.Range = pre->getSourceRange();
9865 e =
const_cast<Expr*
>(cast<OpaqueValueExpr>(pre->
getBase())
9880 Context(Context),
Variable(variable), Capturer(nullptr),
9881 VarWillBeReased(
false) {}
9885 bool VarWillBeReased;
9893 if (Capturer)
return;
9906 if (Capturer)
return;
9911 if (!Variable || VarWillBeReased || BinOp->
getOpcode() != BO_Assign)
9914 if (
const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
9921 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
9931 assert(owner.Variable && owner.Loc.isValid());
9939 e = ME->getInstanceReceiver();
9942 e = e->IgnoreParenCasts();
9944 }
else if (
CallExpr *CE = dyn_cast<CallExpr>(e)) {
9949 if (FnI && FnI->
isStr(
"_Block_copy")) {
9960 FindCaptureVisitor visitor(S.
Context, owner.Variable);
9962 return visitor.VarWillBeReased ?
nullptr : visitor.Capturer;
9966 RetainCycleOwner &owner) {
9968 assert(owner.Variable && owner.Loc.isValid());
9971 << owner.Variable << capturer->getSourceRange();
9972 S.
Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
9973 << owner.Indirect << owner.Range;
9982 while (!str.empty() && str.front() ==
'_') str = str.substr(1);
9983 if (str.startswith(
"set"))
9984 str = str.substr(3);
9985 else if (str.startswith(
"add")) {
9987 if (sel.
getNumArgs() == 1 && str.startswith(
"addOperationWithBlock"))
9989 str = str.substr(3);
9994 if (str.empty())
return true;
10000 bool IsMutableArray = S.
NSAPIObj->isSubclassOfNSClass(
10003 if (!IsMutableArray) {
10009 Optional<NSAPI::NSArrayMethodKind> MKOpt =
10010 S.
NSAPIObj->getNSArrayMethodKind(Sel);
10035 bool IsMutableDictionary = S.
NSAPIObj->isSubclassOfNSClass(
10038 if (!IsMutableDictionary) {
10044 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
10045 S.
NSAPIObj->getNSDictionaryMethodKind(Sel);
10066 bool IsMutableSet = S.
NSAPIObj->isSubclassOfNSClass(
10070 bool IsMutableOrderedSet = S.
NSAPIObj->isSubclassOfNSClass(
10073 if (!IsMutableSet && !IsMutableOrderedSet) {
10079 Optional<NSAPI::NSSetMethodKind> MKOpt = S.
NSAPIObj->getNSSetMethodKind(Sel);
10104 Optional<int> ArgOpt;
10112 int ArgIndex = *ArgOpt;
10120 if (
DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
10121 if (ArgRE->isObjCSelfExpr()) {
10122 Diag(Message->getSourceRange().getBegin(),
10123 diag::warn_objc_circular_container)
10124 << ArgRE->getDecl()->getName() << StringRef(
"super");
10134 if (
DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
10135 if (
DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
10136 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
10138 Diag(Message->getSourceRange().getBegin(),
10139 diag::warn_objc_circular_container)
10141 if (!ArgRE->isObjCSelfExpr()) {
10142 Diag(Decl->getLocation(),
10143 diag::note_objc_circular_container_declared_here)
10148 }
else if (
ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
10150 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
10152 Diag(Message->getSourceRange().getBegin(),
10153 diag::warn_objc_circular_container)
10155 Diag(Decl->getLocation(),
10156 diag::note_objc_circular_container_declared_here)
10171 RetainCycleOwner owner;
10177 owner.Variable = getCurMethodDecl()->getSelfDecl();
10183 for (
unsigned i = 0, e = msg->
getNumArgs(); i != e; ++i)
10190 RetainCycleOwner owner;
10199 RetainCycleOwner Owner;
10205 Owner.Loc = Var->getLocation();
10213 Expr *RHS,
bool isProperty) {
10225 S.
Diag(Loc, diag::warn_arc_literal_assign)
10227 << (isProperty ? 0 : 1)
10228 << RHS->getSourceRange();
10235 Expr *RHS,
bool isProperty) {
10238 if (
cast->getCastKind() == CK_ARCConsumeObject) {
10239 S.
Diag(Loc, diag::warn_arc_retained_assign)
10241 << (isProperty ? 0 : 1)
10242 << RHS->getSourceRange();
10245 RHS =
cast->getSubExpr();
10287 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
10288 getCurFunction()->markSafeWeakUse(LHS);
10291 if (checkUnsafeAssigns(Loc, LHSType, RHS))
10311 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
10316 if (
cast->getCastKind() == CK_ARCConsumeObject) {
10317 Diag(Loc, diag::warn_arc_retained_property_assign)
10318 << RHS->getSourceRange();
10321 RHS =
cast->getSubExpr();
10334 bool ShouldDiagnoseEmptyStmtBody(
const SourceManager &SourceMgr,
10347 bool StmtLineInvalid;
10350 if (StmtLineInvalid)
10353 bool BodyLineInvalid;
10356 if (BodyLineInvalid)
10360 if (StmtLine != BodyLine)
10372 if (CurrentInstantiationScope)
10381 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
10385 Diag(NBody->
getSemiLoc(), diag::note_empty_body_on_separate_line);
10389 const Stmt *PossibleBody) {
10390 assert(!CurrentInstantiationScope);
10395 if (
const ForStmt *FS = dyn_cast<ForStmt>(S)) {
10396 StmtLoc = FS->getRParenLoc();
10397 Body = FS->getBody();
10398 DiagID = diag::warn_empty_for_body;
10399 }
else if (
const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
10400 StmtLoc = WS->getCond()->getSourceRange().getEnd();
10401 Body = WS->getBody();
10402 DiagID = diag::warn_empty_while_body;
10412 if (Diags.isIgnored(DiagID, NBody->
getSemiLoc()))
10416 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
10430 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
10431 if (!ProbableTypo) {
10432 bool BodyColInvalid;
10434 PossibleBody->getLocStart(),
10436 if (BodyColInvalid)
10439 bool StmtColInvalid;
10443 if (StmtColInvalid)
10446 if (BodyCol > StmtCol)
10447 ProbableTypo =
true;
10450 if (ProbableTypo) {
10452 Diag(NBody->
getSemiLoc(), diag::note_empty_body_on_separate_line);
10461 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
10464 if (!ActiveTemplateInstantiations.empty())
10478 if (!FD || !FD->isInStdNamespace() || !FD->
getIdentifier() ||
10483 RHSExpr = CE->
getArg(0);
10489 if (LHSDeclRef && RHSDeclRef) {
10490 if (!LHSDeclRef->
getDecl() || !RHSDeclRef->getDecl())
10492 if (LHSDeclRef->
getDecl()->getCanonicalDecl() !=
10493 RHSDeclRef->getDecl()->getCanonicalDecl())
10496 Diag(OpLoc, diag::warn_self_move) << LHSExpr->
getType()
10497 << LHSExpr->getSourceRange()
10498 << RHSExpr->getSourceRange();
10506 const Expr *LHSBase = LHSExpr;
10507 const Expr *RHSBase = RHSExpr;
10510 if (!LHSME || !RHSME)
10513 while (LHSME && RHSME) {
10515 RHSME->getMemberDecl()->getCanonicalDecl())
10519 RHSBase = RHSME->getBase();
10526 if (LHSDeclRef && RHSDeclRef) {
10527 if (!LHSDeclRef->
getDecl() || !RHSDeclRef->getDecl())
10529 if (LHSDeclRef->
getDecl()->getCanonicalDecl() !=
10530 RHSDeclRef->getDecl()->getCanonicalDecl())
10533 Diag(OpLoc, diag::warn_self_move) << LHSExpr->
getType()
10534 << LHSExpr->getSourceRange()
10535 << RHSExpr->getSourceRange();
10539 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
10540 Diag(OpLoc, diag::warn_self_move) << LHSExpr->
getType()
10541 << LHSExpr->getSourceRange()
10542 << RHSExpr->getSourceRange();
10562 if (!isLayoutCompatible(C, Field1->
getType(), Field2->
getType()))
10573 if (Bits1 != Bits2)
10582 bool isLayoutCompatibleStruct(
ASTContext &C,
10586 if (
const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
10591 if (D1CXX->getNumBases() != D2CXX->
getNumBases())
10596 Base1 = D1CXX->bases_begin(),
10597 BaseEnd1 = D1CXX->bases_end(),
10600 ++Base1, ++Base2) {
10601 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
10604 }
else if (
const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
10615 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
10616 if (!isLayoutCompatible(C, *Field1, *Field2))
10619 if (Field1 != Field1End || Field2 != Field2End)
10630 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
10631 for (
auto *Field2 : RD2->
fields())
10632 UnmatchedFields.insert(Field2);
10634 for (
auto *Field1 : RD1->
fields()) {
10636 I = UnmatchedFields.begin(),
10637 E = UnmatchedFields.end();
10639 for ( ; I !=
E; ++
I) {
10640 if (isLayoutCompatible(C, Field1, *I)) {
10641 bool Result = UnmatchedFields.erase(*I);
10651 return UnmatchedFields.empty();
10659 return isLayoutCompatibleUnion(C, RD1, RD2);
10661 return isLayoutCompatibleStruct(C, RD1, RD2);
10684 if (TC1 == Type::Enum) {
10685 return isLayoutCompatible(C,
10686 cast<EnumType>(T1)->getDecl(),
10687 cast<EnumType>(T2)->getDecl());
10688 }
else if (TC1 == Type::Record) {
10692 return isLayoutCompatible(C,
10693 cast<RecordType>(T1)->getDecl(),
10694 cast<RecordType>(T2)->getDecl());
10711 bool FindTypeTagExpr(
const Expr *TypeExpr,
const ASTContext &Ctx,
10712 const ValueDecl **VD, uint64_t *MagicValue) {
10719 switch (TypeExpr->getStmtClass()) {
10720 case Stmt::UnaryOperatorClass: {
10729 case Stmt::DeclRefExprClass: {
10730 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
10735 case Stmt::IntegerLiteralClass: {
10737 llvm::APInt MagicValueAPInt = IL->
getValue();
10738 if (MagicValueAPInt.getActiveBits() <= 64) {
10739 *MagicValue = MagicValueAPInt.getZExtValue();
10745 case Stmt::BinaryConditionalOperatorClass:
10746 case Stmt::ConditionalOperatorClass: {
10748 cast<AbstractConditionalOperator>(TypeExpr);
10760 case Stmt::BinaryOperatorClass: {
10763 TypeExpr = BO->
getRHS();
10787 bool GetMatchingCType(
10792 bool &FoundWrongKind,
10794 FoundWrongKind =
false;
10799 uint64_t MagicValue;
10801 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
10805 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
10806 if (I->getArgumentKind() != ArgumentKind) {
10807 FoundWrongKind =
true;
10810 TypeInfo.
Type = I->getMatchingCType();
10823 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
10824 if (I == MagicValues->end())
10827 TypeInfo = I->second;
10833 uint64_t MagicValue,
QualType Type,
10834 bool LayoutCompatible,
10836 if (!TypeTagForDatatypeMagicValues)
10837 TypeTagForDatatypeMagicValues.reset(
10838 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
10841 (*TypeTagForDatatypeMagicValues)[Magic] =
10858 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
10859 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
10860 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
10861 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
10865 void Sema::CheckArgumentWithTypeTag(
const ArgumentWithTypeTagAttr *
Attr,
10866 const Expr *
const *ExprArgs) {
10868 bool IsPointerAttr = Attr->getIsPointer();
10870 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
10871 bool FoundWrongKind;
10872 TypeTagData TypeInfo;
10873 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
10874 TypeTagForDatatypeMagicValues.get(),
10875 FoundWrongKind, TypeInfo)) {
10876 if (FoundWrongKind)
10878 diag::warn_type_tag_for_datatype_wrong_kind)
10879 << TypeTagExpr->getSourceRange();
10883 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
10884 if (IsPointerAttr) {
10886 if (
const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
10887 if (ICE->getType()->isVoidPointerType() &&
10888 ICE->getCastKind() == CK_BitCast)
10889 ArgumentExpr = ICE->getSubExpr();
10897 if (TypeInfo.MustBeNull) {
10902 diag::warn_type_safety_null_pointer_required)
10904 << ArgumentExpr->getSourceRange()
10905 << TypeTagExpr->getSourceRange();
10910 QualType RequiredType = TypeInfo.Type;
10914 bool mismatch =
false;
10915 if (!TypeInfo.LayoutCompatible) {
10916 mismatch = !Context.
hasSameType(ArgumentType, RequiredType);
10924 if ((IsPointerAttr && IsSameCharType(ArgumentType->
getPointeeType(),
10926 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
10930 mismatch = !isLayoutCompatible(Context,
10934 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
10937 Diag(ArgumentExpr->
getExprLoc(), diag::warn_type_safety_type_mismatch)
10938 << ArgumentType << ArgumentKind
10939 << TypeInfo.LayoutCompatible << RequiredType
10940 << ArgumentExpr->getSourceRange()
10941 << TypeTagExpr->getSourceRange();
ObjCPropertyRefExpr - A dot-syntax expression to access an ObjC property.
const OptionalFlag & hasSpacePrefix() const
unsigned getFlags() const
getFlags - Return the flags for this scope.
The receiver is the instance of the superclass object.
static void diagnoseArrayStarInParamType(Sema &S, QualType PType, SourceLocation Loc)
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
static FormatStringType GetFormatStringType(const FormatAttr *Format)
bool isMacroArgExpansion(SourceLocation Loc, SourceLocation *StartLoc=nullptr) const
Tests whether the given source location represents a macro argument's expansion into the function-lik...
Defines the clang::ASTContext interface.
unsigned getNumInits() const
SourceLocation getEnd() const
static std::pair< QualType, StringRef > shouldNotPrintDirectly(const ASTContext &Context, QualType IntendedTy, const Expr *E)
const Expr * getBase() const
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
CastKind getCastKind() const
FunctionDecl - An instance of this class is created to represent a function declaration or definition...
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
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.
Scope * getCurScope() const
Retrieve the parser's current scope.
bool isNullPtrType() const
StringRef getName() const
getName - Get the name of identifier for this declaration as a StringRef.
static void CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType, SourceLocation ReturnLoc)
CheckReturnStackAddr - Check if a return statement returns the address of a stack variable...
Smart pointer class that efficiently represents Objective-C method names.
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
PointerType - C99 6.7.5.1 - Pointer Declarators.
EvaluatedExprVisitor - This class visits 'Expr *'s.
static llvm::SmallPtrSet< MemberKind *, 1 > CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty)
bool isAtLeastAsQualifiedAs(QualType Other) const
Determine whether this type is at least as qualified as the other given type, requiring exact equalit...
A (possibly-)qualified type.
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
static bool CheckForReference(Sema &SemaRef, const Expr *E, const PartialDiagnostic &PD)
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall)
OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different overload formats specified ...
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
bool isBitField() const
Determines whether this field is a bitfield.
ArrayRef< QualType > getTypeArgs() const
Retrieve the type arguments for this type.
bool hasLeadingEmptyMacro() const
bool isMemberPointerType() const
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc...
IdentifierInfo * getIdentifier() const
getIdentifier - Get the identifier that names this declaration, if there is one.
bool CheckParmsForFunctionDef(ArrayRef< ParmVarDecl * > Parameters, bool CheckParameterNames)
Helpers for dealing with blocks and functions.
bool isOne() const
isOne - Test whether the quantity equals one.
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
const LangOptions & getLangOpts() const
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false)
Perform unqualified name lookup starting from a given scope.
SourceLocation getSpellingLoc(SourceLocation Loc) const
Given a SourceLocation object, return the spelling location referenced by the ID. ...
static bool IsFunctionStdAbs(const FunctionDecl *FDecl)
static Optional< int > GetNSMutableArrayArgumentIndex(Sema &S, ObjCMessageExpr *Message)
FunctionType - C99 6.7.5.3 - Function Declarators.
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
EnumConstantDecl - An instance of this object exists for each enum constant that is defined...
unsigned getIntWidth(QualType T) const
const ScanfConversionSpecifier & getConversionSpecifier() const
const Scope * getParent() const
getParent - Return the scope that this is nested in.
void addConst()
Add the const type qualifier to this QualType.
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
bool isRecordType() const
unsigned getSpellingLineNumber(SourceLocation Loc, bool *Invalid=nullptr) const
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
bool hasValidThousandsGroupingPrefix() const
const char * getCharacterData(SourceLocation SL, bool *Invalid=nullptr) const
Return a pointer to the start of the specified location in the appropriate spelling MemoryBuffer...
bool isVoidPointerType() const
static bool referToTheSameDecl(const Expr *E1, const Expr *E2)
Check if two expressions refer to the same declaration.
const OptionalFlag & hasLeadingZeros() const
bool isEnumeralType() const
ParenExpr - This represents a parethesized expression, e.g.
Expr * getLowerBound()
Get lower bound of array section.
The base class of the type hierarchy.
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
unsigned getPresumedLineNumber(SourceLocation Loc, bool *Invalid=nullptr) const
bool capturesVariable(const VarDecl *var) 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()
bool usesPositionalArg() const
Represents a call to a C++ constructor.
Wrapper for source info for typedefs.
static AbsoluteValueKind getAbsoluteValueKind(QualType T)
bool isBooleanType() const
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 getOperatorLoc() const
SourceLocation getLocStart() const LLVM_READONLY
bool isBlockPointerType() const
bool isInSystemMacro(SourceLocation loc)
Returns whether Loc is expanded from a macro in a system header.
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
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.
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.
bool consumesDataArgument() const
const llvm::APInt & getSize() const
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.
ObjCDictionaryElement getKeyValueElement(unsigned Index) const
static void CheckFormatString(Sema &S, const StringLiteral *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)
VarDecl - An instance of this class is created to represent a variable declaration or definition...
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
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].
const Expr * getCallee() const
bool areArgsDestroyedLeftToRightInCallee() const
Are arguments to a call destroyed left to right in the callee? This is a fundamental language change...
APFloat & getComplexFloatReal()
ArgType getArgType(ASTContext &Ctx, bool IsObjCLiteral) const
Returns the builtin type that a data argument paired with this format specifier should have...
Extra information about a function prototype.
field_iterator field_begin() const
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
ObjCMethodDecl - Represents an instance or class method declaration.
Expr * IgnoreImplicit() LLVM_READONLY
IgnoreImplicit - Skip past any implicit AST nodes which might surround this expression.
Like System, but searched after the system directories.
Defines the Objective-C statement AST node classes.
static bool isAssignmentOp(Opcode Opc)
ParmVarDecl - Represents a parameter to a function.
bool isObjCRetainableType() const
NullPointerConstantKind isNullPointerConstant(ASTContext &Ctx, NullPointerConstantValueDependence NPC) const
isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to a Null pointer constant...
Defines the clang::Expr interface and subclasses for C++ expressions.
ObjCInterfaceDecl * NSDictionaryDecl
The declaration of the Objective-C NSDictionary class.
SourceLocation getLocation() const
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.
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
QualType withConst() const
Retrieves a version of this type with const applied.
static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, Qualifiers::ObjCLifetime LT, Expr *RHS, bool isProperty)
static bool requiresParensToAddCast(const Expr *E)
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...
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.
unsigned getNumParams() const
RecordDecl - Represents a struct/union/class.
ExprResult UsualUnaryConversions(Expr *E)
UsualUnaryConversions - Performs various conversions that are common to most operators (C99 6...
One of these records is kept for each identifier that is lexed.
std::unique_ptr< NSAPI > NSAPIObj
Caches identifiers/selectors for NSFoundation APIs.
bool isScalarType() const
bool isComplexInt() const
ShuffleVectorExpr - clang-specific builtin-in function __builtin_shufflevector.
class LLVM_ALIGNAS(8) DependentTemplateSpecializationType const IdentifierInfo * Name
Represents a template specialization type whose template cannot be resolved, e.g. ...
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
ArrayRef< QualType > getParamTypes() const
QualType getAddrSpaceQualType(QualType T, unsigned AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
bool isReferenceType() const
QualType getReturnType() const
virtual bool validateCpuSupports(StringRef Name) const
FieldDecl - An instance of this class is created by Sema::ActOnField to represent a member of a struc...
bool isCompleteDefinition() const
isCompleteDefinition - Return true if this decl has its body fully specified.
bool isAnyPointerType() const
static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op)
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
CXXRecordDecl * getDefinition() const
void setArg(unsigned Arg, Expr *ArgExpr)
setArg - Set the specified argument.
The iterator over UnresolvedSets.
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
bool isInlineNamespace() const
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)
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Stmt * getBody() const override
CanQualType OCLReserveIDTy
ObjCArrayLiteral - used for objective-c array containers; as in: @["Hello", NSApp, [NSNumber numberWithInt:42]];.
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
SourceLocation getRParenLoc() const
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.
SourceLocation getSuperLoc() const
Retrieve the location of the 'super' keyword for a class or instance message to 'super', otherwise an invalid source location.
Describes an C or C++ initializer list.
static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, unsigned Start, unsigned End)
ForStmt - This represents a 'for (init;cond;inc)' stmt.
static bool isEqualityOp(Opcode Opc)
Represents the results of name lookup.
const TargetInfo & getTargetInfo() const
SourceLocation getLocWithOffset(int Offset) const
Return a source location with the specified offset from this SourceLocation.
Expr * getTrueExpr() const
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 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...
bool hasValidPlusPrefix() const
unsigned getMinRequiredArguments() const
getMinRequiredArguments - Returns the minimum number of arguments needed to call this function...
QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error, unsigned *IntegerConstantArgs=nullptr) const
Return the type for the specified builtin.
SourceLocation getImmediateMacroCallerLoc(SourceLocation Loc) const
Gets the location of the immediate macro caller, one level up the stack toward the initial macro type...
bool isSuperReceiver() const
static bool isNonNullType(ASTContext &ctx, QualType type)
Determine whether the given type has a non-null nullability annotation.
field_range fields() const
unsigned LayoutCompatible
If true, Type should be compared with other expression's types for layout-compatibility.
bool isMacroBodyExpansion(SourceLocation Loc) const
Tests whether the given source location represents the expansion of a macro body. ...
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
Represents a typeof (or typeof) expression (a GCC extension).
A builtin binary operation expression such as "x + y" or "x <= y".
Selector getSelector() const
bool isValueDependent() const
isValueDependent - Determines whether this expression is value-dependent (C++ [temp.dep.constexpr]).
RecordDecl * getDecl() const
bool isUnsignedIntegerType() const
Return true if this is an integer type that is unsigned, according to C99 6.2.5p6 [which returns true...
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.
Scope - A scope is a transient data structure that is used while parsing the program.
static const Expr * EvalVal(const Expr *E, SmallVectorImpl< const DeclRefExpr * > &refVars, const Decl *ParentDecl)
EvalVal - This function is complements EvalAddr in the mutual recursion.
NSSetMethodKind
Enumerates the NSMutableSet/NSOrderedSet methods used to apply some checks.
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr...
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
TypeClass getTypeClass() const
base_class_iterator bases_begin()
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types...
QualType withVolatile() const
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
const char * getHeaderName(unsigned ID) const
If this is a library function that comes from a specific header, retrieve that header name...
AssignConvertType CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS, bool Diagnose=true, bool DiagnoseCFAudited=false, bool ConvertRHS=true)
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)...
const Expr * getBase() const
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.
Expression is a GNU-style __null constant.
detail::InMemoryDirectory::const_iterator I
static void diagnoseRetainCycle(Sema &S, Expr *capturer, RetainCycleOwner &owner)
PropertyAttributeKind getPropertyAttributes() const
APSInt & getComplexIntReal()
QualType getCanonicalTypeInternal() const
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
CanQualType UnsignedCharTy
This object can be modified without requiring retains or releases.
param_iterator param_begin()
field_iterator field_end() const
APValue & getVectorElt(unsigned I)
bool isAddrLabelDiff() const
OpenMP 4.0 [2.4, Array Sections].
ConditionalOperator - The ?: ternary operator.
Sema - This implements semantic analysis and AST building for C.
Expr * getFalseExpr() const
llvm::APInt getValue() const
bool AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const
QualType getParamType(unsigned i) const
Represents a prototype with parameter type info, e.g.
bool hasIrrelevantDestructor() const
Determine whether this class has a destructor which has no semantic effect.
bool isFloatingPoint() const
bool isInstanceMessage() const
Determine whether this is an instance message to either a computed object or to super.
FileID getFileID(SourceLocation SpellingLoc) const
Return the FileID for a SourceLocation.
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
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...
CastKind
CastKind - The kind of operation required for a conversion.
std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const
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...
unsigned getPresumedColumnNumber(SourceLocation Loc, bool *Invalid=nullptr) const
bool isInstantiationDependent() const
Whether this expression is instantiation-dependent, meaning that it depends in some way on a template...
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee...
bool isUnarySelector() const
bool isFunctionPointerType() const
bool isRealFloatingType() const
Floating point categories.
unsigned getTypeWidth(IntType T) const
Return the width (in bits) of the specified integer type enum.
bool hasValidAlternativeForm() const
NSArrayMethodKind
Enumerates the NSArray/NSMutableArray methods used to generate literals and to apply some checks...
Retains information about a block that is currently being parsed.
static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl, CallExpr *TheCall, unsigned SizeIdx, unsigned DstSizeIdx)
BlockDecl - This represents a block literal declaration, which is like an unnamed FunctionDecl...
static void CheckNonNullArguments(Sema &S, const NamedDecl *FDecl, const FunctionProtoType *Proto, ArrayRef< const Expr * > Args, SourceLocation CallSiteLoc)
bool isKnownToHaveBooleanValue() const
isKnownToHaveBooleanValue - Return true if this is an integer expression that is known to return 0 or...
QualType getPointeeType() const
ValueDecl - Represent the declaration of a variable (in which case it is an lvalue) a function (in wh...
Expr - This represents one expression.
StringRef getName() const
Return the actual identifier string.
Allow any unmodeled side effect.
const char * getName(unsigned ID) const
Return the identifier name for the specified builtin, e.g.
Represents a character-granular source range.
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
unsigned getNumArgs() const
bool isAnyComplexType() const
bool isSEHExceptScope() const
Determine whether this scope is a SEH '__except' block.
bool isListInitialization() const
Whether this constructor call was written as list-initialization.
Expr * getBitWidth() const
bool isComplexFloat() const
bool isAtomicType() 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...
bool isUnsignedInteger() const
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Represents a C++ destructor within a class.
This scope corresponds to an SEH except.
bool isVariableArrayType() const
const ParmVarDecl * getParamDecl(unsigned i) const
ObjCDictionaryLiteral - AST node to represent objective-c dictionary literals; as in:"name" : NSUserN...
bool hasValidFieldWidth() const
ObjCInterfaceDecl * getReceiverInterface() const
Retrieve the Objective-C interface to which this message is being directed, if known.
void setObjectKind(ExprObjectKind Cat)
setObjectKind - Set the object kind produced by this expression.
bool isFloatingType() const
ImplicitParamDecl * getSelfDecl() const
void removeLocalVolatile()
char __ovld __cnfn min(char x, char y)
Returns y if y < x, otherwise it returns x.
unsigned getNumElements() const
getNumElements - Return number of elements of objective-c array literal.
SourceLocation getQuestionLoc() const
SourceLocation getLocation() const
Expr * getSubExpr() const
Expr * getElement(unsigned Index)
getExpr - Return the Expr at the specified index.
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
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.
static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call)
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...
const PrintfConversionSpecifier & getConversionSpecifier() const
An expression that sends a message to the given Objective-C object or class.
UnaryOperator - This represents the unary-expression's (except sizeof and alignof), the postinc/postdec operators from postfix-expression, and various extensions.
ArrayRef< ParmVarDecl * > parameters() const
SmallVector< ActiveTemplateInstantiation, 16 > ActiveTemplateInstantiations
List of active template instantiations.
Represents a GCC generic vector type.
static OpenCLAccessAttr * getOpenCLArgAccess(const Decl *D)
Returns OpenCL access qual.
DeclarationName getDeclName() const
getDeclName - Get the actual, stored name of the declaration, which may be a special name...
class LLVM_ALIGNAS(8) TemplateSpecializationType unsigned NumArgs
Represents a type template specialization; the template must be a class template, a type alias templa...
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...
unsigned getNumBases() const
Retrieves the number of base classes of this class.
APSInt & getComplexIntImag()
ObjCStringFormatFamily getObjCFStringFormattingFamily() const
The result type of a method or function.
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.
NestedNameSpecifierLoc getQualifierLoc() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name, with source-location information.
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...
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
SourceLocation getSemiLoc() const
void EvaluateForOverflow(const ASTContext &Ctx) const
TypeSourceInfo * getTypeSourceInfo() const
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...
Expr * getTrueExpr() 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 CharSourceRange getCharRange(SourceRange R)
const ParmVarDecl * getParamDecl(unsigned i) const
bool isNothrow(const ASTContext &Ctx, bool ResultIfDependent=false) const
Determine whether this function type has a non-throwing exception specification.
std::pair< const IdentifierInfo *, uint64_t > TypeTagMagicValue
A pair of ArgumentKind identifier and magic value.
static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call)
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)
There is no lifetime qualification on this type.
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
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.
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 ...
ConvertVectorExpr - Clang builtin function __builtin_convertvector This AST node provides support for...
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
Assigning into this object requires the old value to be released and the new value to be retained...
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
const char * getSpelling() const
not a target-specific vector type
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner)
Consider whether capturing the given variable can possibly lead to a retain cycle.
Encodes a location in the source.
bool hasIntegerRepresentation() const
Determine whether this type has an integer representation of some sort, e.g., it is an integer type o...
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
unsigned getNumParams() const
getNumParams - Return the number of parameters this function must have based on its FunctionType...
static const Expr * getSizeOfExprArg(const Expr *E)
If E is a sizeof expression, returns its argument expression, otherwise returns NULL.
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums...
const TemplateArgument * iterator
Expression is not a Null pointer constant.
bool isConstant(const ASTContext &Ctx) const
unsigned getBitWidthValue(const ASTContext &Ctx) const
Expr * getSourceExpr() const
The source expression of an opaque value expression is the expression which originally generated the ...
void checkRetainCycles(ObjCMessageExpr *msg)
checkRetainCycles - Check whether an Objective-C message send might create an obvious retain cycle...
static const Expr * ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx)
bool isValid() const
Return true if this is a valid SourceLocation object.
StringRef getNameForSlot(unsigned argIndex) const
Retrieve the name at a given position in the selector.
ASTContext & getASTContext() const
bool refersToEnclosingVariableOrCapture() const
Does this DeclRefExpr refer to an enclosing local or a captured variable?
QualType withConst() const
ExprObjectKind
A further classification of the kind of object referenced by an l-value or x-value.
Represents a static or instance method of a struct/union/class.
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.
ArrayRef< ParmVarDecl * > parameters() const
virtual bool hasSjLjLowering() const
Controls if __builtin_longjmp / __builtin_setjmp can be lowered to llvm.eh.sjlj.longjmp / llvm...
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
const ConstantArrayType * getAsConstantArrayType(QualType T) const
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...
const OptionalFlag & hasPlusPrefix() const
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...
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>.
Specifies that a value-dependent expression should be considered to never be a null pointer constant...
unsigned getMemoryFunctionKind() const
Identify a memory copying or setting function.
Look up any declaration with any name.
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
static bool isBlockPointer(Expr *Arg)
EltType getEltType() const
bool FormatStringHasSArg(const StringLiteral *FExpr)
bool isReserveIDT() const
Represents one property declaration in an Objective-C interface.
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
bool hasValidPrecision() const
bool containsNonAsciiOrNull() const
SourceLocation getBegin() 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.
const T * castAs() const
Member-template castAs<specific type>.
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.
const IdentifierInfo * getIdentifier() const
bool isVectorType() const
SourceRange getSourceRange() const override LLVM_READONLY
static bool isLogicalOp(Opcode Opc)
bool hasCStrMethod(const Expr *E)
Check to see if a given expression could have '.c_str()' called on it.
unsigned getBuiltinID() const
Returns a value indicating whether this function corresponds to a builtin function.
bool isPromotableIntegerType() const
More type predicates useful for type checking/promotion.
Assigning into this object requires a lifetime extension.
SourceRange getSourceRange() const override LLVM_READONLY
SourceLocation getLocStart() const LLVM_READONLY
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call)
const BlockDecl * getBlockDecl() const
SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL, unsigned ByteNo) const
We are currently in the filter expression of an SEH except block.
QualType getType() const
Return the type wrapped by this type source info.
static StringRef getImmediateMacroName(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Retrieve the name of the immediate macro expansion.
bool isDynamicClass() const
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...
bool isFunctionProtoType() const
QualType getPointeeType() const
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
SourceLocation getRBracketLoc() const
CompoundAssignOperator - For compound assignments (e.g.
Expr * getInstanceReceiver()
Returns the object expression (receiver) for an instance message, or null for a message that is not a...
QualType getCallReturnType(const ASTContext &Ctx) const
getCallReturnType - Get the return type of the call expr.
CanQualType UnsignedShortTy
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
bool isTSBuiltin(unsigned ID) const
Return true if this function is a target-specific builtin.
Base class for declarations which introduce a typedef-name.
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
bool hasValidLeadingZeros() const
NullStmt - This is the null statement ";": C99 6.8.3p3.
bool isImplicitProperty() const
EvalResult is a struct with detailed info about an evaluated expression.
static bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx)
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return 0.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
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.
ObjCLiteralKind CheckLiteralKind(Expr *FromE)
const OptionalFlag & hasThousandsGrouping() const
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the current evaluation context.
CanQualType UnsignedLongLongTy
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
std::pair< SourceLocation, SourceLocation > getImmediateExpansionRange(SourceLocation Loc) const
Return the start/end of the expansion information for an expansion location.
static QualType getAbsoluteValueArgumentType(ASTContext &Context, unsigned AbsType)
bool isStandardLayoutType() const
Test if this type is a standard-layout type.
QualType getExceptionObjectType(QualType T) const
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
DeclarationName - The name of a declaration.
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
StringRef getString() const
SourceLocation getLocStart() const LLVM_READONLY
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
EnumDecl - Represents an enum.
Expression is a C++11 nullptr.
detail::InMemoryDirectory::const_iterator E
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Flags to identify the types for overloaded Neon builtins.
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)
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).
ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
SemaConvertVectorExpr - Handle __builtin_convertvector.
bool consumesDataArgument() const
Expr * IgnoreParenImpCasts() LLVM_READONLY
IgnoreParenImpCasts - Ignore parentheses and implicit casts.
param_iterator param_end()
static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall)
Represents a pointer to an Objective C object.
static LLVM_READONLY bool isLowercase(unsigned char c)
Return true if this character is a lowercase ASCII letter: [a-z].
ArgType getArgType(ASTContext &Ctx) 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.
unsigned getNumNegativeBits() const
Returns the width in bits required to store all the negative enumerators of this enum.
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>.
SourceManager & getSourceManager() const
const T * getAs() const
Member-template getAs<specific type>'.
Expr * getFalseExpr() const
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
QualType getCanonicalType() const
AbstractConditionalOperator - An abstract base class for ConditionalOperator and BinaryConditionalOpe...
CanQualType UnsignedLongTy
static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call)
bool isObjCQualifiedIdType() const
QualType getIntegerType() const
getIntegerType - Return the integer type this enum decl corresponds to.
bool hasValidSpacePrefix() const
static unsigned RFT(unsigned t, bool shift=false, bool ForceQuad=false)
SourceLocation getLocStart() const LLVM_READONLY
const OptionalAmount & getPrecision() const
bool isFunctionType() const
const OptionalFlag & hasAlternativeForm() const
bool isComplete() const
Returns true if this can be considered a complete type.
static bool isAdditiveOp(Opcode Opc)
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
ObjCInterfaceDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this Objective-C class.
uint64_t getCharWidth() const
Return the size of the character type, in bits.
bool hasValidLeftJustified() const
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.
ObjCInterfaceDecl * NSArrayDecl
The declaration of the Objective-C NSArray class.
SourceLocation getLocEnd() const LLVM_READONLY
unsigned getNumArgs() const
Return the number of actual arguments in this message, not counting the receiver. ...
SourceLocation getExprLoc() const LLVM_READONLY
static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, unsigned AbsKind, QualType ArgType)
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat]...
Represents a base class of a C++ class.
ObjCPropertyDecl * getExplicitProperty() const
char __ovld __cnfn max(char x, char y)
Returns y if x < y, otherwise it returns x.
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.
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
bool hasNonTrivialObjCLifetime() const
Reading or writing from this object requires a barrier call.
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate.h) and friends (in DeclFriend.h).
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 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.
const OptionalFlag & isLeftJustified() const
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
APFloat & getComplexFloatImag()
unsigned getNumPositiveBits() const
Returns the width in bits required to store all the non-negative enumerators of this enum...
Represents a C++ struct/union/class.
Compatible - the types are compatible according to the standard.
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
bool isObjCObjectPointerType() const
static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr, SourceLocation CallSiteLoc)
ObjCIvarDecl - Represents an ObjC instance variable.
ArraySizeModifier getSizeModifier() const
WhileStmt - This represents a 'while' stmt.
IntType getInt64Type() const
Builtin::Context & BuiltinInfo
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.
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.
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
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]).
PropertyAttributeKind getPropertyAttributesAsWritten() const
void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, SourceLocation OpLoc)
Warn if a value is moved to itself.
A reference to a declared variable, function, enum, etc.
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
virtual bool hasFeature(StringRef Feature) const
Determine whether the given target has the given feature.
static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl)
QualType getElementType() const
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...
QualType getElementType() const
SourceManager & SourceMgr
const Expr * getInit(unsigned Init) const
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 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.
ExprIterator arg_iterator
An l-value expression is a reference to an object with independent storage.
static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc)
const llvm::fltSemantics & getFloatTypeSemantics(QualType T) const
Return the APFloat 'semantics' for the specified scalar floating point type.
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 bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, Expr *RHS, bool isProperty)
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...
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.
bool isConstQualified() const
Determine whether this type is const-qualified.
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.
bool isNull() const
Return true if this QualType doesn't point to a type yet.
TypeSourceInfo * getTypeSourceInfo() const
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.
static InitializedEntity InitializeParameter(ASTContext &Context, ParmVarDecl *Parm)
Create the initialization entity for a parameter.
NamespaceDecl * getStdNamespace() const
static bool isComparisonOp(Opcode Opc)
Optional< NullabilityKind > getNullability(const ASTContext &context) const
Determine the nullability of the given type.
static Expr * findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner)
Check whether the given argument is a block which captures a variable.
ReceiverKind getReceiverKind() const
Determine the kind of receiver that this message is being sent to.
static Optional< int > GetNSMutableDictionaryArgumentIndex(Sema &S, ObjCMessageExpr *Message)
static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall)
This class handles loading and caching of source files into memory.
Represents the canonical version of C arrays with a specified constant size.
unsigned getVectorLength() const
bool isObjC(ID Id)
isObjC - Is this an "ObjC" input (Obj-C and Obj-C++ sources and headers).
unsigned getNumElements() const
getNumElements - Return number of elements of objective-c dictionary literal.
NullPointerConstantKind
Enumeration used to describe the kind of Null pointer constant returned from isNullPointerConstant()...
Attr - This represents one attribute.
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...
CanQualType OCLClkEventTy
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Helper class that creates diagnostics with optional template instantiation stacks.
Expr * IgnoreParens() LLVM_READONLY
IgnoreParens - Ignore parentheses.
CanQualType UnsignedIntTy
Expr * getBase()
An array section can be written only as Base[LowerBound:Length].
bool isPointerType() const
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any...