SemaChecking.cpp revision a9766411aaaa1446a5da96dc5042de8da05d89bd
16f34213f8d6ae8c77685b53664527e39bfaaca3bTed Kremenek//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===// 2610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek// 3610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek// The LLVM Compiler Infrastructure 4610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek// 5610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek// This file is distributed under the University of Illinois Open Source 6610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek// License. See LICENSE.TXT for details. 7610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek// 8610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek//===----------------------------------------------------------------------===// 9610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek// 10610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek// This file implements extra semantic analysis beyond what is enforced 11610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek// by the C type system. 12610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek// 13610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek//===----------------------------------------------------------------------===// 14558e8872b364b43ab9f201dd6b2df9a5b74b0542Richard Smith 152fa67efeaf66a9332c30a026dc1c21bef6c33a6cBenjamin Kramer#include "clang/Sema/Initialization.h" 16610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek#include "clang/Sema/Sema.h" 17d049b40ef411eee12a735233dbe04fdc42c67e1aJordan Rose#include "clang/Sema/SemaInternal.h" 18c1602581f7a4eab486489f09647d724ce35d3f23Ted Kremenek#include "clang/Sema/Initialization.h" 196f34213f8d6ae8c77685b53664527e39bfaaca3bTed Kremenek#include "clang/Sema/ScopeInfo.h" 202fa67efeaf66a9332c30a026dc1c21bef6c33a6cBenjamin Kramer#include "clang/Analysis/Analyses/FormatString.h" 212fa67efeaf66a9332c30a026dc1c21bef6c33a6cBenjamin Kramer#include "clang/AST/ASTContext.h" 2225c1d57fc906e895535fb5c7e6dde80219f353b5Ted Kremenek#include "clang/AST/CharUnits.h" 232fa67efeaf66a9332c30a026dc1c21bef6c33a6cBenjamin Kramer#include "clang/AST/DeclCXX.h" 242fa67efeaf66a9332c30a026dc1c21bef6c33a6cBenjamin Kramer#include "clang/AST/DeclObjC.h" 252fa67efeaf66a9332c30a026dc1c21bef6c33a6cBenjamin Kramer#include "clang/AST/ExprCXX.h" 262fa67efeaf66a9332c30a026dc1c21bef6c33a6cBenjamin Kramer#include "clang/AST/ExprObjC.h" 272fa67efeaf66a9332c30a026dc1c21bef6c33a6cBenjamin Kramer#include "clang/AST/EvaluatedExprVisitor.h" 28b2c60b04a597cc5ba4154837cf8e0a155a376fd7Argyrios Kyrtzidis#include "clang/AST/DeclObjC.h" 292fa67efeaf66a9332c30a026dc1c21bef6c33a6cBenjamin Kramer#include "clang/AST/StmtCXX.h" 30610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek#include "clang/AST/StmtObjC.h" 31610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek#include "clang/Lex/Preprocessor.h" 32610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek#include "llvm/ADT/BitVector.h" 33558e8872b364b43ab9f201dd6b2df9a5b74b0542Richard Smith#include "llvm/ADT/STLExtras.h" 34558e8872b364b43ab9f201dd6b2df9a5b74b0542Richard Smith#include "llvm/Support/raw_ostream.h" 3540900ee8f3072d05456134b57c0fad85a6bb21a6Ted Kremenek#include "clang/Basic/TargetBuiltins.h" 361cbc31515e9b979f55178ffd4587e8671f7ebbfaTed Kremenek#include "clang/Basic/TargetInfo.h" 37ef8225444452a1486bd721f3285301fe84643b00Stephen Hines#include "clang/Basic/ConvertUTF.h" 381cbc31515e9b979f55178ffd4587e8671f7ebbfaTed Kremenek#include <limits> 391cbc31515e9b979f55178ffd4587e8671f7ebbfaTed Kremenekusing namespace clang; 401cbc31515e9b979f55178ffd4587e8671f7ebbfaTed Kremenekusing namespace sema; 411cbc31515e9b979f55178ffd4587e8671f7ebbfaTed Kremenek 421cbc31515e9b979f55178ffd4587e8671f7ebbfaTed KremenekSourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL, 43c104e53639de4424b83955acfadc977773b5883dTed Kremenek unsigned ByteNo) const { 44c104e53639de4424b83955acfadc977773b5883dTed Kremenek return SL->getLocationOfByte(ByteNo, PP.getSourceManager(), 45610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek PP.getLangOptions(), PP.getTargetInfo()); 46136f8f24b0b6c0e57aaa4375d280d72dc5492615Ted Kremenek} 47610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek 48610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek 49610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek/// CheckablePrintfAttr - does a function call have a "printf" attribute 50136f8f24b0b6c0e57aaa4375d280d72dc5492615Ted Kremenek/// and arguments that merit checking? 51610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenekbool Sema::CheckablePrintfAttr(const FormatAttr *Format, CallExpr *TheCall) { 52610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek if (Format->getType() == "printf") return true; 53136f8f24b0b6c0e57aaa4375d280d72dc5492615Ted Kremenek if (Format->getType() == "printf0") { 54610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek // printf0 allows null "format" string; if so don't check format/args 55610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek unsigned format_idx = Format->getFormatIdx() - 1; 56610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek // Does the index refer to the implicit object argument? 57610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek if (isa<CXXMemberCallExpr>(TheCall)) { 58610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek if (format_idx == 0) 59610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek return false; 60610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek --format_idx; 61610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek } 62dc84cd5efdd3430efb22546b4ac656aa0540b210David Blaikie if (format_idx < TheCall->getNumArgs()) { 63610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek Expr *Format = TheCall->getArg(format_idx)->IgnoreParenCasts(); 64610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek if (!Format->isNullPointerConstant(Context, 65610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek Expr::NPC_ValueDependentIsNull)) 66136f8f24b0b6c0e57aaa4375d280d72dc5492615Ted Kremenek return true; 67610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek } 68610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek } 69610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek return false; 70610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek} 71581deb3da481053c4993c7600f97acf7768caac5David Blaikie 7240900ee8f3072d05456134b57c0fad85a6bb21a6Ted Kremenek/// Checks that a call expression's argument count is the desired number. 73610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek/// This is useful when doing custom type-checking. Returns true on error. 74610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenekstatic bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) { 75610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek unsigned argCount = call->getNumArgs(); 76610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek if (argCount == desiredArgCount) return false; 77dc84cd5efdd3430efb22546b4ac656aa0540b210David Blaikie 78b831c673621c5587642343cace9def134916a17bTed Kremenek if (argCount < desiredArgCount) 79610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args) 8066874fb18afbffb8b2ca05576851a64534be3352David Blaikie << 0 /*function call*/ << desiredArgCount << argCount 81610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek << call->getSourceRange(); 82610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek 83610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek // Highlight all the excess arguments. 84610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek SourceRange range(call->getArg(desiredArgCount)->getLocStart(), 85610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek call->getArg(argCount - 1)->getLocEnd()); 86610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek 87610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args) 88f7bafc77ba12bb1beb665243a0334cd81e024728Ted Kremenek << 0 /*function call*/ << desiredArgCount << argCount 89f7bafc77ba12bb1beb665243a0334cd81e024728Ted Kremenek << call->getArg(1)->getSourceRange(); 90f7bafc77ba12bb1beb665243a0334cd81e024728Ted Kremenek} 91f7bafc77ba12bb1beb665243a0334cd81e024728Ted Kremenek 92f7bafc77ba12bb1beb665243a0334cd81e024728Ted Kremenek/// CheckBuiltinAnnotationString - Checks that string argument to the builtin 93f7bafc77ba12bb1beb665243a0334cd81e024728Ted Kremenek/// annotation is a non wide string literal. 94f7bafc77ba12bb1beb665243a0334cd81e024728Ted Kremenekstatic bool CheckBuiltinAnnotationString(Sema &S, Expr *Arg) { 95f7bafc77ba12bb1beb665243a0334cd81e024728Ted Kremenek Arg = Arg->IgnoreParenCasts(); 96f7bafc77ba12bb1beb665243a0334cd81e024728Ted Kremenek StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 97f7bafc77ba12bb1beb665243a0334cd81e024728Ted Kremenek if (!Literal || !Literal->isAscii()) { 98f7bafc77ba12bb1beb665243a0334cd81e024728Ted Kremenek S.Diag(Arg->getLocStart(), diag::err_builtin_annotation_not_string_constant) 99f7bafc77ba12bb1beb665243a0334cd81e024728Ted Kremenek << Arg->getSourceRange(); 100f7bafc77ba12bb1beb665243a0334cd81e024728Ted Kremenek return true; 101afb10c4bda2ac2c268fa7e6c11141584f57de119Ted Kremenek } 102da57f3eeab7b7f7f6e6788956f0a0d9adf196a7dBenjamin Kramer return false; 103afb10c4bda2ac2c268fa7e6c11141584f57de119Ted Kremenek} 104da3d76b4cfbb5ebeb79e03a0abeabd403fe9260aBenjamin Kramer 10513bd4236ab8297350be388ab442b4c42eb8fe437Ted KremenekExprResult 106610068c8cd2321f90e147b12cf794e1f840b6405Ted KremenekSema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 107610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek ExprResult TheCallResult(Owned(TheCall)); 108da3d76b4cfbb5ebeb79e03a0abeabd403fe9260aBenjamin Kramer 109136f8f24b0b6c0e57aaa4375d280d72dc5492615Ted Kremenek // Find out if any arguments are required to be integer constant expressions. 1104ddb3871307376d27d0f276c9da0ecce0384f01fTed Kremenek unsigned ICEArguments = 0; 111610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek ASTContext::GetBuiltinTypeError Error; 112610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 113eee18c38b6dd29c0e6982f5565fcbc3f76d1bf4dTed Kremenek if (Error != ASTContext::GE_None) 114d40066b0fb883839a9100e5455e33190b9b8abacTed Kremenek ICEArguments = 0; // Don't diagnose previously diagnosed errors. 115d40066b0fb883839a9100e5455e33190b9b8abacTed Kremenek 116610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek // If any arguments are required to be ICE's, check and diagnose. 117eee18c38b6dd29c0e6982f5565fcbc3f76d1bf4dTed Kremenek for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 118da3d76b4cfbb5ebeb79e03a0abeabd403fe9260aBenjamin Kramer // Skip arguments not required to be ICE's. 119eee18c38b6dd29c0e6982f5565fcbc3f76d1bf4dTed Kremenek if ((ICEArguments & (1 << ArgNo)) == 0) continue; 12013bd4236ab8297350be388ab442b4c42eb8fe437Ted Kremenek 121a9e8b9e3e90fcfe10a04624a89c39b63c32614d1Richard Smith llvm::APSInt Result; 122136f8f24b0b6c0e57aaa4375d280d72dc5492615Ted Kremenek if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 123136f8f24b0b6c0e57aaa4375d280d72dc5492615Ted Kremenek return true; 124610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek ICEArguments &= ~(1 << ArgNo); 125610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek } 1264ddb3871307376d27d0f276c9da0ecce0384f01fTed Kremenek 127610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek switch (BuiltinID) { 128e0e29332c89da22b6890929b97e6f568c917d85fTed Kremenek case Builtin::BI__builtin___CFStringMakeConstantString: 129610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek assert(TheCall->getNumArgs() == 1 && 13013bd4236ab8297350be388ab442b4c42eb8fe437Ted Kremenek "Wrong # arguments to builtin CFStringMakeConstantString"); 131136f8f24b0b6c0e57aaa4375d280d72dc5492615Ted Kremenek if (CheckObjCString(TheCall->getArg(0))) 1322815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith return ExprError(); 1332815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith break; 1342815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith case Builtin::BI__builtin_stdarg_start: 135dc84cd5efdd3430efb22546b4ac656aa0540b210David Blaikie case Builtin::BI__builtin_va_start: 1362815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith if (SemaBuiltinVAStart(TheCall)) 137eee18c38b6dd29c0e6982f5565fcbc3f76d1bf4dTed Kremenek return ExprError(); 1382815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith break; 139610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek case Builtin::BI__builtin_isgreater: 140da57f3eeab7b7f7f6e6788956f0a0d9adf196a7dBenjamin Kramer case Builtin::BI__builtin_isgreaterequal: 141610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek case Builtin::BI__builtin_isless: 142eee18c38b6dd29c0e6982f5565fcbc3f76d1bf4dTed Kremenek case Builtin::BI__builtin_islessequal: 143610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek case Builtin::BI__builtin_islessgreater: 144610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek case Builtin::BI__builtin_isunordered: 1454ddb3871307376d27d0f276c9da0ecce0384f01fTed Kremenek if (SemaBuiltinUnorderedCompare(TheCall)) 146eee18c38b6dd29c0e6982f5565fcbc3f76d1bf4dTed Kremenek return ExprError(); 147eee18c38b6dd29c0e6982f5565fcbc3f76d1bf4dTed Kremenek break; 148eee18c38b6dd29c0e6982f5565fcbc3f76d1bf4dTed Kremenek case Builtin::BI__builtin_fpclassify: 149eee18c38b6dd29c0e6982f5565fcbc3f76d1bf4dTed Kremenek if (SemaBuiltinFPClassification(TheCall, 6)) 150eee18c38b6dd29c0e6982f5565fcbc3f76d1bf4dTed Kremenek return ExprError(); 151eee18c38b6dd29c0e6982f5565fcbc3f76d1bf4dTed Kremenek break; 152eee18c38b6dd29c0e6982f5565fcbc3f76d1bf4dTed Kremenek case Builtin::BI__builtin_isfinite: 153da3d76b4cfbb5ebeb79e03a0abeabd403fe9260aBenjamin Kramer case Builtin::BI__builtin_isinf: 15413bd4236ab8297350be388ab442b4c42eb8fe437Ted Kremenek case Builtin::BI__builtin_isinf_sign: 15513bd4236ab8297350be388ab442b4c42eb8fe437Ted Kremenek case Builtin::BI__builtin_isnan: 156558e8872b364b43ab9f201dd6b2df9a5b74b0542Richard Smith case Builtin::BI__builtin_isnormal: 157136f8f24b0b6c0e57aaa4375d280d72dc5492615Ted Kremenek if (SemaBuiltinFPClassification(TheCall, 1)) 1589fcbceed43e5610fdff43defe533934733453ae2Ted Kremenek return ExprError(); 1599fcbceed43e5610fdff43defe533934733453ae2Ted Kremenek break; 1609fcbceed43e5610fdff43defe533934733453ae2Ted Kremenek case Builtin::BI__builtin_shufflevector: 1619fcbceed43e5610fdff43defe533934733453ae2Ted Kremenek return SemaBuiltinShuffleVector(TheCall); 1629fcbceed43e5610fdff43defe533934733453ae2Ted Kremenek // TheCall will be freed by the smart pointer here, but that's fine, since 1639fcbceed43e5610fdff43defe533934733453ae2Ted Kremenek // SemaBuiltinShuffleVector guts it, but then doesn't release it. 1649fcbceed43e5610fdff43defe533934733453ae2Ted Kremenek case Builtin::BI__builtin_prefetch: 1659fcbceed43e5610fdff43defe533934733453ae2Ted Kremenek if (SemaBuiltinPrefetch(TheCall)) 166610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek return ExprError(); 167a9e8b9e3e90fcfe10a04624a89c39b63c32614d1Richard Smith break; 168a9e8b9e3e90fcfe10a04624a89c39b63c32614d1Richard Smith case Builtin::BI__builtin_object_size: 169a9e8b9e3e90fcfe10a04624a89c39b63c32614d1Richard Smith if (SemaBuiltinObjectSize(TheCall)) 170a9e8b9e3e90fcfe10a04624a89c39b63c32614d1Richard Smith return ExprError(); 171a9e8b9e3e90fcfe10a04624a89c39b63c32614d1Richard Smith break; 172c5f740ecdbc21d5ba08f97b89cc05c9d4f230fdaTed Kremenek case Builtin::BI__builtin_longjmp: 173c5f740ecdbc21d5ba08f97b89cc05c9d4f230fdaTed Kremenek if (SemaBuiltinLongjmp(TheCall)) 174c5f740ecdbc21d5ba08f97b89cc05c9d4f230fdaTed Kremenek return ExprError(); 175c5f740ecdbc21d5ba08f97b89cc05c9d4f230fdaTed Kremenek break; 176c5f740ecdbc21d5ba08f97b89cc05c9d4f230fdaTed Kremenek 177c5f740ecdbc21d5ba08f97b89cc05c9d4f230fdaTed Kremenek case Builtin::BI__builtin_classify_type: 178c5f740ecdbc21d5ba08f97b89cc05c9d4f230fdaTed Kremenek if (checkArgCount(*this, TheCall, 1)) return true; 179c5f740ecdbc21d5ba08f97b89cc05c9d4f230fdaTed Kremenek TheCall->setType(Context.IntTy); 180136f8f24b0b6c0e57aaa4375d280d72dc5492615Ted Kremenek break; 181eee18c38b6dd29c0e6982f5565fcbc3f76d1bf4dTed Kremenek case Builtin::BI__builtin_constant_p: 182610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek if (checkArgCount(*this, TheCall, 1)) return true; 183610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek TheCall->setType(Context.IntTy); 184610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek break; 185558e8872b364b43ab9f201dd6b2df9a5b74b0542Richard Smith case Builtin::BI__sync_fetch_and_add: 1869fcbceed43e5610fdff43defe533934733453ae2Ted Kremenek case Builtin::BI__sync_fetch_and_add_1: 1879fcbceed43e5610fdff43defe533934733453ae2Ted Kremenek case Builtin::BI__sync_fetch_and_add_2: 18813bd4236ab8297350be388ab442b4c42eb8fe437Ted Kremenek case Builtin::BI__sync_fetch_and_add_4: 18913bd4236ab8297350be388ab442b4c42eb8fe437Ted Kremenek case Builtin::BI__sync_fetch_and_add_8: 19013bd4236ab8297350be388ab442b4c42eb8fe437Ted Kremenek case Builtin::BI__sync_fetch_and_add_16: 191610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek case Builtin::BI__sync_fetch_and_sub: 192610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek case Builtin::BI__sync_fetch_and_sub_1: 193610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek case Builtin::BI__sync_fetch_and_sub_2: 194610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek case Builtin::BI__sync_fetch_and_sub_4: 195136f8f24b0b6c0e57aaa4375d280d72dc5492615Ted Kremenek case Builtin::BI__sync_fetch_and_sub_8: 196dc84cd5efdd3430efb22546b4ac656aa0540b210David Blaikie case Builtin::BI__sync_fetch_and_sub_16: 197610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek case Builtin::BI__sync_fetch_and_or: 198610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek case Builtin::BI__sync_fetch_and_or_1: 199610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek case Builtin::BI__sync_fetch_and_or_2: 200610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek case Builtin::BI__sync_fetch_and_or_4: 201610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek case Builtin::BI__sync_fetch_and_or_8: 202610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek case Builtin::BI__sync_fetch_and_or_16: 203610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek case Builtin::BI__sync_fetch_and_and: 204610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek case Builtin::BI__sync_fetch_and_and_1: 205610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek case Builtin::BI__sync_fetch_and_and_2: 206610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek case Builtin::BI__sync_fetch_and_and_4: 207c1602581f7a4eab486489f09647d724ce35d3f23Ted Kremenek case Builtin::BI__sync_fetch_and_and_8: 2085f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner case Builtin::BI__sync_fetch_and_and_16: 209496398d523de712ac1084c53a397ca3987fe43dbTed Kremenek case Builtin::BI__sync_fetch_and_xor: 210610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek case Builtin::BI__sync_fetch_and_xor_1: 211c1602581f7a4eab486489f09647d724ce35d3f23Ted Kremenek case Builtin::BI__sync_fetch_and_xor_2: 212c1602581f7a4eab486489f09647d724ce35d3f23Ted Kremenek case Builtin::BI__sync_fetch_and_xor_4: 213c1602581f7a4eab486489f09647d724ce35d3f23Ted Kremenek case Builtin::BI__sync_fetch_and_xor_8: 214c1602581f7a4eab486489f09647d724ce35d3f23Ted Kremenek case Builtin::BI__sync_fetch_and_xor_16: 215c1602581f7a4eab486489f09647d724ce35d3f23Ted Kremenek case Builtin::BI__sync_add_and_fetch: 216c1602581f7a4eab486489f09647d724ce35d3f23Ted Kremenek case Builtin::BI__sync_add_and_fetch_1: 217c1602581f7a4eab486489f09647d724ce35d3f23Ted Kremenek case Builtin::BI__sync_add_and_fetch_2: 218c1602581f7a4eab486489f09647d724ce35d3f23Ted Kremenek case Builtin::BI__sync_add_and_fetch_4: 219c1602581f7a4eab486489f09647d724ce35d3f23Ted Kremenek case Builtin::BI__sync_add_and_fetch_8: 220c1602581f7a4eab486489f09647d724ce35d3f23Ted Kremenek case Builtin::BI__sync_add_and_fetch_16: 221610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek case Builtin::BI__sync_sub_and_fetch: 222610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek case Builtin::BI__sync_sub_and_fetch_1: 223610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek case Builtin::BI__sync_sub_and_fetch_2: 224610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek case Builtin::BI__sync_sub_and_fetch_4: 225610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek case Builtin::BI__sync_sub_and_fetch_8: 226610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek case Builtin::BI__sync_sub_and_fetch_16: 227610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek case Builtin::BI__sync_and_and_fetch: 228610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek case Builtin::BI__sync_and_and_fetch_1: 229610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek case Builtin::BI__sync_and_and_fetch_2: 2308052050c8ebfcfbbce8afed57fefc8c95fb9a333Chandler Carruth case Builtin::BI__sync_and_and_fetch_4: 2318052050c8ebfcfbbce8afed57fefc8c95fb9a333Chandler Carruth case Builtin::BI__sync_and_and_fetch_8: 2328052050c8ebfcfbbce8afed57fefc8c95fb9a333Chandler Carruth case Builtin::BI__sync_and_and_fetch_16: 2338052050c8ebfcfbbce8afed57fefc8c95fb9a333Chandler Carruth case Builtin::BI__sync_or_and_fetch: 2348052050c8ebfcfbbce8afed57fefc8c95fb9a333Chandler Carruth case Builtin::BI__sync_or_and_fetch_1: 235610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek case Builtin::BI__sync_or_and_fetch_2: 236610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek case Builtin::BI__sync_or_and_fetch_4: 237610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek case Builtin::BI__sync_or_and_fetch_8: 238610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek case Builtin::BI__sync_or_and_fetch_16: 2396bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines case Builtin::BI__sync_xor_and_fetch: 240c1602581f7a4eab486489f09647d724ce35d3f23Ted Kremenek case Builtin::BI__sync_xor_and_fetch_1: 241c1602581f7a4eab486489f09647d724ce35d3f23Ted Kremenek case Builtin::BI__sync_xor_and_fetch_2: 242c1602581f7a4eab486489f09647d724ce35d3f23Ted Kremenek case Builtin::BI__sync_xor_and_fetch_4: 243344472ebeded2fca2ed5013b9e87f81d09bfa908Robert Wilhelm case Builtin::BI__sync_xor_and_fetch_8: 244344472ebeded2fca2ed5013b9e87f81d09bfa908Robert Wilhelm case Builtin::BI__sync_xor_and_fetch_16: 245344472ebeded2fca2ed5013b9e87f81d09bfa908Robert Wilhelm case Builtin::BI__sync_val_compare_and_swap: 246c1602581f7a4eab486489f09647d724ce35d3f23Ted Kremenek case Builtin::BI__sync_val_compare_and_swap_1: 247c1602581f7a4eab486489f09647d724ce35d3f23Ted Kremenek case Builtin::BI__sync_val_compare_and_swap_2: 248c1602581f7a4eab486489f09647d724ce35d3f23Ted Kremenek case Builtin::BI__sync_val_compare_and_swap_4: 249c1602581f7a4eab486489f09647d724ce35d3f23Ted Kremenek case Builtin::BI__sync_val_compare_and_swap_8: 250c1602581f7a4eab486489f09647d724ce35d3f23Ted Kremenek case Builtin::BI__sync_val_compare_and_swap_16: 251c1602581f7a4eab486489f09647d724ce35d3f23Ted Kremenek case Builtin::BI__sync_bool_compare_and_swap: 252c1602581f7a4eab486489f09647d724ce35d3f23Ted Kremenek case Builtin::BI__sync_bool_compare_and_swap_1: 2536bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines case Builtin::BI__sync_bool_compare_and_swap_2: 254c1602581f7a4eab486489f09647d724ce35d3f23Ted Kremenek case Builtin::BI__sync_bool_compare_and_swap_4: 255c1602581f7a4eab486489f09647d724ce35d3f23Ted Kremenek case Builtin::BI__sync_bool_compare_and_swap_8: 256c1602581f7a4eab486489f09647d724ce35d3f23Ted Kremenek case Builtin::BI__sync_bool_compare_and_swap_16: 257c1602581f7a4eab486489f09647d724ce35d3f23Ted Kremenek case Builtin::BI__sync_lock_test_and_set: 258c1602581f7a4eab486489f09647d724ce35d3f23Ted Kremenek case Builtin::BI__sync_lock_test_and_set_1: 259610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek case Builtin::BI__sync_lock_test_and_set_2: 260610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek case Builtin::BI__sync_lock_test_and_set_4: 261610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek case Builtin::BI__sync_lock_test_and_set_8: 2629532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith case Builtin::BI__sync_lock_test_and_set_16: 263610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek case Builtin::BI__sync_lock_release: 264610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek case Builtin::BI__sync_lock_release_1: 265610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek case Builtin::BI__sync_lock_release_2: 266610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek case Builtin::BI__sync_lock_release_4: 267610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek case Builtin::BI__sync_lock_release_8: 268610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek case Builtin::BI__sync_lock_release_16: 269610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek case Builtin::BI__sync_swap: 2709532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith case Builtin::BI__sync_swap_1: 2719532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith case Builtin::BI__sync_swap_2: 272610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek case Builtin::BI__sync_swap_4: 273610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek case Builtin::BI__sync_swap_8: 274610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek case Builtin::BI__sync_swap_16: 2759532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith return SemaBuiltinAtomicOverloaded(move(TheCallResult)); 2769532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith case Builtin::BI__atomic_load: 2779532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Load); 2789532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith case Builtin::BI__atomic_store: 2799532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Store); 2809532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith case Builtin::BI__atomic_exchange: 2819532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Xchg); 2829532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith case Builtin::BI__atomic_compare_exchange_strong: 2839532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith return SemaAtomicOpsOverloaded(move(TheCallResult), 2849532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith AtomicExpr::CmpXchgStrong); 2859532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith case Builtin::BI__atomic_compare_exchange_weak: 2869532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith return SemaAtomicOpsOverloaded(move(TheCallResult), 2879532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith AtomicExpr::CmpXchgWeak); 2889532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith case Builtin::BI__atomic_fetch_add: 2899532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Add); 2909532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith case Builtin::BI__atomic_fetch_sub: 2919532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Sub); 2929532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith case Builtin::BI__atomic_fetch_and: 2939532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::And); 2949532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith case Builtin::BI__atomic_fetch_or: 2959532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Or); 2969532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith case Builtin::BI__atomic_fetch_xor: 2979532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Xor); 2986bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines case Builtin::BI__builtin_annotation: 2999532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith if (CheckBuiltinAnnotationString(*this, TheCall->getArg(1))) 3009532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith return ExprError(); 3019532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith break; 3029532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith } 3039532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith 3049532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith // Since the target specific builtins for each arch overlap, only check those 3059532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith // of the arch we are compiling for. 3069532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith if (BuiltinID >= Builtin::FirstTSBuiltin) { 3079532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith switch (Context.getTargetInfo().getTriple().getArch()) { 3089532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith case llvm::Triple::arm: 3099532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith case llvm::Triple::thumb: 3109532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall)) 3119532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith return ExprError(); 3129532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith break; 3139532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith default: 3149532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith break; 3159532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith } 3169532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith } 3179532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith 3189532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith return move(TheCallResult); 3199532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith} 3209532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith 3219532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith// Get the valid immediate range for the specified NEON type code. 3229532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smithstatic unsigned RFT(unsigned t, bool shift = false) { 3239532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith NeonTypeFlags Type(t); 3249532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith int IsQuad = Type.isQuad(); 3259532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith switch (Type.getEltType()) { 3269532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith case NeonTypeFlags::Int8: 3279532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith case NeonTypeFlags::Poly8: 3289532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith return shift ? 7 : (8 << IsQuad) - 1; 3299532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith case NeonTypeFlags::Int16: 3309532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith case NeonTypeFlags::Poly16: 3319532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith return shift ? 15 : (4 << IsQuad) - 1; 3329532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith case NeonTypeFlags::Int32: 3339532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith return shift ? 31 : (2 << IsQuad) - 1; 3349532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith case NeonTypeFlags::Int64: 3359532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith return shift ? 63 : (1 << IsQuad) - 1; 3369532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith case NeonTypeFlags::Float16: 3379532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith assert(!shift && "cannot shift float types!"); 3389532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith return (4 << IsQuad) - 1; 3399532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith case NeonTypeFlags::Float32: 3409532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith assert(!shift && "cannot shift float types!"); 3419532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith return (2 << IsQuad) - 1; 3429532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith } 3439532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith return 0; 3449532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith} 3459532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith 3469532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith/// getNeonEltType - Return the QualType corresponding to the elements of 3479532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith/// the vector type specified by the NeonTypeFlags. This is used to check 3489532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith/// the pointer arguments for Neon load/store intrinsics. 3499532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smithstatic QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context) { 3509532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith switch (Flags.getEltType()) { 3519532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith case NeonTypeFlags::Int8: 3529532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 3539532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith case NeonTypeFlags::Int16: 3549532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 3559532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith case NeonTypeFlags::Int32: 3566bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 3579532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith case NeonTypeFlags::Int64: 3589532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith return Flags.isUnsigned() ? Context.UnsignedLongLongTy : Context.LongLongTy; 3599532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith case NeonTypeFlags::Poly8: 36077fd3c0d7837040bb84c1617a6a423f833e784feTed Kremenek return Context.SignedCharTy; 36177fd3c0d7837040bb84c1617a6a423f833e784feTed Kremenek case NeonTypeFlags::Poly16: 36277fd3c0d7837040bb84c1617a6a423f833e784feTed Kremenek return Context.ShortTy; 36377fd3c0d7837040bb84c1617a6a423f833e784feTed Kremenek case NeonTypeFlags::Float16: 36477fd3c0d7837040bb84c1617a6a423f833e784feTed Kremenek return Context.UnsignedShortTy; 36577fd3c0d7837040bb84c1617a6a423f833e784feTed Kremenek case NeonTypeFlags::Float32: 36677fd3c0d7837040bb84c1617a6a423f833e784feTed Kremenek return Context.FloatTy; 36777fd3c0d7837040bb84c1617a6a423f833e784feTed Kremenek } 36877fd3c0d7837040bb84c1617a6a423f833e784feTed Kremenek return QualType(); 36977fd3c0d7837040bb84c1617a6a423f833e784feTed Kremenek} 3709532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith 3719532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smithbool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 3729532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith llvm::APSInt Result; 3739532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith 3749532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith unsigned mask = 0; 3759532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith unsigned TV = 0; 376651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines int PtrArgNum = -1; 377651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines bool HasConstPtr = false; 3789532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith switch (BuiltinID) { 3799532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith#define GET_NEON_OVERLOAD_CHECK 3809532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith#include "clang/Basic/arm_neon.inc" 3819532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith#undef GET_NEON_OVERLOAD_CHECK 3829532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith } 3839532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith 3849532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith // For NEON intrinsics which are overloaded on vector element type, validate 3859532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith // the immediate which specifies which variant to emit. 3869532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith unsigned ImmArg = TheCall->getNumArgs()-1; 3879532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith if (mask) { 3889532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 3899532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith return true; 3906cfa78f6bd4e7d5e23366a0907f8f8792366bc4cRichard Smith 3916cfa78f6bd4e7d5e23366a0907f8f8792366bc4cRichard Smith TV = Result.getLimitedValue(64); 3926cfa78f6bd4e7d5e23366a0907f8f8792366bc4cRichard Smith if ((TV > 63) || (mask & (1 << TV)) == 0) 3939532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code) 3949532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith << TheCall->getArg(ImmArg)->getSourceRange(); 3959532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith } 3969532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith 3979532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith if (PtrArgNum >= 0) { 3989532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith // Check that pointer arguments have the specified type. 3999532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith Expr *Arg = TheCall->getArg(PtrArgNum); 4009532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 4019532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith Arg = ICE->getSubExpr(); 4029532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 4039532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith QualType RHSTy = RHS.get()->getType(); 4049532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context); 4059532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith if (HasConstPtr) 4069532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith EltTy = EltTy.withConst(); 4079532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith QualType LHSTy = Context.getPointerType(EltTy); 4089532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith AssignConvertType ConvTy; 4099532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 4109532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith if (RHS.isInvalid()) 4119532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith return true; 4129532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy, 4139532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith RHS.get(), AA_Assigning)) 4149532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith return true; 4159532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith } 4169532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith 4179532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith // For NEON intrinsics which take an immediate value as part of the 4189532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith // instruction, range check them here. 4199532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith unsigned i = 0, l = 0, u = 0; 4209532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith switch (BuiltinID) { 4219532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith default: return false; 4229532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break; 4239532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith case ARM::BI__builtin_arm_usat: i = 1; u = 31; break; 4249532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith case ARM::BI__builtin_arm_vcvtr_f: 4259532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break; 4269532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith#define GET_NEON_IMMEDIATE_CHECK 4279532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith#include "clang/Basic/arm_neon.inc" 4289532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith#undef GET_NEON_IMMEDIATE_CHECK 4299532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith }; 4309532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith 4310c8e5a0f70cbdb800d939c1807d05f380b2854d4Ted Kremenek // Check that the immediate argument is actually a constant. 432610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek if (SemaBuiltinConstantArg(TheCall, i, Result)) 433610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek return true; 4342815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith 4351d26f48dc2eea1c07431ca1519d7034a21b9bcffTed Kremenek // Range check against the upper/lower values for this isntruction. 4369532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith unsigned Val = Result.getZExtValue(); 43725c1d57fc906e895535fb5c7e6dde80219f353b5Ted Kremenek if (Val < l || Val > (u + l)) 438eba76a4379997f66f8114eb7e63206a5932b1be8Ted Kremenek return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 4399532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith << l << u+l << TheCall->getArg(i)->getSourceRange(); 440610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek 441610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek // FIXME: VFP Intrinsics should error if VFP not present. 4422815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith return false; 4439532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith} 444eba76a4379997f66f8114eb7e63206a5932b1be8Ted Kremenek 4459532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith/// CheckFunctionCall - Check a direct function call for various correctness 44625c1d57fc906e895535fb5c7e6dde80219f353b5Ted Kremenek/// and safety properties not strictly enforced by the C type system. 44725c1d57fc906e895535fb5c7e6dde80219f353b5Ted Kremenekbool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) { 4489532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith // Get the IdentifierInfo* for the called function. 449818918855d84e3db1af5a0807070d4995ca2cf75Richard Smith IdentifierInfo *FnInfo = FDecl->getIdentifier(); 450a8c17a5babab35f2db26bf218e7571d1af4afedfTed Kremenek 45125c1d57fc906e895535fb5c7e6dde80219f353b5Ted Kremenek // None of the checks below are needed for functions that don't have 452a8c17a5babab35f2db26bf218e7571d1af4afedfTed Kremenek // simple names (e.g., C++ conversion functions). 453a9e8b9e3e90fcfe10a04624a89c39b63c32614d1Richard Smith if (!FnInfo) 454c21fed361c11f13db345cba69101578578d8fb79Ted Kremenek return false; 45525c1d57fc906e895535fb5c7e6dde80219f353b5Ted Kremenek 45625c1d57fc906e895535fb5c7e6dde80219f353b5Ted Kremenek // FIXME: This mechanism should be abstracted to be less fragile and 45725c1d57fc906e895535fb5c7e6dde80219f353b5Ted Kremenek // more efficient. For example, just map function ids to custom 4582815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith // handlers. 45940900ee8f3072d05456134b57c0fad85a6bb21a6Ted Kremenek 46040900ee8f3072d05456134b57c0fad85a6bb21a6Ted Kremenek // Printf and scanf checking. 46140900ee8f3072d05456134b57c0fad85a6bb21a6Ted Kremenek for (specific_attr_iterator<FormatAttr> 4622815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith i = FDecl->specific_attr_begin<FormatAttr>(), 4639532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith e = FDecl->specific_attr_end<FormatAttr>(); i != e ; ++i) { 4649532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith 4659532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith const FormatAttr *Format = *i; 4669532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith const bool b = Format->getType() == "scanf"; 4672815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith if (b || CheckablePrintfAttr(Format, TheCall)) { 4682815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith bool HasVAListArg = Format->getFirstArg() == 0; 4692815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith CheckPrintfScanfArguments(TheCall, HasVAListArg, 4702815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith Format->getFormatIdx() - 1, 4712815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith HasVAListArg ? 0 : Format->getFirstArg() - 1, 4722815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith !b); 4732815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith } 4742815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith } 4752815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith 4762815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith for (specific_attr_iterator<NonNullAttr> 4772815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith i = FDecl->specific_attr_begin<NonNullAttr>(), 4782815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith e = FDecl->specific_attr_end<NonNullAttr>(); i != e; ++i) { 4792815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith CheckNonNullArguments(*i, TheCall->getArgs(), 4802815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith TheCall->getCallee()->getLocStart()); 4812815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith } 4822815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith 4832815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith // Builtin handling 4842815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith int CMF = -1; 4852815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith switch (FDecl->getBuiltinID()) { 4862815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith case Builtin::BI__builtin_memset: 4872815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith case Builtin::BI__builtin___memset_chk: 4882815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith case Builtin::BImemset: 4892815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith CMF = CMF_Memset; 4902815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith break; 4912815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith 4922815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith case Builtin::BI__builtin_memcpy: 4932815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith case Builtin::BI__builtin___memcpy_chk: 4942815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith case Builtin::BImemcpy: 4952815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith CMF = CMF_Memcpy; 4962815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith break; 4972815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith 4982815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith case Builtin::BI__builtin_memmove: 4992815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith case Builtin::BI__builtin___memmove_chk: 5002815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith case Builtin::BImemmove: 5012815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith CMF = CMF_Memmove; 5022815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith break; 5032815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith 5042815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith case Builtin::BIstrlcpy: 5052815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith case Builtin::BIstrlcat: 5062815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith CheckStrlcpycatArguments(TheCall, FnInfo); 5072815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith break; 5082815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith 5092815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith case Builtin::BI__builtin_memcmp: 5102815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith CMF = CMF_Memcmp; 5112815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith break; 5122815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith 5132815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith case Builtin::BI__builtin_strncpy: 5142815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith case Builtin::BI__builtin___strncpy_chk: 5152815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith case Builtin::BIstrncpy: 5162815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith CMF = CMF_Strncpy; 5172815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith break; 5182815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith 5192815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith case Builtin::BI__builtin_strncmp: 520cfa88f893915ceb8ae4ce2f17c46c24a4d67502fDmitri Gribenko CMF = CMF_Strncmp; 521cfa88f893915ceb8ae4ce2f17c46c24a4d67502fDmitri Gribenko break; 5222815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith 5232815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith case Builtin::BI__builtin_strncasecmp: 5242815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith CMF = CMF_Strncasecmp; 5252815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith break; 5262815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith 5272815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith case Builtin::BI__builtin_strncat: 528344472ebeded2fca2ed5013b9e87f81d09bfa908Robert Wilhelm case Builtin::BIstrncat: 5298a1fdfc69cc6c2ccbfd57fc8ff643c589da9df9bRichard Smith CMF = CMF_Strncat; 5308a1fdfc69cc6c2ccbfd57fc8ff643c589da9df9bRichard Smith break; 5318a1fdfc69cc6c2ccbfd57fc8ff643c589da9df9bRichard Smith 5328a1fdfc69cc6c2ccbfd57fc8ff643c589da9df9bRichard Smith case Builtin::BI__builtin_strndup: 5338a1fdfc69cc6c2ccbfd57fc8ff643c589da9df9bRichard Smith case Builtin::BIstrndup: 5342815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith CMF = CMF_Strndup; 5352815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith break; 5362815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith 537651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines default: 538651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines if (FDecl->getLinkage() == ExternalLinkage && 539651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines (!getLangOptions().CPlusPlus || FDecl->isExternC())) { 5408a1fdfc69cc6c2ccbfd57fc8ff643c589da9df9bRichard Smith if (FnInfo->isStr("memset")) 5418a1fdfc69cc6c2ccbfd57fc8ff643c589da9df9bRichard Smith CMF = CMF_Memset; 5422815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith else if (FnInfo->isStr("memcpy")) 5432815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith CMF = CMF_Memcpy; 5448a1fdfc69cc6c2ccbfd57fc8ff643c589da9df9bRichard Smith else if (FnInfo->isStr("memmove")) 5456bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines CMF = CMF_Memmove; 5468a1fdfc69cc6c2ccbfd57fc8ff643c589da9df9bRichard Smith else if (FnInfo->isStr("memcmp")) 5478a1fdfc69cc6c2ccbfd57fc8ff643c589da9df9bRichard Smith CMF = CMF_Memcmp; 5488a1fdfc69cc6c2ccbfd57fc8ff643c589da9df9bRichard Smith else if (FnInfo->isStr("strncpy")) 5498a1fdfc69cc6c2ccbfd57fc8ff643c589da9df9bRichard Smith CMF = CMF_Strncpy; 5508a1fdfc69cc6c2ccbfd57fc8ff643c589da9df9bRichard Smith else if (FnInfo->isStr("strncmp")) 5518a1fdfc69cc6c2ccbfd57fc8ff643c589da9df9bRichard Smith CMF = CMF_Strncmp; 5528a1fdfc69cc6c2ccbfd57fc8ff643c589da9df9bRichard Smith else if (FnInfo->isStr("strncasecmp")) 5538a1fdfc69cc6c2ccbfd57fc8ff643c589da9df9bRichard Smith CMF = CMF_Strncasecmp; 5542815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith else if (FnInfo->isStr("strncat")) 555558e8872b364b43ab9f201dd6b2df9a5b74b0542Richard Smith CMF = CMF_Strncat; 556558e8872b364b43ab9f201dd6b2df9a5b74b0542Richard Smith else if (FnInfo->isStr("strndup")) 557558e8872b364b43ab9f201dd6b2df9a5b74b0542Richard Smith CMF = CMF_Strndup; 558558e8872b364b43ab9f201dd6b2df9a5b74b0542Richard Smith } 559558e8872b364b43ab9f201dd6b2df9a5b74b0542Richard Smith break; 560558e8872b364b43ab9f201dd6b2df9a5b74b0542Richard Smith } 561558e8872b364b43ab9f201dd6b2df9a5b74b0542Richard Smith 562558e8872b364b43ab9f201dd6b2df9a5b74b0542Richard Smith // Memset/memcpy/memmove handling 563558e8872b364b43ab9f201dd6b2df9a5b74b0542Richard Smith if (CMF != -1) 564558e8872b364b43ab9f201dd6b2df9a5b74b0542Richard Smith CheckMemaccessArguments(TheCall, CheckedMemoryFunction(CMF), FnInfo); 565558e8872b364b43ab9f201dd6b2df9a5b74b0542Richard Smith 566558e8872b364b43ab9f201dd6b2df9a5b74b0542Richard Smith return false; 5672815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith} 5682815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith 5692815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smithbool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) { 5702815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith // Printf checking. 5712815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith const FormatAttr *Format = NDecl->getAttr<FormatAttr>(); 5722815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith if (!Format) 5732815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith return false; 5742815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith 5752815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith const VarDecl *V = dyn_cast<VarDecl>(NDecl); 5762815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith if (!V) 5772815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith return false; 5782815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith 5792815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith QualType Ty = V->getType(); 5802815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith if (!Ty->isBlockPointerType()) 5812815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith return false; 5822815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith 5832815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith const bool b = Format->getType() == "scanf"; 5842815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith if (!b && !CheckablePrintfAttr(Format, TheCall)) 5852815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith return false; 5862815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith 5872815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith bool HasVAListArg = Format->getFirstArg() == 0; 5882815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith CheckPrintfScanfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1, 5892815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith HasVAListArg ? 0 : Format->getFirstArg() - 1, !b); 5902815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith 5912815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith return false; 5922815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith} 5932815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith 5942815e1a075c74143a0b60a632090ece1dffa5c7cRichard SmithExprResult 5952815e1a075c74143a0b60a632090ece1dffa5c7cRichard SmithSema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, AtomicExpr::AtomicOp Op) { 5962815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 5972815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 5982815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith 5992815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith // All these operations take one of the following four forms: 6002815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith // T __atomic_load(_Atomic(T)*, int) (loads) 6012815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith // T* __atomic_add(_Atomic(T*)*, ptrdiff_t, int) (pointer add/sub) 6022815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith // int __atomic_compare_exchange_strong(_Atomic(T)*, T*, T, int, int) 6032815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith // (cmpxchg) 6042815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith // T __atomic_exchange(_Atomic(T)*, T, int) (everything else) 6052815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith // where T is an appropriate type, and the int paremeterss are for orderings. 6062815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith unsigned NumVals = 1; 6072815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith unsigned NumOrders = 1; 6082815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith if (Op == AtomicExpr::Load) { 6092815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith NumVals = 0; 6102815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith } else if (Op == AtomicExpr::CmpXchgWeak || Op == AtomicExpr::CmpXchgStrong) { 6112815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith NumVals = 2; 6122815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith NumOrders = 2; 6132815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith } 6142815e1a075c74143a0b60a632090ece1dffa5c7cRichard Smith 615610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek if (TheCall->getNumArgs() < NumVals+NumOrders+1) { 616610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 617610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek << 0 << NumVals+NumOrders+1 << TheCall->getNumArgs() 618818918855d84e3db1af5a0807070d4995ca2cf75Richard Smith << TheCall->getCallee()->getSourceRange(); 619818918855d84e3db1af5a0807070d4995ca2cf75Richard Smith return ExprError(); 620818918855d84e3db1af5a0807070d4995ca2cf75Richard Smith } else if (TheCall->getNumArgs() > NumVals+NumOrders+1) { 621eba76a4379997f66f8114eb7e63206a5932b1be8Ted Kremenek Diag(TheCall->getArg(NumVals+NumOrders+1)->getLocStart(), 622610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek diag::err_typecheck_call_too_many_args) 623610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek << 0 << NumVals+NumOrders+1 << TheCall->getNumArgs() 6249532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith << TheCall->getCallee()->getSourceRange(); 6251ea800c4ca76d5bb41aa8a1e0a6c7628b9fff28dTed Kremenek return ExprError(); 6269532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith } 6279532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith 6289532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith // Inspect the first argument of the atomic operation. This should always be 6299532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith // a pointer to an _Atomic type. 6301ea800c4ca76d5bb41aa8a1e0a6c7628b9fff28dTed Kremenek Expr *Ptr = TheCall->getArg(0); 6311ea800c4ca76d5bb41aa8a1e0a6c7628b9fff28dTed Kremenek Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get(); 6321ea800c4ca76d5bb41aa8a1e0a6c7628b9fff28dTed Kremenek const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 633a8c17a5babab35f2db26bf218e7571d1af4afedfTed Kremenek if (!pointerType) { 634bc8b44c4ee7f9c4c3ad296369e72feda61bdb580Ted Kremenek Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic) 635651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines << Ptr->getType() << Ptr->getSourceRange(); 636651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines return ExprError(); 637bc8b44c4ee7f9c4c3ad296369e72feda61bdb580Ted Kremenek } 638bc8b44c4ee7f9c4c3ad296369e72feda61bdb580Ted Kremenek 639651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines QualType AtomTy = pointerType->getPointeeType(); 640bc8b44c4ee7f9c4c3ad296369e72feda61bdb580Ted Kremenek if (!AtomTy->isAtomicType()) { 641bc8b44c4ee7f9c4c3ad296369e72feda61bdb580Ted Kremenek Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic) 642bc8b44c4ee7f9c4c3ad296369e72feda61bdb580Ted Kremenek << Ptr->getType() << Ptr->getSourceRange(); 643818918855d84e3db1af5a0807070d4995ca2cf75Richard Smith return ExprError(); 644a8c17a5babab35f2db26bf218e7571d1af4afedfTed Kremenek } 645a8c17a5babab35f2db26bf218e7571d1af4afedfTed Kremenek QualType ValType = AtomTy->getAs<AtomicType>()->getValueType(); 646a8c17a5babab35f2db26bf218e7571d1af4afedfTed Kremenek 647a9e8b9e3e90fcfe10a04624a89c39b63c32614d1Richard Smith if ((Op == AtomicExpr::Add || Op == AtomicExpr::Sub) && 64844ca53f34deb5efe9fc6f246781f66f1ed83eabcTed Kremenek !ValType->isIntegerType() && !ValType->isPointerType()) { 64944ca53f34deb5efe9fc6f246781f66f1ed83eabcTed Kremenek Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr) 65044ca53f34deb5efe9fc6f246781f66f1ed83eabcTed Kremenek << Ptr->getType() << Ptr->getSourceRange(); 65144ca53f34deb5efe9fc6f246781f66f1ed83eabcTed Kremenek return ExprError(); 65244ca53f34deb5efe9fc6f246781f66f1ed83eabcTed Kremenek } 65344ca53f34deb5efe9fc6f246781f66f1ed83eabcTed Kremenek 65444ca53f34deb5efe9fc6f246781f66f1ed83eabcTed Kremenek if (!ValType->isIntegerType() && 65544ca53f34deb5efe9fc6f246781f66f1ed83eabcTed Kremenek (Op == AtomicExpr::And || Op == AtomicExpr::Or || Op == AtomicExpr::Xor)){ 65644ca53f34deb5efe9fc6f246781f66f1ed83eabcTed Kremenek Diag(DRE->getLocStart(), diag::err_atomic_op_logical_needs_atomic_int) 65744ca53f34deb5efe9fc6f246781f66f1ed83eabcTed Kremenek << Ptr->getType() << Ptr->getSourceRange(); 65844ca53f34deb5efe9fc6f246781f66f1ed83eabcTed Kremenek return ExprError(); 65944ca53f34deb5efe9fc6f246781f66f1ed83eabcTed Kremenek } 66044ca53f34deb5efe9fc6f246781f66f1ed83eabcTed Kremenek 66144ca53f34deb5efe9fc6f246781f66f1ed83eabcTed Kremenek switch (ValType.getObjCLifetime()) { 66244ca53f34deb5efe9fc6f246781f66f1ed83eabcTed Kremenek case Qualifiers::OCL_None: 66344ca53f34deb5efe9fc6f246781f66f1ed83eabcTed Kremenek case Qualifiers::OCL_ExplicitNone: 66444ca53f34deb5efe9fc6f246781f66f1ed83eabcTed Kremenek // okay 66544ca53f34deb5efe9fc6f246781f66f1ed83eabcTed Kremenek break; 66644ca53f34deb5efe9fc6f246781f66f1ed83eabcTed Kremenek 66744ca53f34deb5efe9fc6f246781f66f1ed83eabcTed Kremenek case Qualifiers::OCL_Weak: 668a9e8b9e3e90fcfe10a04624a89c39b63c32614d1Richard Smith case Qualifiers::OCL_Strong: 669a9e8b9e3e90fcfe10a04624a89c39b63c32614d1Richard Smith case Qualifiers::OCL_Autoreleasing: 6700c8e5a0f70cbdb800d939c1807d05f380b2854d4Ted Kremenek Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 6719532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith << ValType << Ptr->getSourceRange(); 6729532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith return ExprError(); 6739532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith } 6749532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith 6759532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith QualType ResultType = ValType; 6769532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith if (Op == AtomicExpr::Store) 6779532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith ResultType = Context.VoidTy; 6789532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith else if (Op == AtomicExpr::CmpXchgWeak || Op == AtomicExpr::CmpXchgStrong) 6799532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith ResultType = Context.BoolTy; 6809532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith 681eba76a4379997f66f8114eb7e63206a5932b1be8Ted Kremenek // The first argument --- the pointer --- has a fixed type; we 6829532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith // deduce the types of the rest of the arguments accordingly. Walk 683610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek // the remaining arguments, converting them to the deduced value type. 684610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek for (unsigned i = 1; i != NumVals+NumOrders+1; ++i) { 685610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek ExprResult Arg = TheCall->getArg(i); 6869532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith QualType Ty; 6879532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith if (i < NumVals+1) { 6889532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith // The second argument to a cmpxchg is a pointer to the data which will 6899532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith // be exchanged. The second argument to a pointer add/subtract is the 6909532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith // amount to add/subtract, which must be a ptrdiff_t. The third 691610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek // argument to a cmpxchg and the second argument in all other cases 692610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek // is the type of the value. 693610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek if (i == 1 && (Op == AtomicExpr::CmpXchgWeak || 6949532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith Op == AtomicExpr::CmpXchgStrong)) 695651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines Ty = Context.getPointerType(ValType.getUnqualifiedType()); 696651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines else if (!ValType->isIntegerType() && 6979532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith (Op == AtomicExpr::Add || Op == AtomicExpr::Sub)) 6989532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith Ty = Context.getPointerDiffType(); 6999532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith else 7009532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith Ty = ValType; 7019532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith } else { 7029532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith // The order(s) are always converted to int. 7039532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith Ty = Context.IntTy; 7049532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith } 7059532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith InitializedEntity Entity = 7069532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith InitializedEntity::InitializeParameter(Context, Ty, false); 7079532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 7089532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith if (Arg.isInvalid()) 7099532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith return true; 7109532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith TheCall->setArg(i, Arg.get()); 7119532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith } 7129532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith 7139532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith SmallVector<Expr*, 5> SubExprs; 7149532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith SubExprs.push_back(Ptr); 7159532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith if (Op == AtomicExpr::Load) { 7169532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith SubExprs.push_back(TheCall->getArg(1)); // Order 7179532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith } else if (Op != AtomicExpr::CmpXchgWeak && Op != AtomicExpr::CmpXchgStrong) { 7189532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith SubExprs.push_back(TheCall->getArg(2)); // Order 7199532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith SubExprs.push_back(TheCall->getArg(1)); // Val1 7209532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith } else { 7219532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith SubExprs.push_back(TheCall->getArg(3)); // Order 7229532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith SubExprs.push_back(TheCall->getArg(1)); // Val1 7239532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith SubExprs.push_back(TheCall->getArg(2)); // Val2 7249532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith SubExprs.push_back(TheCall->getArg(4)); // OrderFail 7250c8e5a0f70cbdb800d939c1807d05f380b2854d4Ted Kremenek } 726dd0f7942c5415ce146dcc02d57fc503c683f8625Ted Kremenek 727dd0f7942c5415ce146dcc02d57fc503c683f8625Ted Kremenek return Owned(new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(), 728610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek SubExprs.data(), SubExprs.size(), 729610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek ResultType, Op, 73025c1d57fc906e895535fb5c7e6dde80219f353b5Ted Kremenek TheCall->getRParenLoc())); 73125c1d57fc906e895535fb5c7e6dde80219f353b5Ted Kremenek} 73225c1d57fc906e895535fb5c7e6dde80219f353b5Ted Kremenek 73325c1d57fc906e895535fb5c7e6dde80219f353b5Ted Kremenek 73425c1d57fc906e895535fb5c7e6dde80219f353b5Ted Kremenek/// checkBuiltinArgument - Given a call to a builtin function, perform 73525c1d57fc906e895535fb5c7e6dde80219f353b5Ted Kremenek/// normal type-checking on the given argument, updating the call in 73625c1d57fc906e895535fb5c7e6dde80219f353b5Ted Kremenek/// place. This is useful when a builtin function requires custom 73725c1d57fc906e895535fb5c7e6dde80219f353b5Ted Kremenek/// type-checking for some of its arguments but not necessarily all of 738610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek/// them. 739610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek/// 740610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek/// Returns true on error. 741610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenekstatic bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 74213bd4236ab8297350be388ab442b4c42eb8fe437Ted Kremenek FunctionDecl *Fn = E->getDirectCallee(); 7431d26f48dc2eea1c07431ca1519d7034a21b9bcffTed Kremenek assert(Fn && "builtin call without direct callee!"); 7449532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith 745f8adeefa9e9882bff402e092024dd457f8574673Ted Kremenek ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 746eba76a4379997f66f8114eb7e63206a5932b1be8Ted Kremenek InitializedEntity Entity = 747f8adeefa9e9882bff402e092024dd457f8574673Ted Kremenek InitializedEntity::InitializeParameter(S.Context, Param); 748610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek 749eee18c38b6dd29c0e6982f5565fcbc3f76d1bf4dTed Kremenek ExprResult Arg = E->getArg(0); 750610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 751610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek if (Arg.isInvalid()) 752610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek return true; 7536f27542da8843b5c1c579b86e342385bcc43d5f0Ted Kremenek 754651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines E->setArg(ArgIndex, Arg.take()); 755651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines return false; 7566f27542da8843b5c1c579b86e342385bcc43d5f0Ted Kremenek} 757eee18c38b6dd29c0e6982f5565fcbc3f76d1bf4dTed Kremenek 7586f27542da8843b5c1c579b86e342385bcc43d5f0Ted Kremenek/// SemaBuiltinAtomicOverloaded - We have a call to a function like 7596f27542da8843b5c1c579b86e342385bcc43d5f0Ted Kremenek/// __sync_fetch_and_add, which is an overloaded function based on the pointer 760610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek/// type of its first argument. The main ActOnCallExpr routines have already 761610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek/// promoted the types of arguments because all of these calls are prototyped as 7629532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith/// void(...). 763610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek/// 764610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek/// This function goes through and does final semantic checking for these 765b07805485c603be3d8011f72611465324c9e664bDavid Blaikie/// builtins, 766b07805485c603be3d8011f72611465324c9e664bDavid BlaikieExprResult 767610068c8cd2321f90e147b12cf794e1f840b6405Ted KremenekSema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 768136f8f24b0b6c0e57aaa4375d280d72dc5492615Ted Kremenek CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 769610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 770610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 771eba76a4379997f66f8114eb7e63206a5932b1be8Ted Kremenek 772eba76a4379997f66f8114eb7e63206a5932b1be8Ted Kremenek // Ensure that we have at least one argument to do type inference from. 773eba76a4379997f66f8114eb7e63206a5932b1be8Ted Kremenek if (TheCall->getNumArgs() < 1) { 774eba76a4379997f66f8114eb7e63206a5932b1be8Ted Kremenek Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 775eba76a4379997f66f8114eb7e63206a5932b1be8Ted Kremenek << 0 << 1 << TheCall->getNumArgs() 776eba76a4379997f66f8114eb7e63206a5932b1be8Ted Kremenek << TheCall->getCallee()->getSourceRange(); 777eba76a4379997f66f8114eb7e63206a5932b1be8Ted Kremenek return ExprError(); 778eba76a4379997f66f8114eb7e63206a5932b1be8Ted Kremenek } 779eba76a4379997f66f8114eb7e63206a5932b1be8Ted Kremenek 780eba76a4379997f66f8114eb7e63206a5932b1be8Ted Kremenek // Inspect the first argument of the atomic builtin. This should always be 781eba76a4379997f66f8114eb7e63206a5932b1be8Ted Kremenek // a pointer type, whose element is an integral scalar or pointer type. 782eba76a4379997f66f8114eb7e63206a5932b1be8Ted Kremenek // Because it is a pointer type, we don't have to worry about any implicit 783eba76a4379997f66f8114eb7e63206a5932b1be8Ted Kremenek // casts here. 784eba76a4379997f66f8114eb7e63206a5932b1be8Ted Kremenek // FIXME: We don't allow floating point scalars as input. 785eba76a4379997f66f8114eb7e63206a5932b1be8Ted Kremenek Expr *FirstArg = TheCall->getArg(0); 786eba76a4379997f66f8114eb7e63206a5932b1be8Ted Kremenek const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 787eba76a4379997f66f8114eb7e63206a5932b1be8Ted Kremenek if (!pointerType) { 788eba76a4379997f66f8114eb7e63206a5932b1be8Ted Kremenek Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 789eba76a4379997f66f8114eb7e63206a5932b1be8Ted Kremenek << FirstArg->getType() << FirstArg->getSourceRange(); 790eba76a4379997f66f8114eb7e63206a5932b1be8Ted Kremenek return ExprError(); 791eba76a4379997f66f8114eb7e63206a5932b1be8Ted Kremenek } 792651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines 793651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines QualType ValType = pointerType->getPointeeType(); 794eba76a4379997f66f8114eb7e63206a5932b1be8Ted Kremenek if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 795eba76a4379997f66f8114eb7e63206a5932b1be8Ted Kremenek !ValType->isBlockPointerType()) { 796eba76a4379997f66f8114eb7e63206a5932b1be8Ted Kremenek Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr) 797eba76a4379997f66f8114eb7e63206a5932b1be8Ted Kremenek << FirstArg->getType() << FirstArg->getSourceRange(); 798eba76a4379997f66f8114eb7e63206a5932b1be8Ted Kremenek return ExprError(); 799eba76a4379997f66f8114eb7e63206a5932b1be8Ted Kremenek } 800eba76a4379997f66f8114eb7e63206a5932b1be8Ted Kremenek 801651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines switch (ValType.getObjCLifetime()) { 802eba76a4379997f66f8114eb7e63206a5932b1be8Ted Kremenek case Qualifiers::OCL_None: 803eba76a4379997f66f8114eb7e63206a5932b1be8Ted Kremenek case Qualifiers::OCL_ExplicitNone: 804eba76a4379997f66f8114eb7e63206a5932b1be8Ted Kremenek // okay 805eba76a4379997f66f8114eb7e63206a5932b1be8Ted Kremenek break; 806eba76a4379997f66f8114eb7e63206a5932b1be8Ted Kremenek 807eba76a4379997f66f8114eb7e63206a5932b1be8Ted Kremenek case Qualifiers::OCL_Weak: 8085d98994c7749312a43ce6adf45537979a98e7afdChandler Carruth case Qualifiers::OCL_Strong: 8095d98994c7749312a43ce6adf45537979a98e7afdChandler Carruth case Qualifiers::OCL_Autoreleasing: 8105d98994c7749312a43ce6adf45537979a98e7afdChandler Carruth Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 8111d26f48dc2eea1c07431ca1519d7034a21b9bcffTed Kremenek << ValType << FirstArg->getSourceRange(); 8125d98994c7749312a43ce6adf45537979a98e7afdChandler Carruth return ExprError(); 8135d98994c7749312a43ce6adf45537979a98e7afdChandler Carruth } 814610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek 815610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek // Strip any qualifiers off ValType. 816610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek ValType = ValType.getUnqualifiedType(); 817610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek 818d40066b0fb883839a9100e5455e33190b9b8abacTed Kremenek // The majority of builtins return a value, but a few have special return 8195d98994c7749312a43ce6adf45537979a98e7afdChandler Carruth // types, so allow them to override appropriately below. 8205d98994c7749312a43ce6adf45537979a98e7afdChandler Carruth QualType ResultType = ValType; 8219532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith 8229532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith // We need to figure out which concrete builtin this maps onto. For example, 8239532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith // __sync_fetch_and_add with a 2 byte object turns into 8249532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith // __sync_fetch_and_add_2. 825d40066b0fb883839a9100e5455e33190b9b8abacTed Kremenek#define BUILTIN_ROW(x) \ 826d40066b0fb883839a9100e5455e33190b9b8abacTed Kremenek { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 827eee18c38b6dd29c0e6982f5565fcbc3f76d1bf4dTed Kremenek Builtin::BI##x##_8, Builtin::BI##x##_16 } 828eee18c38b6dd29c0e6982f5565fcbc3f76d1bf4dTed Kremenek 829eee18c38b6dd29c0e6982f5565fcbc3f76d1bf4dTed Kremenek static const unsigned BuiltinIndices[][5] = { 830eee18c38b6dd29c0e6982f5565fcbc3f76d1bf4dTed Kremenek BUILTIN_ROW(__sync_fetch_and_add), 831d40066b0fb883839a9100e5455e33190b9b8abacTed Kremenek BUILTIN_ROW(__sync_fetch_and_sub), 832d40066b0fb883839a9100e5455e33190b9b8abacTed Kremenek BUILTIN_ROW(__sync_fetch_and_or), 833d40066b0fb883839a9100e5455e33190b9b8abacTed Kremenek BUILTIN_ROW(__sync_fetch_and_and), 834c1602581f7a4eab486489f09647d724ce35d3f23Ted Kremenek BUILTIN_ROW(__sync_fetch_and_xor), 835496398d523de712ac1084c53a397ca3987fe43dbTed Kremenek 836610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek BUILTIN_ROW(__sync_add_and_fetch), 837f8adeefa9e9882bff402e092024dd457f8574673Ted Kremenek BUILTIN_ROW(__sync_sub_and_fetch), 8386f27542da8843b5c1c579b86e342385bcc43d5f0Ted Kremenek BUILTIN_ROW(__sync_and_and_fetch), 839eba76a4379997f66f8114eb7e63206a5932b1be8Ted Kremenek BUILTIN_ROW(__sync_or_and_fetch), 840610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek BUILTIN_ROW(__sync_xor_and_fetch), 841610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek 842eba76a4379997f66f8114eb7e63206a5932b1be8Ted Kremenek BUILTIN_ROW(__sync_val_compare_and_swap), 843eba76a4379997f66f8114eb7e63206a5932b1be8Ted Kremenek BUILTIN_ROW(__sync_bool_compare_and_swap), 844610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek BUILTIN_ROW(__sync_lock_test_and_set), 8459532e0d89ca2afa556f032aa9377f6ec1d3eaa3eRichard Smith BUILTIN_ROW(__sync_lock_release), 846eba76a4379997f66f8114eb7e63206a5932b1be8Ted Kremenek BUILTIN_ROW(__sync_swap) 8475d98994c7749312a43ce6adf45537979a98e7afdChandler Carruth }; 848610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek#undef BUILTIN_ROW 849610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek 850610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek // Determine the index of the size. 851610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek unsigned SizeIndex; 852eba76a4379997f66f8114eb7e63206a5932b1be8Ted Kremenek switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 853eba76a4379997f66f8114eb7e63206a5932b1be8Ted Kremenek case 1: SizeIndex = 0; break; 854eba76a4379997f66f8114eb7e63206a5932b1be8Ted Kremenek case 2: SizeIndex = 1; break; 855eba76a4379997f66f8114eb7e63206a5932b1be8Ted Kremenek case 4: SizeIndex = 2; break; 85667d472c19310c06efd5cb87c60b8489abf507233Enea Zaffanella case 8: SizeIndex = 3; break; 857610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek case 16: SizeIndex = 4; break; 8586f27542da8843b5c1c579b86e342385bcc43d5f0Ted Kremenek default: 859eba76a4379997f66f8114eb7e63206a5932b1be8Ted Kremenek Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size) 860eba76a4379997f66f8114eb7e63206a5932b1be8Ted Kremenek << FirstArg->getType() << FirstArg->getSourceRange(); 8615d98994c7749312a43ce6adf45537979a98e7afdChandler Carruth return ExprError(); 8625d98994c7749312a43ce6adf45537979a98e7afdChandler Carruth } 863610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek 864610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek // Each of these builtins has one pointer argument, followed by some number of 865610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek // values (0, 1 or 2) followed by a potentially empty varags list of stuff 866610068c8cd2321f90e147b12cf794e1f840b6405Ted Kremenek // that we ignore. Find out which row of BuiltinIndices to read from as well 867 // as the number of fixed args. 868 unsigned BuiltinID = FDecl->getBuiltinID(); 869 unsigned BuiltinIndex, NumFixed = 1; 870 switch (BuiltinID) { 871 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 872 case Builtin::BI__sync_fetch_and_add: 873 case Builtin::BI__sync_fetch_and_add_1: 874 case Builtin::BI__sync_fetch_and_add_2: 875 case Builtin::BI__sync_fetch_and_add_4: 876 case Builtin::BI__sync_fetch_and_add_8: 877 case Builtin::BI__sync_fetch_and_add_16: 878 BuiltinIndex = 0; 879 break; 880 881 case Builtin::BI__sync_fetch_and_sub: 882 case Builtin::BI__sync_fetch_and_sub_1: 883 case Builtin::BI__sync_fetch_and_sub_2: 884 case Builtin::BI__sync_fetch_and_sub_4: 885 case Builtin::BI__sync_fetch_and_sub_8: 886 case Builtin::BI__sync_fetch_and_sub_16: 887 BuiltinIndex = 1; 888 break; 889 890 case Builtin::BI__sync_fetch_and_or: 891 case Builtin::BI__sync_fetch_and_or_1: 892 case Builtin::BI__sync_fetch_and_or_2: 893 case Builtin::BI__sync_fetch_and_or_4: 894 case Builtin::BI__sync_fetch_and_or_8: 895 case Builtin::BI__sync_fetch_and_or_16: 896 BuiltinIndex = 2; 897 break; 898 899 case Builtin::BI__sync_fetch_and_and: 900 case Builtin::BI__sync_fetch_and_and_1: 901 case Builtin::BI__sync_fetch_and_and_2: 902 case Builtin::BI__sync_fetch_and_and_4: 903 case Builtin::BI__sync_fetch_and_and_8: 904 case Builtin::BI__sync_fetch_and_and_16: 905 BuiltinIndex = 3; 906 break; 907 908 case Builtin::BI__sync_fetch_and_xor: 909 case Builtin::BI__sync_fetch_and_xor_1: 910 case Builtin::BI__sync_fetch_and_xor_2: 911 case Builtin::BI__sync_fetch_and_xor_4: 912 case Builtin::BI__sync_fetch_and_xor_8: 913 case Builtin::BI__sync_fetch_and_xor_16: 914 BuiltinIndex = 4; 915 break; 916 917 case Builtin::BI__sync_add_and_fetch: 918 case Builtin::BI__sync_add_and_fetch_1: 919 case Builtin::BI__sync_add_and_fetch_2: 920 case Builtin::BI__sync_add_and_fetch_4: 921 case Builtin::BI__sync_add_and_fetch_8: 922 case Builtin::BI__sync_add_and_fetch_16: 923 BuiltinIndex = 5; 924 break; 925 926 case Builtin::BI__sync_sub_and_fetch: 927 case Builtin::BI__sync_sub_and_fetch_1: 928 case Builtin::BI__sync_sub_and_fetch_2: 929 case Builtin::BI__sync_sub_and_fetch_4: 930 case Builtin::BI__sync_sub_and_fetch_8: 931 case Builtin::BI__sync_sub_and_fetch_16: 932 BuiltinIndex = 6; 933 break; 934 935 case Builtin::BI__sync_and_and_fetch: 936 case Builtin::BI__sync_and_and_fetch_1: 937 case Builtin::BI__sync_and_and_fetch_2: 938 case Builtin::BI__sync_and_and_fetch_4: 939 case Builtin::BI__sync_and_and_fetch_8: 940 case Builtin::BI__sync_and_and_fetch_16: 941 BuiltinIndex = 7; 942 break; 943 944 case Builtin::BI__sync_or_and_fetch: 945 case Builtin::BI__sync_or_and_fetch_1: 946 case Builtin::BI__sync_or_and_fetch_2: 947 case Builtin::BI__sync_or_and_fetch_4: 948 case Builtin::BI__sync_or_and_fetch_8: 949 case Builtin::BI__sync_or_and_fetch_16: 950 BuiltinIndex = 8; 951 break; 952 953 case Builtin::BI__sync_xor_and_fetch: 954 case Builtin::BI__sync_xor_and_fetch_1: 955 case Builtin::BI__sync_xor_and_fetch_2: 956 case Builtin::BI__sync_xor_and_fetch_4: 957 case Builtin::BI__sync_xor_and_fetch_8: 958 case Builtin::BI__sync_xor_and_fetch_16: 959 BuiltinIndex = 9; 960 break; 961 962 case Builtin::BI__sync_val_compare_and_swap: 963 case Builtin::BI__sync_val_compare_and_swap_1: 964 case Builtin::BI__sync_val_compare_and_swap_2: 965 case Builtin::BI__sync_val_compare_and_swap_4: 966 case Builtin::BI__sync_val_compare_and_swap_8: 967 case Builtin::BI__sync_val_compare_and_swap_16: 968 BuiltinIndex = 10; 969 NumFixed = 2; 970 break; 971 972 case Builtin::BI__sync_bool_compare_and_swap: 973 case Builtin::BI__sync_bool_compare_and_swap_1: 974 case Builtin::BI__sync_bool_compare_and_swap_2: 975 case Builtin::BI__sync_bool_compare_and_swap_4: 976 case Builtin::BI__sync_bool_compare_and_swap_8: 977 case Builtin::BI__sync_bool_compare_and_swap_16: 978 BuiltinIndex = 11; 979 NumFixed = 2; 980 ResultType = Context.BoolTy; 981 break; 982 983 case Builtin::BI__sync_lock_test_and_set: 984 case Builtin::BI__sync_lock_test_and_set_1: 985 case Builtin::BI__sync_lock_test_and_set_2: 986 case Builtin::BI__sync_lock_test_and_set_4: 987 case Builtin::BI__sync_lock_test_and_set_8: 988 case Builtin::BI__sync_lock_test_and_set_16: 989 BuiltinIndex = 12; 990 break; 991 992 case Builtin::BI__sync_lock_release: 993 case Builtin::BI__sync_lock_release_1: 994 case Builtin::BI__sync_lock_release_2: 995 case Builtin::BI__sync_lock_release_4: 996 case Builtin::BI__sync_lock_release_8: 997 case Builtin::BI__sync_lock_release_16: 998 BuiltinIndex = 13; 999 NumFixed = 0; 1000 ResultType = Context.VoidTy; 1001 break; 1002 1003 case Builtin::BI__sync_swap: 1004 case Builtin::BI__sync_swap_1: 1005 case Builtin::BI__sync_swap_2: 1006 case Builtin::BI__sync_swap_4: 1007 case Builtin::BI__sync_swap_8: 1008 case Builtin::BI__sync_swap_16: 1009 BuiltinIndex = 14; 1010 break; 1011 } 1012 1013 // Now that we know how many fixed arguments we expect, first check that we 1014 // have at least that many. 1015 if (TheCall->getNumArgs() < 1+NumFixed) { 1016 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 1017 << 0 << 1+NumFixed << TheCall->getNumArgs() 1018 << TheCall->getCallee()->getSourceRange(); 1019 return ExprError(); 1020 } 1021 1022 // Get the decl for the concrete builtin from this, we can tell what the 1023 // concrete integer type we should convert to is. 1024 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 1025 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID); 1026 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName); 1027 FunctionDecl *NewBuiltinDecl = 1028 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID, 1029 TUScope, false, DRE->getLocStart())); 1030 1031 // The first argument --- the pointer --- has a fixed type; we 1032 // deduce the types of the rest of the arguments accordingly. Walk 1033 // the remaining arguments, converting them to the deduced value type. 1034 for (unsigned i = 0; i != NumFixed; ++i) { 1035 ExprResult Arg = TheCall->getArg(i+1); 1036 1037 // GCC does an implicit conversion to the pointer or integer ValType. This 1038 // can fail in some cases (1i -> int**), check for this error case now. 1039 // Initialize the argument. 1040 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 1041 ValType, /*consume*/ false); 1042 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 1043 if (Arg.isInvalid()) 1044 return ExprError(); 1045 1046 // Okay, we have something that *can* be converted to the right type. Check 1047 // to see if there is a potentially weird extension going on here. This can 1048 // happen when you do an atomic operation on something like an char* and 1049 // pass in 42. The 42 gets converted to char. This is even more strange 1050 // for things like 45.123 -> char, etc. 1051 // FIXME: Do this check. 1052 TheCall->setArg(i+1, Arg.take()); 1053 } 1054 1055 ASTContext& Context = this->getASTContext(); 1056 1057 // Create a new DeclRefExpr to refer to the new decl. 1058 DeclRefExpr* NewDRE = DeclRefExpr::Create( 1059 Context, 1060 DRE->getQualifierLoc(), 1061 NewBuiltinDecl, 1062 DRE->getLocation(), 1063 NewBuiltinDecl->getType(), 1064 DRE->getValueKind()); 1065 1066 // Set the callee in the CallExpr. 1067 // FIXME: This leaks the original parens and implicit casts. 1068 ExprResult PromotedCall = UsualUnaryConversions(NewDRE); 1069 if (PromotedCall.isInvalid()) 1070 return ExprError(); 1071 TheCall->setCallee(PromotedCall.take()); 1072 1073 // Change the result type of the call to match the original value type. This 1074 // is arbitrary, but the codegen for these builtins ins design to handle it 1075 // gracefully. 1076 TheCall->setType(ResultType); 1077 1078 return move(TheCallResult); 1079} 1080 1081/// CheckObjCString - Checks that the argument to the builtin 1082/// CFString constructor is correct 1083/// Note: It might also make sense to do the UTF-16 conversion here (would 1084/// simplify the backend). 1085bool Sema::CheckObjCString(Expr *Arg) { 1086 Arg = Arg->IgnoreParenCasts(); 1087 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 1088 1089 if (!Literal || !Literal->isAscii()) { 1090 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant) 1091 << Arg->getSourceRange(); 1092 return true; 1093 } 1094 1095 if (Literal->containsNonAsciiOrNull()) { 1096 StringRef String = Literal->getString(); 1097 unsigned NumBytes = String.size(); 1098 SmallVector<UTF16, 128> ToBuf(NumBytes); 1099 const UTF8 *FromPtr = (UTF8 *)String.data(); 1100 UTF16 *ToPtr = &ToBuf[0]; 1101 1102 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, 1103 &ToPtr, ToPtr + NumBytes, 1104 strictConversion); 1105 // Check for conversion failure. 1106 if (Result != conversionOK) 1107 Diag(Arg->getLocStart(), 1108 diag::warn_cfstring_truncated) << Arg->getSourceRange(); 1109 } 1110 return false; 1111} 1112 1113/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity. 1114/// Emit an error and return true on failure, return false on success. 1115bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) { 1116 Expr *Fn = TheCall->getCallee(); 1117 if (TheCall->getNumArgs() > 2) { 1118 Diag(TheCall->getArg(2)->getLocStart(), 1119 diag::err_typecheck_call_too_many_args) 1120 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 1121 << Fn->getSourceRange() 1122 << SourceRange(TheCall->getArg(2)->getLocStart(), 1123 (*(TheCall->arg_end()-1))->getLocEnd()); 1124 return true; 1125 } 1126 1127 if (TheCall->getNumArgs() < 2) { 1128 return Diag(TheCall->getLocEnd(), 1129 diag::err_typecheck_call_too_few_args_at_least) 1130 << 0 /*function call*/ << 2 << TheCall->getNumArgs(); 1131 } 1132 1133 // Type-check the first argument normally. 1134 if (checkBuiltinArgument(*this, TheCall, 0)) 1135 return true; 1136 1137 // Determine whether the current function is variadic or not. 1138 BlockScopeInfo *CurBlock = getCurBlock(); 1139 bool isVariadic; 1140 if (CurBlock) 1141 isVariadic = CurBlock->TheDecl->isVariadic(); 1142 else if (FunctionDecl *FD = getCurFunctionDecl()) 1143 isVariadic = FD->isVariadic(); 1144 else 1145 isVariadic = getCurMethodDecl()->isVariadic(); 1146 1147 if (!isVariadic) { 1148 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function); 1149 return true; 1150 } 1151 1152 // Verify that the second argument to the builtin is the last argument of the 1153 // current function or method. 1154 bool SecondArgIsLastNamedArgument = false; 1155 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 1156 1157 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 1158 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 1159 // FIXME: This isn't correct for methods (results in bogus warning). 1160 // Get the last formal in the current function. 1161 const ParmVarDecl *LastArg; 1162 if (CurBlock) 1163 LastArg = *(CurBlock->TheDecl->param_end()-1); 1164 else if (FunctionDecl *FD = getCurFunctionDecl()) 1165 LastArg = *(FD->param_end()-1); 1166 else 1167 LastArg = *(getCurMethodDecl()->param_end()-1); 1168 SecondArgIsLastNamedArgument = PV == LastArg; 1169 } 1170 } 1171 1172 if (!SecondArgIsLastNamedArgument) 1173 Diag(TheCall->getArg(1)->getLocStart(), 1174 diag::warn_second_parameter_of_va_start_not_last_named_argument); 1175 return false; 1176} 1177 1178/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 1179/// friends. This is declared to take (...), so we have to check everything. 1180bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 1181 if (TheCall->getNumArgs() < 2) 1182 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 1183 << 0 << 2 << TheCall->getNumArgs()/*function call*/; 1184 if (TheCall->getNumArgs() > 2) 1185 return Diag(TheCall->getArg(2)->getLocStart(), 1186 diag::err_typecheck_call_too_many_args) 1187 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 1188 << SourceRange(TheCall->getArg(2)->getLocStart(), 1189 (*(TheCall->arg_end()-1))->getLocEnd()); 1190 1191 ExprResult OrigArg0 = TheCall->getArg(0); 1192 ExprResult OrigArg1 = TheCall->getArg(1); 1193 1194 // Do standard promotions between the two arguments, returning their common 1195 // type. 1196 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false); 1197 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 1198 return true; 1199 1200 // Make sure any conversions are pushed back into the call; this is 1201 // type safe since unordered compare builtins are declared as "_Bool 1202 // foo(...)". 1203 TheCall->setArg(0, OrigArg0.get()); 1204 TheCall->setArg(1, OrigArg1.get()); 1205 1206 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 1207 return false; 1208 1209 // If the common type isn't a real floating type, then the arguments were 1210 // invalid for this operation. 1211 if (!Res->isRealFloatingType()) 1212 return Diag(OrigArg0.get()->getLocStart(), 1213 diag::err_typecheck_call_invalid_ordered_compare) 1214 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 1215 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd()); 1216 1217 return false; 1218} 1219 1220/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 1221/// __builtin_isnan and friends. This is declared to take (...), so we have 1222/// to check everything. We expect the last argument to be a floating point 1223/// value. 1224bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 1225 if (TheCall->getNumArgs() < NumArgs) 1226 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 1227 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/; 1228 if (TheCall->getNumArgs() > NumArgs) 1229 return Diag(TheCall->getArg(NumArgs)->getLocStart(), 1230 diag::err_typecheck_call_too_many_args) 1231 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs() 1232 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(), 1233 (*(TheCall->arg_end()-1))->getLocEnd()); 1234 1235 Expr *OrigArg = TheCall->getArg(NumArgs-1); 1236 1237 if (OrigArg->isTypeDependent()) 1238 return false; 1239 1240 // This operation requires a non-_Complex floating-point number. 1241 if (!OrigArg->getType()->isRealFloatingType()) 1242 return Diag(OrigArg->getLocStart(), 1243 diag::err_typecheck_call_invalid_unary_fp) 1244 << OrigArg->getType() << OrigArg->getSourceRange(); 1245 1246 // If this is an implicit conversion from float -> double, remove it. 1247 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) { 1248 Expr *CastArg = Cast->getSubExpr(); 1249 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) { 1250 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) && 1251 "promotion from float to double is the only expected cast here"); 1252 Cast->setSubExpr(0); 1253 TheCall->setArg(NumArgs-1, CastArg); 1254 OrigArg = CastArg; 1255 } 1256 } 1257 1258 return false; 1259} 1260 1261/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 1262// This is declared to take (...), so we have to check everything. 1263ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 1264 if (TheCall->getNumArgs() < 2) 1265 return ExprError(Diag(TheCall->getLocEnd(), 1266 diag::err_typecheck_call_too_few_args_at_least) 1267 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 1268 << TheCall->getSourceRange()); 1269 1270 // Determine which of the following types of shufflevector we're checking: 1271 // 1) unary, vector mask: (lhs, mask) 1272 // 2) binary, vector mask: (lhs, rhs, mask) 1273 // 3) binary, scalar mask: (lhs, rhs, index, ..., index) 1274 QualType resType = TheCall->getArg(0)->getType(); 1275 unsigned numElements = 0; 1276 1277 if (!TheCall->getArg(0)->isTypeDependent() && 1278 !TheCall->getArg(1)->isTypeDependent()) { 1279 QualType LHSType = TheCall->getArg(0)->getType(); 1280 QualType RHSType = TheCall->getArg(1)->getType(); 1281 1282 if (!LHSType->isVectorType() || !RHSType->isVectorType()) { 1283 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector) 1284 << SourceRange(TheCall->getArg(0)->getLocStart(), 1285 TheCall->getArg(1)->getLocEnd()); 1286 return ExprError(); 1287 } 1288 1289 numElements = LHSType->getAs<VectorType>()->getNumElements(); 1290 unsigned numResElements = TheCall->getNumArgs() - 2; 1291 1292 // Check to see if we have a call with 2 vector arguments, the unary shuffle 1293 // with mask. If so, verify that RHS is an integer vector type with the 1294 // same number of elts as lhs. 1295 if (TheCall->getNumArgs() == 2) { 1296 if (!RHSType->hasIntegerRepresentation() || 1297 RHSType->getAs<VectorType>()->getNumElements() != numElements) 1298 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector) 1299 << SourceRange(TheCall->getArg(1)->getLocStart(), 1300 TheCall->getArg(1)->getLocEnd()); 1301 numResElements = numElements; 1302 } 1303 else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 1304 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector) 1305 << SourceRange(TheCall->getArg(0)->getLocStart(), 1306 TheCall->getArg(1)->getLocEnd()); 1307 return ExprError(); 1308 } else if (numElements != numResElements) { 1309 QualType eltType = LHSType->getAs<VectorType>()->getElementType(); 1310 resType = Context.getVectorType(eltType, numResElements, 1311 VectorType::GenericVector); 1312 } 1313 } 1314 1315 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 1316 if (TheCall->getArg(i)->isTypeDependent() || 1317 TheCall->getArg(i)->isValueDependent()) 1318 continue; 1319 1320 llvm::APSInt Result(32); 1321 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context)) 1322 return ExprError(Diag(TheCall->getLocStart(), 1323 diag::err_shufflevector_nonconstant_argument) 1324 << TheCall->getArg(i)->getSourceRange()); 1325 1326 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2) 1327 return ExprError(Diag(TheCall->getLocStart(), 1328 diag::err_shufflevector_argument_too_large) 1329 << TheCall->getArg(i)->getSourceRange()); 1330 } 1331 1332 SmallVector<Expr*, 32> exprs; 1333 1334 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 1335 exprs.push_back(TheCall->getArg(i)); 1336 TheCall->setArg(i, 0); 1337 } 1338 1339 return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(), 1340 exprs.size(), resType, 1341 TheCall->getCallee()->getLocStart(), 1342 TheCall->getRParenLoc())); 1343} 1344 1345/// SemaBuiltinPrefetch - Handle __builtin_prefetch. 1346// This is declared to take (const void*, ...) and can take two 1347// optional constant int args. 1348bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 1349 unsigned NumArgs = TheCall->getNumArgs(); 1350 1351 if (NumArgs > 3) 1352 return Diag(TheCall->getLocEnd(), 1353 diag::err_typecheck_call_too_many_args_at_most) 1354 << 0 /*function call*/ << 3 << NumArgs 1355 << TheCall->getSourceRange(); 1356 1357 // Argument 0 is checked for us and the remaining arguments must be 1358 // constant integers. 1359 for (unsigned i = 1; i != NumArgs; ++i) { 1360 Expr *Arg = TheCall->getArg(i); 1361 1362 llvm::APSInt Result; 1363 if (SemaBuiltinConstantArg(TheCall, i, Result)) 1364 return true; 1365 1366 // FIXME: gcc issues a warning and rewrites these to 0. These 1367 // seems especially odd for the third argument since the default 1368 // is 3. 1369 if (i == 1) { 1370 if (Result.getLimitedValue() > 1) 1371 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 1372 << "0" << "1" << Arg->getSourceRange(); 1373 } else { 1374 if (Result.getLimitedValue() > 3) 1375 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 1376 << "0" << "3" << Arg->getSourceRange(); 1377 } 1378 } 1379 1380 return false; 1381} 1382 1383/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 1384/// TheCall is a constant expression. 1385bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 1386 llvm::APSInt &Result) { 1387 Expr *Arg = TheCall->getArg(ArgNum); 1388 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 1389 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 1390 1391 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 1392 1393 if (!Arg->isIntegerConstantExpr(Result, Context)) 1394 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type) 1395 << FDecl->getDeclName() << Arg->getSourceRange(); 1396 1397 return false; 1398} 1399 1400/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr, 1401/// int type). This simply type checks that type is one of the defined 1402/// constants (0-3). 1403// For compatibility check 0-3, llvm only handles 0 and 2. 1404bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) { 1405 llvm::APSInt Result; 1406 1407 // Check constant-ness first. 1408 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 1409 return true; 1410 1411 Expr *Arg = TheCall->getArg(1); 1412 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) { 1413 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 1414 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 1415 } 1416 1417 return false; 1418} 1419 1420/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 1421/// This checks that val is a constant 1. 1422bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 1423 Expr *Arg = TheCall->getArg(1); 1424 llvm::APSInt Result; 1425 1426 // TODO: This is less than ideal. Overload this to take a value. 1427 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 1428 return true; 1429 1430 if (Result != 1) 1431 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val) 1432 << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 1433 1434 return false; 1435} 1436 1437// Handle i > 1 ? "x" : "y", recursively. 1438bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall, 1439 bool HasVAListArg, 1440 unsigned format_idx, unsigned firstDataArg, 1441 bool isPrintf, bool inFunctionCall) { 1442 tryAgain: 1443 if (E->isTypeDependent() || E->isValueDependent()) 1444 return false; 1445 1446 E = E->IgnoreParens(); 1447 1448 switch (E->getStmtClass()) { 1449 case Stmt::BinaryConditionalOperatorClass: 1450 case Stmt::ConditionalOperatorClass: { 1451 const AbstractConditionalOperator *C = cast<AbstractConditionalOperator>(E); 1452 return SemaCheckStringLiteral(C->getTrueExpr(), TheCall, HasVAListArg, 1453 format_idx, firstDataArg, isPrintf, 1454 inFunctionCall) 1455 && SemaCheckStringLiteral(C->getFalseExpr(), TheCall, HasVAListArg, 1456 format_idx, firstDataArg, isPrintf, 1457 inFunctionCall); 1458 } 1459 1460 case Stmt::IntegerLiteralClass: 1461 // Technically -Wformat-nonliteral does not warn about this case. 1462 // The behavior of printf and friends in this case is implementation 1463 // dependent. Ideally if the format string cannot be null then 1464 // it should have a 'nonnull' attribute in the function prototype. 1465 return true; 1466 1467 case Stmt::ImplicitCastExprClass: { 1468 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 1469 goto tryAgain; 1470 } 1471 1472 case Stmt::OpaqueValueExprClass: 1473 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 1474 E = src; 1475 goto tryAgain; 1476 } 1477 return false; 1478 1479 case Stmt::PredefinedExprClass: 1480 // While __func__, etc., are technically not string literals, they 1481 // cannot contain format specifiers and thus are not a security 1482 // liability. 1483 return true; 1484 1485 case Stmt::DeclRefExprClass: { 1486 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 1487 1488 // As an exception, do not flag errors for variables binding to 1489 // const string literals. 1490 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 1491 bool isConstant = false; 1492 QualType T = DR->getType(); 1493 1494 if (const ArrayType *AT = Context.getAsArrayType(T)) { 1495 isConstant = AT->getElementType().isConstant(Context); 1496 } else if (const PointerType *PT = T->getAs<PointerType>()) { 1497 isConstant = T.isConstant(Context) && 1498 PT->getPointeeType().isConstant(Context); 1499 } 1500 1501 if (isConstant) { 1502 if (const Expr *Init = VD->getAnyInitializer()) 1503 return SemaCheckStringLiteral(Init, TheCall, 1504 HasVAListArg, format_idx, firstDataArg, 1505 isPrintf, /*inFunctionCall*/false); 1506 } 1507 1508 // For vprintf* functions (i.e., HasVAListArg==true), we add a 1509 // special check to see if the format string is a function parameter 1510 // of the function calling the printf function. If the function 1511 // has an attribute indicating it is a printf-like function, then we 1512 // should suppress warnings concerning non-literals being used in a call 1513 // to a vprintf function. For example: 1514 // 1515 // void 1516 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 1517 // va_list ap; 1518 // va_start(ap, fmt); 1519 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 1520 // ... 1521 // 1522 // 1523 // FIXME: We don't have full attribute support yet, so just check to see 1524 // if the argument is a DeclRefExpr that references a parameter. We'll 1525 // add proper support for checking the attribute later. 1526 if (HasVAListArg) 1527 if (isa<ParmVarDecl>(VD)) 1528 return true; 1529 } 1530 1531 return false; 1532 } 1533 1534 case Stmt::CallExprClass: { 1535 const CallExpr *CE = cast<CallExpr>(E); 1536 if (const ImplicitCastExpr *ICE 1537 = dyn_cast<ImplicitCastExpr>(CE->getCallee())) { 1538 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) { 1539 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) { 1540 if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) { 1541 unsigned ArgIndex = FA->getFormatIdx(); 1542 const Expr *Arg = CE->getArg(ArgIndex - 1); 1543 1544 return SemaCheckStringLiteral(Arg, TheCall, HasVAListArg, 1545 format_idx, firstDataArg, isPrintf, 1546 inFunctionCall); 1547 } 1548 } 1549 } 1550 } 1551 1552 return false; 1553 } 1554 case Stmt::ObjCStringLiteralClass: 1555 case Stmt::StringLiteralClass: { 1556 const StringLiteral *StrE = NULL; 1557 1558 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 1559 StrE = ObjCFExpr->getString(); 1560 else 1561 StrE = cast<StringLiteral>(E); 1562 1563 if (StrE) { 1564 CheckFormatString(StrE, E, TheCall, HasVAListArg, format_idx, 1565 firstDataArg, isPrintf, inFunctionCall); 1566 return true; 1567 } 1568 1569 return false; 1570 } 1571 1572 default: 1573 return false; 1574 } 1575} 1576 1577void 1578Sema::CheckNonNullArguments(const NonNullAttr *NonNull, 1579 const Expr * const *ExprArgs, 1580 SourceLocation CallSiteLoc) { 1581 for (NonNullAttr::args_iterator i = NonNull->args_begin(), 1582 e = NonNull->args_end(); 1583 i != e; ++i) { 1584 const Expr *ArgExpr = ExprArgs[*i]; 1585 if (ArgExpr->isNullPointerConstant(Context, 1586 Expr::NPC_ValueDependentIsNotNull)) 1587 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 1588 } 1589} 1590 1591/// CheckPrintfScanfArguments - Check calls to printf and scanf (and similar 1592/// functions) for correct use of format strings. 1593void 1594Sema::CheckPrintfScanfArguments(const CallExpr *TheCall, bool HasVAListArg, 1595 unsigned format_idx, unsigned firstDataArg, 1596 bool isPrintf) { 1597 1598 const Expr *Fn = TheCall->getCallee(); 1599 1600 // The way the format attribute works in GCC, the implicit this argument 1601 // of member functions is counted. However, it doesn't appear in our own 1602 // lists, so decrement format_idx in that case. 1603 if (isa<CXXMemberCallExpr>(TheCall)) { 1604 const CXXMethodDecl *method_decl = 1605 dyn_cast<CXXMethodDecl>(TheCall->getCalleeDecl()); 1606 if (method_decl && method_decl->isInstance()) { 1607 // Catch a format attribute mistakenly referring to the object argument. 1608 if (format_idx == 0) 1609 return; 1610 --format_idx; 1611 if(firstDataArg != 0) 1612 --firstDataArg; 1613 } 1614 } 1615 1616 // CHECK: printf/scanf-like function is called with no format string. 1617 if (format_idx >= TheCall->getNumArgs()) { 1618 Diag(TheCall->getRParenLoc(), diag::warn_missing_format_string) 1619 << Fn->getSourceRange(); 1620 return; 1621 } 1622 1623 const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts(); 1624 1625 // CHECK: format string is not a string literal. 1626 // 1627 // Dynamically generated format strings are difficult to 1628 // automatically vet at compile time. Requiring that format strings 1629 // are string literals: (1) permits the checking of format strings by 1630 // the compiler and thereby (2) can practically remove the source of 1631 // many format string exploits. 1632 1633 // Format string can be either ObjC string (e.g. @"%d") or 1634 // C string (e.g. "%d") 1635 // ObjC string uses the same format specifiers as C string, so we can use 1636 // the same format string checking logic for both ObjC and C strings. 1637 if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx, 1638 firstDataArg, isPrintf)) 1639 return; // Literal format string found, check done! 1640 1641 // If there are no arguments specified, warn with -Wformat-security, otherwise 1642 // warn only with -Wformat-nonliteral. 1643 if (TheCall->getNumArgs() == format_idx+1) 1644 Diag(TheCall->getArg(format_idx)->getLocStart(), 1645 diag::warn_format_nonliteral_noargs) 1646 << OrigFormatExpr->getSourceRange(); 1647 else 1648 Diag(TheCall->getArg(format_idx)->getLocStart(), 1649 diag::warn_format_nonliteral) 1650 << OrigFormatExpr->getSourceRange(); 1651} 1652 1653namespace { 1654class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 1655protected: 1656 Sema &S; 1657 const StringLiteral *FExpr; 1658 const Expr *OrigFormatExpr; 1659 const unsigned FirstDataArg; 1660 const unsigned NumDataArgs; 1661 const bool IsObjCLiteral; 1662 const char *Beg; // Start of format string. 1663 const bool HasVAListArg; 1664 const CallExpr *TheCall; 1665 unsigned FormatIdx; 1666 llvm::BitVector CoveredArgs; 1667 bool usesPositionalArgs; 1668 bool atFirstArg; 1669 bool inFunctionCall; 1670public: 1671 CheckFormatHandler(Sema &s, const StringLiteral *fexpr, 1672 const Expr *origFormatExpr, unsigned firstDataArg, 1673 unsigned numDataArgs, bool isObjCLiteral, 1674 const char *beg, bool hasVAListArg, 1675 const CallExpr *theCall, unsigned formatIdx, 1676 bool inFunctionCall) 1677 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), 1678 FirstDataArg(firstDataArg), 1679 NumDataArgs(numDataArgs), 1680 IsObjCLiteral(isObjCLiteral), Beg(beg), 1681 HasVAListArg(hasVAListArg), 1682 TheCall(theCall), FormatIdx(formatIdx), 1683 usesPositionalArgs(false), atFirstArg(true), 1684 inFunctionCall(inFunctionCall) { 1685 CoveredArgs.resize(numDataArgs); 1686 CoveredArgs.reset(); 1687 } 1688 1689 void DoneProcessing(); 1690 1691 void HandleIncompleteSpecifier(const char *startSpecifier, 1692 unsigned specifierLen); 1693 1694 virtual void HandleInvalidPosition(const char *startSpecifier, 1695 unsigned specifierLen, 1696 analyze_format_string::PositionContext p); 1697 1698 virtual void HandleZeroPosition(const char *startPos, unsigned posLen); 1699 1700 void HandleNullChar(const char *nullCharacter); 1701 1702 template <typename Range> 1703 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall, 1704 const Expr *ArgumentExpr, 1705 PartialDiagnostic PDiag, 1706 SourceLocation StringLoc, 1707 bool IsStringLocation, Range StringRange, 1708 FixItHint Fixit = FixItHint()); 1709 1710protected: 1711 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 1712 const char *startSpec, 1713 unsigned specifierLen, 1714 const char *csStart, unsigned csLen); 1715 1716 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 1717 const char *startSpec, 1718 unsigned specifierLen); 1719 1720 SourceRange getFormatStringRange(); 1721 CharSourceRange getSpecifierRange(const char *startSpecifier, 1722 unsigned specifierLen); 1723 SourceLocation getLocationOfByte(const char *x); 1724 1725 const Expr *getDataArg(unsigned i) const; 1726 1727 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 1728 const analyze_format_string::ConversionSpecifier &CS, 1729 const char *startSpecifier, unsigned specifierLen, 1730 unsigned argIndex); 1731 1732 template <typename Range> 1733 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 1734 bool IsStringLocation, Range StringRange, 1735 FixItHint Fixit = FixItHint()); 1736 1737 void CheckPositionalAndNonpositionalArgs( 1738 const analyze_format_string::FormatSpecifier *FS); 1739}; 1740} 1741 1742SourceRange CheckFormatHandler::getFormatStringRange() { 1743 return OrigFormatExpr->getSourceRange(); 1744} 1745 1746CharSourceRange CheckFormatHandler:: 1747getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 1748 SourceLocation Start = getLocationOfByte(startSpecifier); 1749 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 1750 1751 // Advance the end SourceLocation by one due to half-open ranges. 1752 End = End.getLocWithOffset(1); 1753 1754 return CharSourceRange::getCharRange(Start, End); 1755} 1756 1757SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 1758 return S.getLocationOfStringLiteralByte(FExpr, x - Beg); 1759} 1760 1761void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 1762 unsigned specifierLen){ 1763 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 1764 getLocationOfByte(startSpecifier), 1765 /*IsStringLocation*/true, 1766 getSpecifierRange(startSpecifier, specifierLen)); 1767} 1768 1769void 1770CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 1771 analyze_format_string::PositionContext p) { 1772 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 1773 << (unsigned) p, 1774 getLocationOfByte(startPos), /*IsStringLocation*/true, 1775 getSpecifierRange(startPos, posLen)); 1776} 1777 1778void CheckFormatHandler::HandleZeroPosition(const char *startPos, 1779 unsigned posLen) { 1780 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 1781 getLocationOfByte(startPos), 1782 /*IsStringLocation*/true, 1783 getSpecifierRange(startPos, posLen)); 1784} 1785 1786void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 1787 if (!IsObjCLiteral) { 1788 // The presence of a null character is likely an error. 1789 EmitFormatDiagnostic( 1790 S.PDiag(diag::warn_printf_format_string_contains_null_char), 1791 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 1792 getFormatStringRange()); 1793 } 1794} 1795 1796const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 1797 return TheCall->getArg(FirstDataArg + i); 1798} 1799 1800void CheckFormatHandler::DoneProcessing() { 1801 // Does the number of data arguments exceed the number of 1802 // format conversions in the format string? 1803 if (!HasVAListArg) { 1804 // Find any arguments that weren't covered. 1805 CoveredArgs.flip(); 1806 signed notCoveredArg = CoveredArgs.find_first(); 1807 if (notCoveredArg >= 0) { 1808 assert((unsigned)notCoveredArg < NumDataArgs); 1809 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used), 1810 getDataArg((unsigned) notCoveredArg)->getLocStart(), 1811 /*IsStringLocation*/false, getFormatStringRange()); 1812 } 1813 } 1814} 1815 1816bool 1817CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 1818 SourceLocation Loc, 1819 const char *startSpec, 1820 unsigned specifierLen, 1821 const char *csStart, 1822 unsigned csLen) { 1823 1824 bool keepGoing = true; 1825 if (argIndex < NumDataArgs) { 1826 // Consider the argument coverered, even though the specifier doesn't 1827 // make sense. 1828 CoveredArgs.set(argIndex); 1829 } 1830 else { 1831 // If argIndex exceeds the number of data arguments we 1832 // don't issue a warning because that is just a cascade of warnings (and 1833 // they may have intended '%%' anyway). We don't want to continue processing 1834 // the format string after this point, however, as we will like just get 1835 // gibberish when trying to match arguments. 1836 keepGoing = false; 1837 } 1838 1839 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion) 1840 << StringRef(csStart, csLen), 1841 Loc, /*IsStringLocation*/true, 1842 getSpecifierRange(startSpec, specifierLen)); 1843 1844 return keepGoing; 1845} 1846 1847void 1848CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 1849 const char *startSpec, 1850 unsigned specifierLen) { 1851 EmitFormatDiagnostic( 1852 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 1853 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 1854} 1855 1856bool 1857CheckFormatHandler::CheckNumArgs( 1858 const analyze_format_string::FormatSpecifier &FS, 1859 const analyze_format_string::ConversionSpecifier &CS, 1860 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 1861 1862 if (argIndex >= NumDataArgs) { 1863 PartialDiagnostic PDiag = FS.usesPositionalArg() 1864 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 1865 << (argIndex+1) << NumDataArgs) 1866 : S.PDiag(diag::warn_printf_insufficient_data_args); 1867 EmitFormatDiagnostic( 1868 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 1869 getSpecifierRange(startSpecifier, specifierLen)); 1870 return false; 1871 } 1872 return true; 1873} 1874 1875template<typename Range> 1876void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 1877 SourceLocation Loc, 1878 bool IsStringLocation, 1879 Range StringRange, 1880 FixItHint FixIt) { 1881 EmitFormatDiagnostic(S, inFunctionCall, TheCall->getArg(FormatIdx), PDiag, 1882 Loc, IsStringLocation, StringRange, FixIt); 1883} 1884 1885/// \brief If the format string is not within the funcion call, emit a note 1886/// so that the function call and string are in diagnostic messages. 1887/// 1888/// \param inFunctionCall if true, the format string is within the function 1889/// call and only one diagnostic message will be produced. Otherwise, an 1890/// extra note will be emitted pointing to location of the format string. 1891/// 1892/// \param ArgumentExpr the expression that is passed as the format string 1893/// argument in the function call. Used for getting locations when two 1894/// diagnostics are emitted. 1895/// 1896/// \param PDiag the callee should already have provided any strings for the 1897/// diagnostic message. This function only adds locations and fixits 1898/// to diagnostics. 1899/// 1900/// \param Loc primary location for diagnostic. If two diagnostics are 1901/// required, one will be at Loc and a new SourceLocation will be created for 1902/// the other one. 1903/// 1904/// \param IsStringLocation if true, Loc points to the format string should be 1905/// used for the note. Otherwise, Loc points to the argument list and will 1906/// be used with PDiag. 1907/// 1908/// \param StringRange some or all of the string to highlight. This is 1909/// templated so it can accept either a CharSourceRange or a SourceRange. 1910/// 1911/// \param Fixit optional fix it hint for the format string. 1912template<typename Range> 1913void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall, 1914 const Expr *ArgumentExpr, 1915 PartialDiagnostic PDiag, 1916 SourceLocation Loc, 1917 bool IsStringLocation, 1918 Range StringRange, 1919 FixItHint FixIt) { 1920 if (InFunctionCall) 1921 S.Diag(Loc, PDiag) << StringRange << FixIt; 1922 else { 1923 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 1924 << ArgumentExpr->getSourceRange(); 1925 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 1926 diag::note_format_string_defined) 1927 << StringRange << FixIt; 1928 } 1929} 1930 1931//===--- CHECK: Printf format string checking ------------------------------===// 1932 1933namespace { 1934class CheckPrintfHandler : public CheckFormatHandler { 1935public: 1936 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr, 1937 const Expr *origFormatExpr, unsigned firstDataArg, 1938 unsigned numDataArgs, bool isObjCLiteral, 1939 const char *beg, bool hasVAListArg, 1940 const CallExpr *theCall, unsigned formatIdx, 1941 bool inFunctionCall) 1942 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg, 1943 numDataArgs, isObjCLiteral, beg, hasVAListArg, 1944 theCall, formatIdx, inFunctionCall) {} 1945 1946 1947 bool HandleInvalidPrintfConversionSpecifier( 1948 const analyze_printf::PrintfSpecifier &FS, 1949 const char *startSpecifier, 1950 unsigned specifierLen); 1951 1952 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 1953 const char *startSpecifier, 1954 unsigned specifierLen); 1955 1956 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 1957 const char *startSpecifier, unsigned specifierLen); 1958 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 1959 const analyze_printf::OptionalAmount &Amt, 1960 unsigned type, 1961 const char *startSpecifier, unsigned specifierLen); 1962 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 1963 const analyze_printf::OptionalFlag &flag, 1964 const char *startSpecifier, unsigned specifierLen); 1965 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 1966 const analyze_printf::OptionalFlag &ignoredFlag, 1967 const analyze_printf::OptionalFlag &flag, 1968 const char *startSpecifier, unsigned specifierLen); 1969}; 1970} 1971 1972bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 1973 const analyze_printf::PrintfSpecifier &FS, 1974 const char *startSpecifier, 1975 unsigned specifierLen) { 1976 const analyze_printf::PrintfConversionSpecifier &CS = 1977 FS.getConversionSpecifier(); 1978 1979 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 1980 getLocationOfByte(CS.getStart()), 1981 startSpecifier, specifierLen, 1982 CS.getStart(), CS.getLength()); 1983} 1984 1985bool CheckPrintfHandler::HandleAmount( 1986 const analyze_format_string::OptionalAmount &Amt, 1987 unsigned k, const char *startSpecifier, 1988 unsigned specifierLen) { 1989 1990 if (Amt.hasDataArgument()) { 1991 if (!HasVAListArg) { 1992 unsigned argIndex = Amt.getArgIndex(); 1993 if (argIndex >= NumDataArgs) { 1994 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 1995 << k, 1996 getLocationOfByte(Amt.getStart()), 1997 /*IsStringLocation*/true, 1998 getSpecifierRange(startSpecifier, specifierLen)); 1999 // Don't do any more checking. We will just emit 2000 // spurious errors. 2001 return false; 2002 } 2003 2004 // Type check the data argument. It should be an 'int'. 2005 // Although not in conformance with C99, we also allow the argument to be 2006 // an 'unsigned int' as that is a reasonably safe case. GCC also 2007 // doesn't emit a warning for that case. 2008 CoveredArgs.set(argIndex); 2009 const Expr *Arg = getDataArg(argIndex); 2010 QualType T = Arg->getType(); 2011 2012 const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context); 2013 assert(ATR.isValid()); 2014 2015 if (!ATR.matchesType(S.Context, T)) { 2016 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 2017 << k << ATR.getRepresentativeType(S.Context) 2018 << T << Arg->getSourceRange(), 2019 getLocationOfByte(Amt.getStart()), 2020 /*IsStringLocation*/true, 2021 getSpecifierRange(startSpecifier, specifierLen)); 2022 // Don't do any more checking. We will just emit 2023 // spurious errors. 2024 return false; 2025 } 2026 } 2027 } 2028 return true; 2029} 2030 2031void CheckPrintfHandler::HandleInvalidAmount( 2032 const analyze_printf::PrintfSpecifier &FS, 2033 const analyze_printf::OptionalAmount &Amt, 2034 unsigned type, 2035 const char *startSpecifier, 2036 unsigned specifierLen) { 2037 const analyze_printf::PrintfConversionSpecifier &CS = 2038 FS.getConversionSpecifier(); 2039 2040 FixItHint fixit = 2041 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 2042 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 2043 Amt.getConstantLength())) 2044 : FixItHint(); 2045 2046 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 2047 << type << CS.toString(), 2048 getLocationOfByte(Amt.getStart()), 2049 /*IsStringLocation*/true, 2050 getSpecifierRange(startSpecifier, specifierLen), 2051 fixit); 2052} 2053 2054void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 2055 const analyze_printf::OptionalFlag &flag, 2056 const char *startSpecifier, 2057 unsigned specifierLen) { 2058 // Warn about pointless flag with a fixit removal. 2059 const analyze_printf::PrintfConversionSpecifier &CS = 2060 FS.getConversionSpecifier(); 2061 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 2062 << flag.toString() << CS.toString(), 2063 getLocationOfByte(flag.getPosition()), 2064 /*IsStringLocation*/true, 2065 getSpecifierRange(startSpecifier, specifierLen), 2066 FixItHint::CreateRemoval( 2067 getSpecifierRange(flag.getPosition(), 1))); 2068} 2069 2070void CheckPrintfHandler::HandleIgnoredFlag( 2071 const analyze_printf::PrintfSpecifier &FS, 2072 const analyze_printf::OptionalFlag &ignoredFlag, 2073 const analyze_printf::OptionalFlag &flag, 2074 const char *startSpecifier, 2075 unsigned specifierLen) { 2076 // Warn about ignored flag with a fixit removal. 2077 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 2078 << ignoredFlag.toString() << flag.toString(), 2079 getLocationOfByte(ignoredFlag.getPosition()), 2080 /*IsStringLocation*/true, 2081 getSpecifierRange(startSpecifier, specifierLen), 2082 FixItHint::CreateRemoval( 2083 getSpecifierRange(ignoredFlag.getPosition(), 1))); 2084} 2085 2086bool 2087CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 2088 &FS, 2089 const char *startSpecifier, 2090 unsigned specifierLen) { 2091 2092 using namespace analyze_format_string; 2093 using namespace analyze_printf; 2094 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 2095 2096 if (FS.consumesDataArgument()) { 2097 if (atFirstArg) { 2098 atFirstArg = false; 2099 usesPositionalArgs = FS.usesPositionalArg(); 2100 } 2101 else if (usesPositionalArgs != FS.usesPositionalArg()) { 2102 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 2103 startSpecifier, specifierLen); 2104 return false; 2105 } 2106 } 2107 2108 // First check if the field width, precision, and conversion specifier 2109 // have matching data arguments. 2110 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 2111 startSpecifier, specifierLen)) { 2112 return false; 2113 } 2114 2115 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 2116 startSpecifier, specifierLen)) { 2117 return false; 2118 } 2119 2120 if (!CS.consumesDataArgument()) { 2121 // FIXME: Technically specifying a precision or field width here 2122 // makes no sense. Worth issuing a warning at some point. 2123 return true; 2124 } 2125 2126 // Consume the argument. 2127 unsigned argIndex = FS.getArgIndex(); 2128 if (argIndex < NumDataArgs) { 2129 // The check to see if the argIndex is valid will come later. 2130 // We set the bit here because we may exit early from this 2131 // function if we encounter some other error. 2132 CoveredArgs.set(argIndex); 2133 } 2134 2135 // Check for using an Objective-C specific conversion specifier 2136 // in a non-ObjC literal. 2137 if (!IsObjCLiteral && CS.isObjCArg()) { 2138 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 2139 specifierLen); 2140 } 2141 2142 // Check for invalid use of field width 2143 if (!FS.hasValidFieldWidth()) { 2144 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 2145 startSpecifier, specifierLen); 2146 } 2147 2148 // Check for invalid use of precision 2149 if (!FS.hasValidPrecision()) { 2150 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 2151 startSpecifier, specifierLen); 2152 } 2153 2154 // Check each flag does not conflict with any other component. 2155 if (!FS.hasValidThousandsGroupingPrefix()) 2156 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 2157 if (!FS.hasValidLeadingZeros()) 2158 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 2159 if (!FS.hasValidPlusPrefix()) 2160 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 2161 if (!FS.hasValidSpacePrefix()) 2162 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 2163 if (!FS.hasValidAlternativeForm()) 2164 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 2165 if (!FS.hasValidLeftJustified()) 2166 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 2167 2168 // Check that flags are not ignored by another flag 2169 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 2170 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 2171 startSpecifier, specifierLen); 2172 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 2173 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 2174 startSpecifier, specifierLen); 2175 2176 // Check the length modifier is valid with the given conversion specifier. 2177 const LengthModifier &LM = FS.getLengthModifier(); 2178 if (!FS.hasValidLengthModifier()) 2179 EmitFormatDiagnostic(S.PDiag(diag::warn_format_nonsensical_length) 2180 << LM.toString() << CS.toString(), 2181 getLocationOfByte(LM.getStart()), 2182 /*IsStringLocation*/true, 2183 getSpecifierRange(startSpecifier, specifierLen), 2184 FixItHint::CreateRemoval( 2185 getSpecifierRange(LM.getStart(), 2186 LM.getLength()))); 2187 2188 // Are we using '%n'? 2189 if (CS.getKind() == ConversionSpecifier::nArg) { 2190 // Issue a warning about this being a possible security issue. 2191 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_write_back), 2192 getLocationOfByte(CS.getStart()), 2193 /*IsStringLocation*/true, 2194 getSpecifierRange(startSpecifier, specifierLen)); 2195 // Continue checking the other format specifiers. 2196 return true; 2197 } 2198 2199 // The remaining checks depend on the data arguments. 2200 if (HasVAListArg) 2201 return true; 2202 2203 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 2204 return false; 2205 2206 // Now type check the data expression that matches the 2207 // format specifier. 2208 const Expr *Ex = getDataArg(argIndex); 2209 const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context); 2210 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) { 2211 // Check if we didn't match because of an implicit cast from a 'char' 2212 // or 'short' to an 'int'. This is done because printf is a varargs 2213 // function. 2214 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex)) 2215 if (ICE->getType() == S.Context.IntTy) { 2216 // All further checking is done on the subexpression. 2217 Ex = ICE->getSubExpr(); 2218 if (ATR.matchesType(S.Context, Ex->getType())) 2219 return true; 2220 } 2221 2222 // We may be able to offer a FixItHint if it is a supported type. 2223 PrintfSpecifier fixedFS = FS; 2224 bool success = fixedFS.fixType(Ex->getType(), S.getLangOptions()); 2225 2226 if (success) { 2227 // Get the fix string from the fixed format specifier 2228 llvm::SmallString<128> buf; 2229 llvm::raw_svector_ostream os(buf); 2230 fixedFS.toString(os); 2231 2232 // FIXME: getRepresentativeType() perhaps should return a string 2233 // instead of a QualType to better handle when the representative 2234 // type is 'wint_t' (which is defined in the system headers). 2235 EmitFormatDiagnostic( 2236 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch) 2237 << ATR.getRepresentativeType(S.Context) << Ex->getType() 2238 << Ex->getSourceRange(), 2239 getLocationOfByte(CS.getStart()), 2240 /*IsStringLocation*/true, 2241 getSpecifierRange(startSpecifier, specifierLen), 2242 FixItHint::CreateReplacement( 2243 getSpecifierRange(startSpecifier, specifierLen), 2244 os.str())); 2245 } 2246 else { 2247 S.Diag(getLocationOfByte(CS.getStart()), 2248 diag::warn_printf_conversion_argument_type_mismatch) 2249 << ATR.getRepresentativeType(S.Context) << Ex->getType() 2250 << getSpecifierRange(startSpecifier, specifierLen) 2251 << Ex->getSourceRange(); 2252 } 2253 } 2254 2255 return true; 2256} 2257 2258//===--- CHECK: Scanf format string checking ------------------------------===// 2259 2260namespace { 2261class CheckScanfHandler : public CheckFormatHandler { 2262public: 2263 CheckScanfHandler(Sema &s, const StringLiteral *fexpr, 2264 const Expr *origFormatExpr, unsigned firstDataArg, 2265 unsigned numDataArgs, bool isObjCLiteral, 2266 const char *beg, bool hasVAListArg, 2267 const CallExpr *theCall, unsigned formatIdx, 2268 bool inFunctionCall) 2269 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg, 2270 numDataArgs, isObjCLiteral, beg, hasVAListArg, 2271 theCall, formatIdx, inFunctionCall) {} 2272 2273 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 2274 const char *startSpecifier, 2275 unsigned specifierLen); 2276 2277 bool HandleInvalidScanfConversionSpecifier( 2278 const analyze_scanf::ScanfSpecifier &FS, 2279 const char *startSpecifier, 2280 unsigned specifierLen); 2281 2282 void HandleIncompleteScanList(const char *start, const char *end); 2283}; 2284} 2285 2286void CheckScanfHandler::HandleIncompleteScanList(const char *start, 2287 const char *end) { 2288 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 2289 getLocationOfByte(end), /*IsStringLocation*/true, 2290 getSpecifierRange(start, end - start)); 2291} 2292 2293bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 2294 const analyze_scanf::ScanfSpecifier &FS, 2295 const char *startSpecifier, 2296 unsigned specifierLen) { 2297 2298 const analyze_scanf::ScanfConversionSpecifier &CS = 2299 FS.getConversionSpecifier(); 2300 2301 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 2302 getLocationOfByte(CS.getStart()), 2303 startSpecifier, specifierLen, 2304 CS.getStart(), CS.getLength()); 2305} 2306 2307bool CheckScanfHandler::HandleScanfSpecifier( 2308 const analyze_scanf::ScanfSpecifier &FS, 2309 const char *startSpecifier, 2310 unsigned specifierLen) { 2311 2312 using namespace analyze_scanf; 2313 using namespace analyze_format_string; 2314 2315 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 2316 2317 // Handle case where '%' and '*' don't consume an argument. These shouldn't 2318 // be used to decide if we are using positional arguments consistently. 2319 if (FS.consumesDataArgument()) { 2320 if (atFirstArg) { 2321 atFirstArg = false; 2322 usesPositionalArgs = FS.usesPositionalArg(); 2323 } 2324 else if (usesPositionalArgs != FS.usesPositionalArg()) { 2325 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 2326 startSpecifier, specifierLen); 2327 return false; 2328 } 2329 } 2330 2331 // Check if the field with is non-zero. 2332 const OptionalAmount &Amt = FS.getFieldWidth(); 2333 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 2334 if (Amt.getConstantAmount() == 0) { 2335 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 2336 Amt.getConstantLength()); 2337 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 2338 getLocationOfByte(Amt.getStart()), 2339 /*IsStringLocation*/true, R, 2340 FixItHint::CreateRemoval(R)); 2341 } 2342 } 2343 2344 if (!FS.consumesDataArgument()) { 2345 // FIXME: Technically specifying a precision or field width here 2346 // makes no sense. Worth issuing a warning at some point. 2347 return true; 2348 } 2349 2350 // Consume the argument. 2351 unsigned argIndex = FS.getArgIndex(); 2352 if (argIndex < NumDataArgs) { 2353 // The check to see if the argIndex is valid will come later. 2354 // We set the bit here because we may exit early from this 2355 // function if we encounter some other error. 2356 CoveredArgs.set(argIndex); 2357 } 2358 2359 // Check the length modifier is valid with the given conversion specifier. 2360 const LengthModifier &LM = FS.getLengthModifier(); 2361 if (!FS.hasValidLengthModifier()) { 2362 S.Diag(getLocationOfByte(LM.getStart()), 2363 diag::warn_format_nonsensical_length) 2364 << LM.toString() << CS.toString() 2365 << getSpecifierRange(startSpecifier, specifierLen) 2366 << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(), 2367 LM.getLength())); 2368 } 2369 2370 // The remaining checks depend on the data arguments. 2371 if (HasVAListArg) 2372 return true; 2373 2374 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 2375 return false; 2376 2377 // FIXME: Check that the argument type matches the format specifier. 2378 2379 return true; 2380} 2381 2382void Sema::CheckFormatString(const StringLiteral *FExpr, 2383 const Expr *OrigFormatExpr, 2384 const CallExpr *TheCall, bool HasVAListArg, 2385 unsigned format_idx, unsigned firstDataArg, 2386 bool isPrintf, bool inFunctionCall) { 2387 2388 // CHECK: is the format string a wide literal? 2389 if (!FExpr->isAscii()) { 2390 CheckFormatHandler::EmitFormatDiagnostic( 2391 *this, inFunctionCall, TheCall->getArg(format_idx), 2392 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(), 2393 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 2394 return; 2395 } 2396 2397 // Str - The format string. NOTE: this is NOT null-terminated! 2398 StringRef StrRef = FExpr->getString(); 2399 const char *Str = StrRef.data(); 2400 unsigned StrLen = StrRef.size(); 2401 const unsigned numDataArgs = TheCall->getNumArgs() - firstDataArg; 2402 2403 // CHECK: empty format string? 2404 if (StrLen == 0 && numDataArgs > 0) { 2405 CheckFormatHandler::EmitFormatDiagnostic( 2406 *this, inFunctionCall, TheCall->getArg(format_idx), 2407 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(), 2408 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 2409 return; 2410 } 2411 2412 if (isPrintf) { 2413 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, 2414 numDataArgs, isa<ObjCStringLiteral>(OrigFormatExpr), 2415 Str, HasVAListArg, TheCall, format_idx, 2416 inFunctionCall); 2417 2418 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen)) 2419 H.DoneProcessing(); 2420 } 2421 else { 2422 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, 2423 numDataArgs, isa<ObjCStringLiteral>(OrigFormatExpr), 2424 Str, HasVAListArg, TheCall, format_idx, 2425 inFunctionCall); 2426 2427 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen)) 2428 H.DoneProcessing(); 2429 } 2430} 2431 2432//===--- CHECK: Standard memory functions ---------------------------------===// 2433 2434/// \brief Determine whether the given type is a dynamic class type (e.g., 2435/// whether it has a vtable). 2436static bool isDynamicClassType(QualType T) { 2437 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 2438 if (CXXRecordDecl *Definition = Record->getDefinition()) 2439 if (Definition->isDynamicClass()) 2440 return true; 2441 2442 return false; 2443} 2444 2445/// \brief If E is a sizeof expression, returns its argument expression, 2446/// otherwise returns NULL. 2447static const Expr *getSizeOfExprArg(const Expr* E) { 2448 if (const UnaryExprOrTypeTraitExpr *SizeOf = 2449 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 2450 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType()) 2451 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 2452 2453 return 0; 2454} 2455 2456/// \brief If E is a sizeof expression, returns its argument type. 2457static QualType getSizeOfArgType(const Expr* E) { 2458 if (const UnaryExprOrTypeTraitExpr *SizeOf = 2459 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 2460 if (SizeOf->getKind() == clang::UETT_SizeOf) 2461 return SizeOf->getTypeOfArgument(); 2462 2463 return QualType(); 2464} 2465 2466/// \brief Check for dangerous or invalid arguments to memset(). 2467/// 2468/// This issues warnings on known problematic, dangerous or unspecified 2469/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 2470/// function calls. 2471/// 2472/// \param Call The call expression to diagnose. 2473void Sema::CheckMemaccessArguments(const CallExpr *Call, 2474 CheckedMemoryFunction CMF, 2475 IdentifierInfo *FnName) { 2476 // It is possible to have a non-standard definition of memset. Validate 2477 // we have enough arguments, and if not, abort further checking. 2478 unsigned ExpectedNumArgs = (CMF == CMF_Strndup ? 2 : 3); 2479 if (Call->getNumArgs() < ExpectedNumArgs) 2480 return; 2481 2482 unsigned LastArg = (CMF == CMF_Memset || CMF == CMF_Strndup ? 1 : 2); 2483 unsigned LenArg = (CMF == CMF_Strndup ? 1 : 2); 2484 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 2485 2486 // We have special checking when the length is a sizeof expression. 2487 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 2488 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 2489 llvm::FoldingSetNodeID SizeOfArgID; 2490 2491 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 2492 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 2493 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 2494 2495 QualType DestTy = Dest->getType(); 2496 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 2497 QualType PointeeTy = DestPtrTy->getPointeeType(); 2498 2499 // Never warn about void type pointers. This can be used to suppress 2500 // false positives. 2501 if (PointeeTy->isVoidType()) 2502 continue; 2503 2504 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 2505 // actually comparing the expressions for equality. Because computing the 2506 // expression IDs can be expensive, we only do this if the diagnostic is 2507 // enabled. 2508 if (SizeOfArg && 2509 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess, 2510 SizeOfArg->getExprLoc())) { 2511 // We only compute IDs for expressions if the warning is enabled, and 2512 // cache the sizeof arg's ID. 2513 if (SizeOfArgID == llvm::FoldingSetNodeID()) 2514 SizeOfArg->Profile(SizeOfArgID, Context, true); 2515 llvm::FoldingSetNodeID DestID; 2516 Dest->Profile(DestID, Context, true); 2517 if (DestID == SizeOfArgID) { 2518 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 2519 // over sizeof(src) as well. 2520 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 2521 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 2522 if (UnaryOp->getOpcode() == UO_AddrOf) 2523 ActionIdx = 1; // If its an address-of operator, just remove it. 2524 if (Context.getTypeSize(PointeeTy) == Context.getCharWidth()) 2525 ActionIdx = 2; // If the pointee's size is sizeof(char), 2526 // suggest an explicit length. 2527 unsigned DestSrcSelect = (CMF == CMF_Strndup ? 1 : ArgIdx); 2528 DiagRuntimeBehavior(SizeOfArg->getExprLoc(), Dest, 2529 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 2530 << FnName << DestSrcSelect << ActionIdx 2531 << Dest->getSourceRange() 2532 << SizeOfArg->getSourceRange()); 2533 break; 2534 } 2535 } 2536 2537 // Also check for cases where the sizeof argument is the exact same 2538 // type as the memory argument, and where it points to a user-defined 2539 // record type. 2540 if (SizeOfArgTy != QualType()) { 2541 if (PointeeTy->isRecordType() && 2542 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 2543 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 2544 PDiag(diag::warn_sizeof_pointer_type_memaccess) 2545 << FnName << SizeOfArgTy << ArgIdx 2546 << PointeeTy << Dest->getSourceRange() 2547 << LenExpr->getSourceRange()); 2548 break; 2549 } 2550 } 2551 2552 // Always complain about dynamic classes. 2553 if (isDynamicClassType(PointeeTy)) 2554 DiagRuntimeBehavior( 2555 Dest->getExprLoc(), Dest, 2556 PDiag(diag::warn_dyn_class_memaccess) 2557 << (CMF == CMF_Memcmp ? ArgIdx + 2 : ArgIdx) << FnName << PointeeTy 2558 // "overwritten" if we're warning about the destination for any call 2559 // but memcmp; otherwise a verb appropriate to the call. 2560 << (ArgIdx == 0 && CMF != CMF_Memcmp ? 0 : (unsigned)CMF) 2561 << Call->getCallee()->getSourceRange()); 2562 else if (PointeeTy.hasNonTrivialObjCLifetime() && CMF != CMF_Memset) 2563 DiagRuntimeBehavior( 2564 Dest->getExprLoc(), Dest, 2565 PDiag(diag::warn_arc_object_memaccess) 2566 << ArgIdx << FnName << PointeeTy 2567 << Call->getCallee()->getSourceRange()); 2568 else 2569 continue; 2570 2571 DiagRuntimeBehavior( 2572 Dest->getExprLoc(), Dest, 2573 PDiag(diag::note_bad_memaccess_silence) 2574 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 2575 break; 2576 } 2577 } 2578} 2579 2580// A little helper routine: ignore addition and subtraction of integer literals. 2581// This intentionally does not ignore all integer constant expressions because 2582// we don't want to remove sizeof(). 2583static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 2584 Ex = Ex->IgnoreParenCasts(); 2585 2586 for (;;) { 2587 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 2588 if (!BO || !BO->isAdditiveOp()) 2589 break; 2590 2591 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 2592 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 2593 2594 if (isa<IntegerLiteral>(RHS)) 2595 Ex = LHS; 2596 else if (isa<IntegerLiteral>(LHS)) 2597 Ex = RHS; 2598 else 2599 break; 2600 } 2601 2602 return Ex; 2603} 2604 2605// Warn if the user has made the 'size' argument to strlcpy or strlcat 2606// be the size of the source, instead of the destination. 2607void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 2608 IdentifierInfo *FnName) { 2609 2610 // Don't crash if the user has the wrong number of arguments 2611 if (Call->getNumArgs() != 3) 2612 return; 2613 2614 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 2615 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 2616 const Expr *CompareWithSrc = NULL; 2617 2618 // Look for 'strlcpy(dst, x, sizeof(x))' 2619 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 2620 CompareWithSrc = Ex; 2621 else { 2622 // Look for 'strlcpy(dst, x, strlen(x))' 2623 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 2624 if (SizeCall->isBuiltinCall() == Builtin::BIstrlen 2625 && SizeCall->getNumArgs() == 1) 2626 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 2627 } 2628 } 2629 2630 if (!CompareWithSrc) 2631 return; 2632 2633 // Determine if the argument to sizeof/strlen is equal to the source 2634 // argument. In principle there's all kinds of things you could do 2635 // here, for instance creating an == expression and evaluating it with 2636 // EvaluateAsBooleanCondition, but this uses a more direct technique: 2637 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 2638 if (!SrcArgDRE) 2639 return; 2640 2641 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 2642 if (!CompareWithSrcDRE || 2643 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 2644 return; 2645 2646 const Expr *OriginalSizeArg = Call->getArg(2); 2647 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size) 2648 << OriginalSizeArg->getSourceRange() << FnName; 2649 2650 // Output a FIXIT hint if the destination is an array (rather than a 2651 // pointer to an array). This could be enhanced to handle some 2652 // pointers if we know the actual size, like if DstArg is 'array+2' 2653 // we could say 'sizeof(array)-2'. 2654 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 2655 QualType DstArgTy = DstArg->getType(); 2656 2657 // Only handle constant-sized or VLAs, but not flexible members. 2658 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(DstArgTy)) { 2659 // Only issue the FIXIT for arrays of size > 1. 2660 if (CAT->getSize().getSExtValue() <= 1) 2661 return; 2662 } else if (!DstArgTy->isVariableArrayType()) { 2663 return; 2664 } 2665 2666 llvm::SmallString<128> sizeString; 2667 llvm::raw_svector_ostream OS(sizeString); 2668 OS << "sizeof("; 2669 DstArg->printPretty(OS, Context, 0, getPrintingPolicy()); 2670 OS << ")"; 2671 2672 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size) 2673 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 2674 OS.str()); 2675} 2676 2677//===--- CHECK: Return Address of Stack Variable --------------------------===// 2678 2679static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars); 2680static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars); 2681 2682/// CheckReturnStackAddr - Check if a return statement returns the address 2683/// of a stack variable. 2684void 2685Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType, 2686 SourceLocation ReturnLoc) { 2687 2688 Expr *stackE = 0; 2689 SmallVector<DeclRefExpr *, 8> refVars; 2690 2691 // Perform checking for returned stack addresses, local blocks, 2692 // label addresses or references to temporaries. 2693 if (lhsType->isPointerType() || 2694 (!getLangOptions().ObjCAutoRefCount && lhsType->isBlockPointerType())) { 2695 stackE = EvalAddr(RetValExp, refVars); 2696 } else if (lhsType->isReferenceType()) { 2697 stackE = EvalVal(RetValExp, refVars); 2698 } 2699 2700 if (stackE == 0) 2701 return; // Nothing suspicious was found. 2702 2703 SourceLocation diagLoc; 2704 SourceRange diagRange; 2705 if (refVars.empty()) { 2706 diagLoc = stackE->getLocStart(); 2707 diagRange = stackE->getSourceRange(); 2708 } else { 2709 // We followed through a reference variable. 'stackE' contains the 2710 // problematic expression but we will warn at the return statement pointing 2711 // at the reference variable. We will later display the "trail" of 2712 // reference variables using notes. 2713 diagLoc = refVars[0]->getLocStart(); 2714 diagRange = refVars[0]->getSourceRange(); 2715 } 2716 2717 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var. 2718 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref 2719 : diag::warn_ret_stack_addr) 2720 << DR->getDecl()->getDeclName() << diagRange; 2721 } else if (isa<BlockExpr>(stackE)) { // local block. 2722 Diag(diagLoc, diag::err_ret_local_block) << diagRange; 2723 } else if (isa<AddrLabelExpr>(stackE)) { // address of label. 2724 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange; 2725 } else { // local temporary. 2726 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref 2727 : diag::warn_ret_local_temp_addr) 2728 << diagRange; 2729 } 2730 2731 // Display the "trail" of reference variables that we followed until we 2732 // found the problematic expression using notes. 2733 for (unsigned i = 0, e = refVars.size(); i != e; ++i) { 2734 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl()); 2735 // If this var binds to another reference var, show the range of the next 2736 // var, otherwise the var binds to the problematic expression, in which case 2737 // show the range of the expression. 2738 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange() 2739 : stackE->getSourceRange(); 2740 Diag(VD->getLocation(), diag::note_ref_var_local_bind) 2741 << VD->getDeclName() << range; 2742 } 2743} 2744 2745/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that 2746/// check if the expression in a return statement evaluates to an address 2747/// to a location on the stack, a local block, an address of a label, or a 2748/// reference to local temporary. The recursion is used to traverse the 2749/// AST of the return expression, with recursion backtracking when we 2750/// encounter a subexpression that (1) clearly does not lead to one of the 2751/// above problematic expressions (2) is something we cannot determine leads to 2752/// a problematic expression based on such local checking. 2753/// 2754/// Both EvalAddr and EvalVal follow through reference variables to evaluate 2755/// the expression that they point to. Such variables are added to the 2756/// 'refVars' vector so that we know what the reference variable "trail" was. 2757/// 2758/// EvalAddr processes expressions that are pointers that are used as 2759/// references (and not L-values). EvalVal handles all other values. 2760/// At the base case of the recursion is a check for the above problematic 2761/// expressions. 2762/// 2763/// This implementation handles: 2764/// 2765/// * pointer-to-pointer casts 2766/// * implicit conversions from array references to pointers 2767/// * taking the address of fields 2768/// * arbitrary interplay between "&" and "*" operators 2769/// * pointer arithmetic from an address of a stack variable 2770/// * taking the address of an array element where the array is on the stack 2771static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars) { 2772 if (E->isTypeDependent()) 2773 return NULL; 2774 2775 // We should only be called for evaluating pointer expressions. 2776 assert((E->getType()->isAnyPointerType() || 2777 E->getType()->isBlockPointerType() || 2778 E->getType()->isObjCQualifiedIdType()) && 2779 "EvalAddr only works on pointers"); 2780 2781 E = E->IgnoreParens(); 2782 2783 // Our "symbolic interpreter" is just a dispatch off the currently 2784 // viewed AST node. We then recursively traverse the AST by calling 2785 // EvalAddr and EvalVal appropriately. 2786 switch (E->getStmtClass()) { 2787 case Stmt::DeclRefExprClass: { 2788 DeclRefExpr *DR = cast<DeclRefExpr>(E); 2789 2790 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) 2791 // If this is a reference variable, follow through to the expression that 2792 // it points to. 2793 if (V->hasLocalStorage() && 2794 V->getType()->isReferenceType() && V->hasInit()) { 2795 // Add the reference variable to the "trail". 2796 refVars.push_back(DR); 2797 return EvalAddr(V->getInit(), refVars); 2798 } 2799 2800 return NULL; 2801 } 2802 2803 case Stmt::UnaryOperatorClass: { 2804 // The only unary operator that make sense to handle here 2805 // is AddrOf. All others don't make sense as pointers. 2806 UnaryOperator *U = cast<UnaryOperator>(E); 2807 2808 if (U->getOpcode() == UO_AddrOf) 2809 return EvalVal(U->getSubExpr(), refVars); 2810 else 2811 return NULL; 2812 } 2813 2814 case Stmt::BinaryOperatorClass: { 2815 // Handle pointer arithmetic. All other binary operators are not valid 2816 // in this context. 2817 BinaryOperator *B = cast<BinaryOperator>(E); 2818 BinaryOperatorKind op = B->getOpcode(); 2819 2820 if (op != BO_Add && op != BO_Sub) 2821 return NULL; 2822 2823 Expr *Base = B->getLHS(); 2824 2825 // Determine which argument is the real pointer base. It could be 2826 // the RHS argument instead of the LHS. 2827 if (!Base->getType()->isPointerType()) Base = B->getRHS(); 2828 2829 assert (Base->getType()->isPointerType()); 2830 return EvalAddr(Base, refVars); 2831 } 2832 2833 // For conditional operators we need to see if either the LHS or RHS are 2834 // valid DeclRefExpr*s. If one of them is valid, we return it. 2835 case Stmt::ConditionalOperatorClass: { 2836 ConditionalOperator *C = cast<ConditionalOperator>(E); 2837 2838 // Handle the GNU extension for missing LHS. 2839 if (Expr *lhsExpr = C->getLHS()) { 2840 // In C++, we can have a throw-expression, which has 'void' type. 2841 if (!lhsExpr->getType()->isVoidType()) 2842 if (Expr* LHS = EvalAddr(lhsExpr, refVars)) 2843 return LHS; 2844 } 2845 2846 // In C++, we can have a throw-expression, which has 'void' type. 2847 if (C->getRHS()->getType()->isVoidType()) 2848 return NULL; 2849 2850 return EvalAddr(C->getRHS(), refVars); 2851 } 2852 2853 case Stmt::BlockExprClass: 2854 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures()) 2855 return E; // local block. 2856 return NULL; 2857 2858 case Stmt::AddrLabelExprClass: 2859 return E; // address of label. 2860 2861 case Stmt::ExprWithCleanupsClass: 2862 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars); 2863 2864 // For casts, we need to handle conversions from arrays to 2865 // pointer values, and pointer-to-pointer conversions. 2866 case Stmt::ImplicitCastExprClass: 2867 case Stmt::CStyleCastExprClass: 2868 case Stmt::CXXFunctionalCastExprClass: 2869 case Stmt::ObjCBridgedCastExprClass: { 2870 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr(); 2871 QualType T = SubExpr->getType(); 2872 2873 if (SubExpr->getType()->isPointerType() || 2874 SubExpr->getType()->isBlockPointerType() || 2875 SubExpr->getType()->isObjCQualifiedIdType()) 2876 return EvalAddr(SubExpr, refVars); 2877 else if (T->isArrayType()) 2878 return EvalVal(SubExpr, refVars); 2879 else 2880 return 0; 2881 } 2882 2883 // C++ casts. For dynamic casts, static casts, and const casts, we 2884 // are always converting from a pointer-to-pointer, so we just blow 2885 // through the cast. In the case the dynamic cast doesn't fail (and 2886 // return NULL), we take the conservative route and report cases 2887 // where we return the address of a stack variable. For Reinterpre 2888 // FIXME: The comment about is wrong; we're not always converting 2889 // from pointer to pointer. I'm guessing that this code should also 2890 // handle references to objects. 2891 case Stmt::CXXStaticCastExprClass: 2892 case Stmt::CXXDynamicCastExprClass: 2893 case Stmt::CXXConstCastExprClass: 2894 case Stmt::CXXReinterpretCastExprClass: { 2895 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr(); 2896 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType()) 2897 return EvalAddr(S, refVars); 2898 else 2899 return NULL; 2900 } 2901 2902 case Stmt::MaterializeTemporaryExprClass: 2903 if (Expr *Result = EvalAddr( 2904 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 2905 refVars)) 2906 return Result; 2907 2908 return E; 2909 2910 // Everything else: we simply don't reason about them. 2911 default: 2912 return NULL; 2913 } 2914} 2915 2916 2917/// EvalVal - This function is complements EvalAddr in the mutual recursion. 2918/// See the comments for EvalAddr for more details. 2919static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars) { 2920do { 2921 // We should only be called for evaluating non-pointer expressions, or 2922 // expressions with a pointer type that are not used as references but instead 2923 // are l-values (e.g., DeclRefExpr with a pointer type). 2924 2925 // Our "symbolic interpreter" is just a dispatch off the currently 2926 // viewed AST node. We then recursively traverse the AST by calling 2927 // EvalAddr and EvalVal appropriately. 2928 2929 E = E->IgnoreParens(); 2930 switch (E->getStmtClass()) { 2931 case Stmt::ImplicitCastExprClass: { 2932 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E); 2933 if (IE->getValueKind() == VK_LValue) { 2934 E = IE->getSubExpr(); 2935 continue; 2936 } 2937 return NULL; 2938 } 2939 2940 case Stmt::ExprWithCleanupsClass: 2941 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars); 2942 2943 case Stmt::DeclRefExprClass: { 2944 // When we hit a DeclRefExpr we are looking at code that refers to a 2945 // variable's name. If it's not a reference variable we check if it has 2946 // local storage within the function, and if so, return the expression. 2947 DeclRefExpr *DR = cast<DeclRefExpr>(E); 2948 2949 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) 2950 if (V->hasLocalStorage()) { 2951 if (!V->getType()->isReferenceType()) 2952 return DR; 2953 2954 // Reference variable, follow through to the expression that 2955 // it points to. 2956 if (V->hasInit()) { 2957 // Add the reference variable to the "trail". 2958 refVars.push_back(DR); 2959 return EvalVal(V->getInit(), refVars); 2960 } 2961 } 2962 2963 return NULL; 2964 } 2965 2966 case Stmt::UnaryOperatorClass: { 2967 // The only unary operator that make sense to handle here 2968 // is Deref. All others don't resolve to a "name." This includes 2969 // handling all sorts of rvalues passed to a unary operator. 2970 UnaryOperator *U = cast<UnaryOperator>(E); 2971 2972 if (U->getOpcode() == UO_Deref) 2973 return EvalAddr(U->getSubExpr(), refVars); 2974 2975 return NULL; 2976 } 2977 2978 case Stmt::ArraySubscriptExprClass: { 2979 // Array subscripts are potential references to data on the stack. We 2980 // retrieve the DeclRefExpr* for the array variable if it indeed 2981 // has local storage. 2982 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars); 2983 } 2984 2985 case Stmt::ConditionalOperatorClass: { 2986 // For conditional operators we need to see if either the LHS or RHS are 2987 // non-NULL Expr's. If one is non-NULL, we return it. 2988 ConditionalOperator *C = cast<ConditionalOperator>(E); 2989 2990 // Handle the GNU extension for missing LHS. 2991 if (Expr *lhsExpr = C->getLHS()) 2992 if (Expr *LHS = EvalVal(lhsExpr, refVars)) 2993 return LHS; 2994 2995 return EvalVal(C->getRHS(), refVars); 2996 } 2997 2998 // Accesses to members are potential references to data on the stack. 2999 case Stmt::MemberExprClass: { 3000 MemberExpr *M = cast<MemberExpr>(E); 3001 3002 // Check for indirect access. We only want direct field accesses. 3003 if (M->isArrow()) 3004 return NULL; 3005 3006 // Check whether the member type is itself a reference, in which case 3007 // we're not going to refer to the member, but to what the member refers to. 3008 if (M->getMemberDecl()->getType()->isReferenceType()) 3009 return NULL; 3010 3011 return EvalVal(M->getBase(), refVars); 3012 } 3013 3014 case Stmt::MaterializeTemporaryExprClass: 3015 if (Expr *Result = EvalVal( 3016 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 3017 refVars)) 3018 return Result; 3019 3020 return E; 3021 3022 default: 3023 // Check that we don't return or take the address of a reference to a 3024 // temporary. This is only useful in C++. 3025 if (!E->isTypeDependent() && E->isRValue()) 3026 return E; 3027 3028 // Everything else: we simply don't reason about them. 3029 return NULL; 3030 } 3031} while (true); 3032} 3033 3034//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 3035 3036/// Check for comparisons of floating point operands using != and ==. 3037/// Issue a warning if these are no self-comparisons, as they are not likely 3038/// to do what the programmer intended. 3039void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 3040 bool EmitWarning = true; 3041 3042 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 3043 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 3044 3045 // Special case: check for x == x (which is OK). 3046 // Do not emit warnings for such cases. 3047 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 3048 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 3049 if (DRL->getDecl() == DRR->getDecl()) 3050 EmitWarning = false; 3051 3052 3053 // Special case: check for comparisons against literals that can be exactly 3054 // represented by APFloat. In such cases, do not emit a warning. This 3055 // is a heuristic: often comparison against such literals are used to 3056 // detect if a value in a variable has not changed. This clearly can 3057 // lead to false negatives. 3058 if (EmitWarning) { 3059 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 3060 if (FLL->isExact()) 3061 EmitWarning = false; 3062 } else 3063 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){ 3064 if (FLR->isExact()) 3065 EmitWarning = false; 3066 } 3067 } 3068 3069 // Check for comparisons with builtin types. 3070 if (EmitWarning) 3071 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 3072 if (CL->isBuiltinCall()) 3073 EmitWarning = false; 3074 3075 if (EmitWarning) 3076 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 3077 if (CR->isBuiltinCall()) 3078 EmitWarning = false; 3079 3080 // Emit the diagnostic. 3081 if (EmitWarning) 3082 Diag(Loc, diag::warn_floatingpoint_eq) 3083 << LHS->getSourceRange() << RHS->getSourceRange(); 3084} 3085 3086//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 3087//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 3088 3089namespace { 3090 3091/// Structure recording the 'active' range of an integer-valued 3092/// expression. 3093struct IntRange { 3094 /// The number of bits active in the int. 3095 unsigned Width; 3096 3097 /// True if the int is known not to have negative values. 3098 bool NonNegative; 3099 3100 IntRange(unsigned Width, bool NonNegative) 3101 : Width(Width), NonNegative(NonNegative) 3102 {} 3103 3104 /// Returns the range of the bool type. 3105 static IntRange forBoolType() { 3106 return IntRange(1, true); 3107 } 3108 3109 /// Returns the range of an opaque value of the given integral type. 3110 static IntRange forValueOfType(ASTContext &C, QualType T) { 3111 return forValueOfCanonicalType(C, 3112 T->getCanonicalTypeInternal().getTypePtr()); 3113 } 3114 3115 /// Returns the range of an opaque value of a canonical integral type. 3116 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 3117 assert(T->isCanonicalUnqualified()); 3118 3119 if (const VectorType *VT = dyn_cast<VectorType>(T)) 3120 T = VT->getElementType().getTypePtr(); 3121 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 3122 T = CT->getElementType().getTypePtr(); 3123 3124 // For enum types, use the known bit width of the enumerators. 3125 if (const EnumType *ET = dyn_cast<EnumType>(T)) { 3126 EnumDecl *Enum = ET->getDecl(); 3127 if (!Enum->isCompleteDefinition()) 3128 return IntRange(C.getIntWidth(QualType(T, 0)), false); 3129 3130 unsigned NumPositive = Enum->getNumPositiveBits(); 3131 unsigned NumNegative = Enum->getNumNegativeBits(); 3132 3133 return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0); 3134 } 3135 3136 const BuiltinType *BT = cast<BuiltinType>(T); 3137 assert(BT->isInteger()); 3138 3139 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 3140 } 3141 3142 /// Returns the "target" range of a canonical integral type, i.e. 3143 /// the range of values expressible in the type. 3144 /// 3145 /// This matches forValueOfCanonicalType except that enums have the 3146 /// full range of their type, not the range of their enumerators. 3147 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 3148 assert(T->isCanonicalUnqualified()); 3149 3150 if (const VectorType *VT = dyn_cast<VectorType>(T)) 3151 T = VT->getElementType().getTypePtr(); 3152 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 3153 T = CT->getElementType().getTypePtr(); 3154 if (const EnumType *ET = dyn_cast<EnumType>(T)) 3155 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 3156 3157 const BuiltinType *BT = cast<BuiltinType>(T); 3158 assert(BT->isInteger()); 3159 3160 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 3161 } 3162 3163 /// Returns the supremum of two ranges: i.e. their conservative merge. 3164 static IntRange join(IntRange L, IntRange R) { 3165 return IntRange(std::max(L.Width, R.Width), 3166 L.NonNegative && R.NonNegative); 3167 } 3168 3169 /// Returns the infinum of two ranges: i.e. their aggressive merge. 3170 static IntRange meet(IntRange L, IntRange R) { 3171 return IntRange(std::min(L.Width, R.Width), 3172 L.NonNegative || R.NonNegative); 3173 } 3174}; 3175 3176IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) { 3177 if (value.isSigned() && value.isNegative()) 3178 return IntRange(value.getMinSignedBits(), false); 3179 3180 if (value.getBitWidth() > MaxWidth) 3181 value = value.trunc(MaxWidth); 3182 3183 // isNonNegative() just checks the sign bit without considering 3184 // signedness. 3185 return IntRange(value.getActiveBits(), true); 3186} 3187 3188IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 3189 unsigned MaxWidth) { 3190 if (result.isInt()) 3191 return GetValueRange(C, result.getInt(), MaxWidth); 3192 3193 if (result.isVector()) { 3194 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 3195 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 3196 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 3197 R = IntRange::join(R, El); 3198 } 3199 return R; 3200 } 3201 3202 if (result.isComplexInt()) { 3203 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 3204 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 3205 return IntRange::join(R, I); 3206 } 3207 3208 // This can happen with lossless casts to intptr_t of "based" lvalues. 3209 // Assume it might use arbitrary bits. 3210 // FIXME: The only reason we need to pass the type in here is to get 3211 // the sign right on this one case. It would be nice if APValue 3212 // preserved this. 3213 assert(result.isLValue()); 3214 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 3215} 3216 3217/// Pseudo-evaluate the given integer expression, estimating the 3218/// range of values it might take. 3219/// 3220/// \param MaxWidth - the width to which the value will be truncated 3221IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) { 3222 E = E->IgnoreParens(); 3223 3224 // Try a full evaluation first. 3225 Expr::EvalResult result; 3226 if (E->EvaluateAsRValue(result, C)) 3227 return GetValueRange(C, result.Val, E->getType(), MaxWidth); 3228 3229 // I think we only want to look through implicit casts here; if the 3230 // user has an explicit widening cast, we should treat the value as 3231 // being of the new, wider type. 3232 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) { 3233 if (CE->getCastKind() == CK_NoOp) 3234 return GetExprRange(C, CE->getSubExpr(), MaxWidth); 3235 3236 IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType()); 3237 3238 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast); 3239 3240 // Assume that non-integer casts can span the full range of the type. 3241 if (!isIntegerCast) 3242 return OutputTypeRange; 3243 3244 IntRange SubRange 3245 = GetExprRange(C, CE->getSubExpr(), 3246 std::min(MaxWidth, OutputTypeRange.Width)); 3247 3248 // Bail out if the subexpr's range is as wide as the cast type. 3249 if (SubRange.Width >= OutputTypeRange.Width) 3250 return OutputTypeRange; 3251 3252 // Otherwise, we take the smaller width, and we're non-negative if 3253 // either the output type or the subexpr is. 3254 return IntRange(SubRange.Width, 3255 SubRange.NonNegative || OutputTypeRange.NonNegative); 3256 } 3257 3258 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 3259 // If we can fold the condition, just take that operand. 3260 bool CondResult; 3261 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 3262 return GetExprRange(C, CondResult ? CO->getTrueExpr() 3263 : CO->getFalseExpr(), 3264 MaxWidth); 3265 3266 // Otherwise, conservatively merge. 3267 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth); 3268 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth); 3269 return IntRange::join(L, R); 3270 } 3271 3272 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 3273 switch (BO->getOpcode()) { 3274 3275 // Boolean-valued operations are single-bit and positive. 3276 case BO_LAnd: 3277 case BO_LOr: 3278 case BO_LT: 3279 case BO_GT: 3280 case BO_LE: 3281 case BO_GE: 3282 case BO_EQ: 3283 case BO_NE: 3284 return IntRange::forBoolType(); 3285 3286 // The type of the assignments is the type of the LHS, so the RHS 3287 // is not necessarily the same type. 3288 case BO_MulAssign: 3289 case BO_DivAssign: 3290 case BO_RemAssign: 3291 case BO_AddAssign: 3292 case BO_SubAssign: 3293 case BO_XorAssign: 3294 case BO_OrAssign: 3295 // TODO: bitfields? 3296 return IntRange::forValueOfType(C, E->getType()); 3297 3298 // Simple assignments just pass through the RHS, which will have 3299 // been coerced to the LHS type. 3300 case BO_Assign: 3301 // TODO: bitfields? 3302 return GetExprRange(C, BO->getRHS(), MaxWidth); 3303 3304 // Operations with opaque sources are black-listed. 3305 case BO_PtrMemD: 3306 case BO_PtrMemI: 3307 return IntRange::forValueOfType(C, E->getType()); 3308 3309 // Bitwise-and uses the *infinum* of the two source ranges. 3310 case BO_And: 3311 case BO_AndAssign: 3312 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth), 3313 GetExprRange(C, BO->getRHS(), MaxWidth)); 3314 3315 // Left shift gets black-listed based on a judgement call. 3316 case BO_Shl: 3317 // ...except that we want to treat '1 << (blah)' as logically 3318 // positive. It's an important idiom. 3319 if (IntegerLiteral *I 3320 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 3321 if (I->getValue() == 1) { 3322 IntRange R = IntRange::forValueOfType(C, E->getType()); 3323 return IntRange(R.Width, /*NonNegative*/ true); 3324 } 3325 } 3326 // fallthrough 3327 3328 case BO_ShlAssign: 3329 return IntRange::forValueOfType(C, E->getType()); 3330 3331 // Right shift by a constant can narrow its left argument. 3332 case BO_Shr: 3333 case BO_ShrAssign: { 3334 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 3335 3336 // If the shift amount is a positive constant, drop the width by 3337 // that much. 3338 llvm::APSInt shift; 3339 if (BO->getRHS()->isIntegerConstantExpr(shift, C) && 3340 shift.isNonNegative()) { 3341 unsigned zext = shift.getZExtValue(); 3342 if (zext >= L.Width) 3343 L.Width = (L.NonNegative ? 0 : 1); 3344 else 3345 L.Width -= zext; 3346 } 3347 3348 return L; 3349 } 3350 3351 // Comma acts as its right operand. 3352 case BO_Comma: 3353 return GetExprRange(C, BO->getRHS(), MaxWidth); 3354 3355 // Black-list pointer subtractions. 3356 case BO_Sub: 3357 if (BO->getLHS()->getType()->isPointerType()) 3358 return IntRange::forValueOfType(C, E->getType()); 3359 break; 3360 3361 // The width of a division result is mostly determined by the size 3362 // of the LHS. 3363 case BO_Div: { 3364 // Don't 'pre-truncate' the operands. 3365 unsigned opWidth = C.getIntWidth(E->getType()); 3366 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 3367 3368 // If the divisor is constant, use that. 3369 llvm::APSInt divisor; 3370 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) { 3371 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor)) 3372 if (log2 >= L.Width) 3373 L.Width = (L.NonNegative ? 0 : 1); 3374 else 3375 L.Width = std::min(L.Width - log2, MaxWidth); 3376 return L; 3377 } 3378 3379 // Otherwise, just use the LHS's width. 3380 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 3381 return IntRange(L.Width, L.NonNegative && R.NonNegative); 3382 } 3383 3384 // The result of a remainder can't be larger than the result of 3385 // either side. 3386 case BO_Rem: { 3387 // Don't 'pre-truncate' the operands. 3388 unsigned opWidth = C.getIntWidth(E->getType()); 3389 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 3390 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 3391 3392 IntRange meet = IntRange::meet(L, R); 3393 meet.Width = std::min(meet.Width, MaxWidth); 3394 return meet; 3395 } 3396 3397 // The default behavior is okay for these. 3398 case BO_Mul: 3399 case BO_Add: 3400 case BO_Xor: 3401 case BO_Or: 3402 break; 3403 } 3404 3405 // The default case is to treat the operation as if it were closed 3406 // on the narrowest type that encompasses both operands. 3407 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 3408 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth); 3409 return IntRange::join(L, R); 3410 } 3411 3412 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 3413 switch (UO->getOpcode()) { 3414 // Boolean-valued operations are white-listed. 3415 case UO_LNot: 3416 return IntRange::forBoolType(); 3417 3418 // Operations with opaque sources are black-listed. 3419 case UO_Deref: 3420 case UO_AddrOf: // should be impossible 3421 return IntRange::forValueOfType(C, E->getType()); 3422 3423 default: 3424 return GetExprRange(C, UO->getSubExpr(), MaxWidth); 3425 } 3426 } 3427 3428 if (dyn_cast<OffsetOfExpr>(E)) { 3429 IntRange::forValueOfType(C, E->getType()); 3430 } 3431 3432 if (FieldDecl *BitField = E->getBitField()) 3433 return IntRange(BitField->getBitWidthValue(C), 3434 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 3435 3436 return IntRange::forValueOfType(C, E->getType()); 3437} 3438 3439IntRange GetExprRange(ASTContext &C, Expr *E) { 3440 return GetExprRange(C, E, C.getIntWidth(E->getType())); 3441} 3442 3443/// Checks whether the given value, which currently has the given 3444/// source semantics, has the same value when coerced through the 3445/// target semantics. 3446bool IsSameFloatAfterCast(const llvm::APFloat &value, 3447 const llvm::fltSemantics &Src, 3448 const llvm::fltSemantics &Tgt) { 3449 llvm::APFloat truncated = value; 3450 3451 bool ignored; 3452 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 3453 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 3454 3455 return truncated.bitwiseIsEqual(value); 3456} 3457 3458/// Checks whether the given value, which currently has the given 3459/// source semantics, has the same value when coerced through the 3460/// target semantics. 3461/// 3462/// The value might be a vector of floats (or a complex number). 3463bool IsSameFloatAfterCast(const APValue &value, 3464 const llvm::fltSemantics &Src, 3465 const llvm::fltSemantics &Tgt) { 3466 if (value.isFloat()) 3467 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 3468 3469 if (value.isVector()) { 3470 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 3471 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 3472 return false; 3473 return true; 3474 } 3475 3476 assert(value.isComplexFloat()); 3477 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 3478 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 3479} 3480 3481void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC); 3482 3483static bool IsZero(Sema &S, Expr *E) { 3484 // Suppress cases where we are comparing against an enum constant. 3485 if (const DeclRefExpr *DR = 3486 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 3487 if (isa<EnumConstantDecl>(DR->getDecl())) 3488 return false; 3489 3490 // Suppress cases where the '0' value is expanded from a macro. 3491 if (E->getLocStart().isMacroID()) 3492 return false; 3493 3494 llvm::APSInt Value; 3495 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0; 3496} 3497 3498static bool HasEnumType(Expr *E) { 3499 // Strip off implicit integral promotions. 3500 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 3501 if (ICE->getCastKind() != CK_IntegralCast && 3502 ICE->getCastKind() != CK_NoOp) 3503 break; 3504 E = ICE->getSubExpr(); 3505 } 3506 3507 return E->getType()->isEnumeralType(); 3508} 3509 3510void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) { 3511 BinaryOperatorKind op = E->getOpcode(); 3512 if (E->isValueDependent()) 3513 return; 3514 3515 if (op == BO_LT && IsZero(S, E->getRHS())) { 3516 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison) 3517 << "< 0" << "false" << HasEnumType(E->getLHS()) 3518 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 3519 } else if (op == BO_GE && IsZero(S, E->getRHS())) { 3520 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison) 3521 << ">= 0" << "true" << HasEnumType(E->getLHS()) 3522 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 3523 } else if (op == BO_GT && IsZero(S, E->getLHS())) { 3524 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison) 3525 << "0 >" << "false" << HasEnumType(E->getRHS()) 3526 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 3527 } else if (op == BO_LE && IsZero(S, E->getLHS())) { 3528 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison) 3529 << "0 <=" << "true" << HasEnumType(E->getRHS()) 3530 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 3531 } 3532} 3533 3534/// Analyze the operands of the given comparison. Implements the 3535/// fallback case from AnalyzeComparison. 3536void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 3537 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 3538 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 3539} 3540 3541/// \brief Implements -Wsign-compare. 3542/// 3543/// \param E the binary operator to check for warnings 3544void AnalyzeComparison(Sema &S, BinaryOperator *E) { 3545 // The type the comparison is being performed in. 3546 QualType T = E->getLHS()->getType(); 3547 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()) 3548 && "comparison with mismatched types"); 3549 3550 // We don't do anything special if this isn't an unsigned integral 3551 // comparison: we're only interested in integral comparisons, and 3552 // signed comparisons only happen in cases we don't care to warn about. 3553 // 3554 // We also don't care about value-dependent expressions or expressions 3555 // whose result is a constant. 3556 if (!T->hasUnsignedIntegerRepresentation() 3557 || E->isValueDependent() || E->isIntegerConstantExpr(S.Context)) 3558 return AnalyzeImpConvsInComparison(S, E); 3559 3560 Expr *LHS = E->getLHS()->IgnoreParenImpCasts(); 3561 Expr *RHS = E->getRHS()->IgnoreParenImpCasts(); 3562 3563 // Check to see if one of the (unmodified) operands is of different 3564 // signedness. 3565 Expr *signedOperand, *unsignedOperand; 3566 if (LHS->getType()->hasSignedIntegerRepresentation()) { 3567 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 3568 "unsigned comparison between two signed integer expressions?"); 3569 signedOperand = LHS; 3570 unsignedOperand = RHS; 3571 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 3572 signedOperand = RHS; 3573 unsignedOperand = LHS; 3574 } else { 3575 CheckTrivialUnsignedComparison(S, E); 3576 return AnalyzeImpConvsInComparison(S, E); 3577 } 3578 3579 // Otherwise, calculate the effective range of the signed operand. 3580 IntRange signedRange = GetExprRange(S.Context, signedOperand); 3581 3582 // Go ahead and analyze implicit conversions in the operands. Note 3583 // that we skip the implicit conversions on both sides. 3584 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 3585 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 3586 3587 // If the signed range is non-negative, -Wsign-compare won't fire, 3588 // but we should still check for comparisons which are always true 3589 // or false. 3590 if (signedRange.NonNegative) 3591 return CheckTrivialUnsignedComparison(S, E); 3592 3593 // For (in)equality comparisons, if the unsigned operand is a 3594 // constant which cannot collide with a overflowed signed operand, 3595 // then reinterpreting the signed operand as unsigned will not 3596 // change the result of the comparison. 3597 if (E->isEqualityOp()) { 3598 unsigned comparisonWidth = S.Context.getIntWidth(T); 3599 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand); 3600 3601 // We should never be unable to prove that the unsigned operand is 3602 // non-negative. 3603 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 3604 3605 if (unsignedRange.Width < comparisonWidth) 3606 return; 3607 } 3608 3609 S.Diag(E->getOperatorLoc(), diag::warn_mixed_sign_comparison) 3610 << LHS->getType() << RHS->getType() 3611 << LHS->getSourceRange() << RHS->getSourceRange(); 3612} 3613 3614/// Analyzes an attempt to assign the given value to a bitfield. 3615/// 3616/// Returns true if there was something fishy about the attempt. 3617bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 3618 SourceLocation InitLoc) { 3619 assert(Bitfield->isBitField()); 3620 if (Bitfield->isInvalidDecl()) 3621 return false; 3622 3623 // White-list bool bitfields. 3624 if (Bitfield->getType()->isBooleanType()) 3625 return false; 3626 3627 // Ignore value- or type-dependent expressions. 3628 if (Bitfield->getBitWidth()->isValueDependent() || 3629 Bitfield->getBitWidth()->isTypeDependent() || 3630 Init->isValueDependent() || 3631 Init->isTypeDependent()) 3632 return false; 3633 3634 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 3635 3636 Expr::EvalResult InitValue; 3637 if (!OriginalInit->EvaluateAsRValue(InitValue, S.Context) || 3638 !InitValue.Val.isInt()) 3639 return false; 3640 3641 const llvm::APSInt &Value = InitValue.Val.getInt(); 3642 unsigned OriginalWidth = Value.getBitWidth(); 3643 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 3644 3645 if (OriginalWidth <= FieldWidth) 3646 return false; 3647 3648 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 3649 3650 // It's fairly common to write values into signed bitfields 3651 // that, if sign-extended, would end up becoming a different 3652 // value. We don't want to warn about that. 3653 if (Value.isSigned() && Value.isNegative()) 3654 TruncatedValue = TruncatedValue.sext(OriginalWidth); 3655 else 3656 TruncatedValue = TruncatedValue.zext(OriginalWidth); 3657 3658 if (Value == TruncatedValue) 3659 return false; 3660 3661 std::string PrettyValue = Value.toString(10); 3662 std::string PrettyTrunc = TruncatedValue.toString(10); 3663 3664 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 3665 << PrettyValue << PrettyTrunc << OriginalInit->getType() 3666 << Init->getSourceRange(); 3667 3668 return true; 3669} 3670 3671/// Analyze the given simple or compound assignment for warning-worthy 3672/// operations. 3673void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 3674 // Just recurse on the LHS. 3675 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 3676 3677 // We want to recurse on the RHS as normal unless we're assigning to 3678 // a bitfield. 3679 if (FieldDecl *Bitfield = E->getLHS()->getBitField()) { 3680 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 3681 E->getOperatorLoc())) { 3682 // Recurse, ignoring any implicit conversions on the RHS. 3683 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 3684 E->getOperatorLoc()); 3685 } 3686 } 3687 3688 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 3689} 3690 3691/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 3692void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 3693 SourceLocation CContext, unsigned diag) { 3694 S.Diag(E->getExprLoc(), diag) 3695 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 3696} 3697 3698/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 3699void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext, 3700 unsigned diag) { 3701 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag); 3702} 3703 3704/// Diagnose an implicit cast from a literal expression. Does not warn when the 3705/// cast wouldn't lose information. 3706void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T, 3707 SourceLocation CContext) { 3708 // Try to convert the literal exactly to an integer. If we can, don't warn. 3709 bool isExact = false; 3710 const llvm::APFloat &Value = FL->getValue(); 3711 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 3712 T->hasUnsignedIntegerRepresentation()); 3713 if (Value.convertToInteger(IntegerValue, 3714 llvm::APFloat::rmTowardZero, &isExact) 3715 == llvm::APFloat::opOK && isExact) 3716 return; 3717 3718 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer) 3719 << FL->getType() << T << FL->getSourceRange() << SourceRange(CContext); 3720} 3721 3722std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) { 3723 if (!Range.Width) return "0"; 3724 3725 llvm::APSInt ValueInRange = Value; 3726 ValueInRange.setIsSigned(!Range.NonNegative); 3727 ValueInRange = ValueInRange.trunc(Range.Width); 3728 return ValueInRange.toString(10); 3729} 3730 3731static bool isFromSystemMacro(Sema &S, SourceLocation loc) { 3732 SourceManager &smgr = S.Context.getSourceManager(); 3733 return loc.isMacroID() && smgr.isInSystemHeader(smgr.getSpellingLoc(loc)); 3734} 3735 3736void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 3737 SourceLocation CC, bool *ICContext = 0) { 3738 if (E->isTypeDependent() || E->isValueDependent()) return; 3739 3740 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 3741 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 3742 if (Source == Target) return; 3743 if (Target->isDependentType()) return; 3744 3745 // If the conversion context location is invalid don't complain. We also 3746 // don't want to emit a warning if the issue occurs from the expansion of 3747 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 3748 // delay this check as long as possible. Once we detect we are in that 3749 // scenario, we just return. 3750 if (CC.isInvalid()) 3751 return; 3752 3753 // Diagnose implicit casts to bool. 3754 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 3755 if (isa<StringLiteral>(E)) 3756 // Warn on string literal to bool. Checks for string literals in logical 3757 // expressions, for instances, assert(0 && "error here"), is prevented 3758 // by a check in AnalyzeImplicitConversions(). 3759 return DiagnoseImpCast(S, E, T, CC, 3760 diag::warn_impcast_string_literal_to_bool); 3761 return; // Other casts to bool are not checked. 3762 } 3763 3764 // Strip vector types. 3765 if (isa<VectorType>(Source)) { 3766 if (!isa<VectorType>(Target)) { 3767 if (isFromSystemMacro(S, CC)) 3768 return; 3769 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 3770 } 3771 3772 // If the vector cast is cast between two vectors of the same size, it is 3773 // a bitcast, not a conversion. 3774 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 3775 return; 3776 3777 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 3778 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 3779 } 3780 3781 // Strip complex types. 3782 if (isa<ComplexType>(Source)) { 3783 if (!isa<ComplexType>(Target)) { 3784 if (isFromSystemMacro(S, CC)) 3785 return; 3786 3787 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar); 3788 } 3789 3790 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 3791 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 3792 } 3793 3794 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 3795 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 3796 3797 // If the source is floating point... 3798 if (SourceBT && SourceBT->isFloatingPoint()) { 3799 // ...and the target is floating point... 3800 if (TargetBT && TargetBT->isFloatingPoint()) { 3801 // ...then warn if we're dropping FP rank. 3802 3803 // Builtin FP kinds are ordered by increasing FP rank. 3804 if (SourceBT->getKind() > TargetBT->getKind()) { 3805 // Don't warn about float constants that are precisely 3806 // representable in the target type. 3807 Expr::EvalResult result; 3808 if (E->EvaluateAsRValue(result, S.Context)) { 3809 // Value might be a float, a float vector, or a float complex. 3810 if (IsSameFloatAfterCast(result.Val, 3811 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 3812 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 3813 return; 3814 } 3815 3816 if (isFromSystemMacro(S, CC)) 3817 return; 3818 3819 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 3820 } 3821 return; 3822 } 3823 3824 // If the target is integral, always warn. 3825 if ((TargetBT && TargetBT->isInteger())) { 3826 if (isFromSystemMacro(S, CC)) 3827 return; 3828 3829 Expr *InnerE = E->IgnoreParenImpCasts(); 3830 // We also want to warn on, e.g., "int i = -1.234" 3831 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 3832 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 3833 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 3834 3835 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) { 3836 DiagnoseFloatingLiteralImpCast(S, FL, T, CC); 3837 } else { 3838 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer); 3839 } 3840 } 3841 3842 return; 3843 } 3844 3845 if (!Source->isIntegerType() || !Target->isIntegerType()) 3846 return; 3847 3848 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) 3849 == Expr::NPCK_GNUNull) && Target->isIntegerType()) { 3850 S.Diag(E->getExprLoc(), diag::warn_impcast_null_pointer_to_integer) 3851 << E->getSourceRange() << clang::SourceRange(CC); 3852 return; 3853 } 3854 3855 IntRange SourceRange = GetExprRange(S.Context, E); 3856 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 3857 3858 if (SourceRange.Width > TargetRange.Width) { 3859 // If the source is a constant, use a default-on diagnostic. 3860 // TODO: this should happen for bitfield stores, too. 3861 llvm::APSInt Value(32); 3862 if (E->isIntegerConstantExpr(Value, S.Context)) { 3863 if (isFromSystemMacro(S, CC)) 3864 return; 3865 3866 std::string PrettySourceValue = Value.toString(10); 3867 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 3868 3869 S.DiagRuntimeBehavior(E->getExprLoc(), E, 3870 S.PDiag(diag::warn_impcast_integer_precision_constant) 3871 << PrettySourceValue << PrettyTargetValue 3872 << E->getType() << T << E->getSourceRange() 3873 << clang::SourceRange(CC)); 3874 return; 3875 } 3876 3877 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 3878 if (isFromSystemMacro(S, CC)) 3879 return; 3880 3881 if (SourceRange.Width == 64 && TargetRange.Width == 32) 3882 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32); 3883 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 3884 } 3885 3886 if ((TargetRange.NonNegative && !SourceRange.NonNegative) || 3887 (!TargetRange.NonNegative && SourceRange.NonNegative && 3888 SourceRange.Width == TargetRange.Width)) { 3889 3890 if (isFromSystemMacro(S, CC)) 3891 return; 3892 3893 unsigned DiagID = diag::warn_impcast_integer_sign; 3894 3895 // Traditionally, gcc has warned about this under -Wsign-compare. 3896 // We also want to warn about it in -Wconversion. 3897 // So if -Wconversion is off, use a completely identical diagnostic 3898 // in the sign-compare group. 3899 // The conditional-checking code will 3900 if (ICContext) { 3901 DiagID = diag::warn_impcast_integer_sign_conditional; 3902 *ICContext = true; 3903 } 3904 3905 return DiagnoseImpCast(S, E, T, CC, DiagID); 3906 } 3907 3908 // Diagnose conversions between different enumeration types. 3909 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 3910 // type, to give us better diagnostics. 3911 QualType SourceType = E->getType(); 3912 if (!S.getLangOptions().CPlusPlus) { 3913 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 3914 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 3915 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 3916 SourceType = S.Context.getTypeDeclType(Enum); 3917 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 3918 } 3919 } 3920 3921 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 3922 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 3923 if ((SourceEnum->getDecl()->getIdentifier() || 3924 SourceEnum->getDecl()->getTypedefNameForAnonDecl()) && 3925 (TargetEnum->getDecl()->getIdentifier() || 3926 TargetEnum->getDecl()->getTypedefNameForAnonDecl()) && 3927 SourceEnum != TargetEnum) { 3928 if (isFromSystemMacro(S, CC)) 3929 return; 3930 3931 return DiagnoseImpCast(S, E, SourceType, T, CC, 3932 diag::warn_impcast_different_enum_types); 3933 } 3934 3935 return; 3936} 3937 3938void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T); 3939 3940void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 3941 SourceLocation CC, bool &ICContext) { 3942 E = E->IgnoreParenImpCasts(); 3943 3944 if (isa<ConditionalOperator>(E)) 3945 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), T); 3946 3947 AnalyzeImplicitConversions(S, E, CC); 3948 if (E->getType() != T) 3949 return CheckImplicitConversion(S, E, T, CC, &ICContext); 3950 return; 3951} 3952 3953void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T) { 3954 SourceLocation CC = E->getQuestionLoc(); 3955 3956 AnalyzeImplicitConversions(S, E->getCond(), CC); 3957 3958 bool Suspicious = false; 3959 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious); 3960 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 3961 3962 // If -Wconversion would have warned about either of the candidates 3963 // for a signedness conversion to the context type... 3964 if (!Suspicious) return; 3965 3966 // ...but it's currently ignored... 3967 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional, 3968 CC)) 3969 return; 3970 3971 // ...then check whether it would have warned about either of the 3972 // candidates for a signedness conversion to the condition type. 3973 if (E->getType() == T) return; 3974 3975 Suspicious = false; 3976 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(), 3977 E->getType(), CC, &Suspicious); 3978 if (!Suspicious) 3979 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 3980 E->getType(), CC, &Suspicious); 3981} 3982 3983/// AnalyzeImplicitConversions - Find and report any interesting 3984/// implicit conversions in the given expression. There are a couple 3985/// of competing diagnostics here, -Wconversion and -Wsign-compare. 3986void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) { 3987 QualType T = OrigE->getType(); 3988 Expr *E = OrigE->IgnoreParenImpCasts(); 3989 3990 if (E->isTypeDependent() || E->isValueDependent()) 3991 return; 3992 3993 // For conditional operators, we analyze the arguments as if they 3994 // were being fed directly into the output. 3995 if (isa<ConditionalOperator>(E)) { 3996 ConditionalOperator *CO = cast<ConditionalOperator>(E); 3997 CheckConditionalOperator(S, CO, T); 3998 return; 3999 } 4000 4001 // Go ahead and check any implicit conversions we might have skipped. 4002 // The non-canonical typecheck is just an optimization; 4003 // CheckImplicitConversion will filter out dead implicit conversions. 4004 if (E->getType() != T) 4005 CheckImplicitConversion(S, E, T, CC); 4006 4007 // Now continue drilling into this expression. 4008 4009 // Skip past explicit casts. 4010 if (isa<ExplicitCastExpr>(E)) { 4011 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts(); 4012 return AnalyzeImplicitConversions(S, E, CC); 4013 } 4014 4015 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 4016 // Do a somewhat different check with comparison operators. 4017 if (BO->isComparisonOp()) 4018 return AnalyzeComparison(S, BO); 4019 4020 // And with assignments and compound assignments. 4021 if (BO->isAssignmentOp()) 4022 return AnalyzeAssignment(S, BO); 4023 } 4024 4025 // These break the otherwise-useful invariant below. Fortunately, 4026 // we don't really need to recurse into them, because any internal 4027 // expressions should have been analyzed already when they were 4028 // built into statements. 4029 if (isa<StmtExpr>(E)) return; 4030 4031 // Don't descend into unevaluated contexts. 4032 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 4033 4034 // Now just recurse over the expression's children. 4035 CC = E->getExprLoc(); 4036 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 4037 bool IsLogicalOperator = BO && BO->isLogicalOp(); 4038 for (Stmt::child_range I = E->children(); I; ++I) { 4039 Expr *ChildExpr = cast<Expr>(*I); 4040 if (IsLogicalOperator && 4041 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 4042 // Ignore checking string literals that are in logical operators. 4043 continue; 4044 AnalyzeImplicitConversions(S, ChildExpr, CC); 4045 } 4046} 4047 4048} // end anonymous namespace 4049 4050/// Diagnoses "dangerous" implicit conversions within the given 4051/// expression (which is a full expression). Implements -Wconversion 4052/// and -Wsign-compare. 4053/// 4054/// \param CC the "context" location of the implicit conversion, i.e. 4055/// the most location of the syntactic entity requiring the implicit 4056/// conversion 4057void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 4058 // Don't diagnose in unevaluated contexts. 4059 if (ExprEvalContexts.back().Context == Sema::Unevaluated) 4060 return; 4061 4062 // Don't diagnose for value- or type-dependent expressions. 4063 if (E->isTypeDependent() || E->isValueDependent()) 4064 return; 4065 4066 // Check for array bounds violations in cases where the check isn't triggered 4067 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 4068 // ArraySubscriptExpr is on the RHS of a variable initialization. 4069 CheckArrayAccess(E); 4070 4071 // This is not the right CC for (e.g.) a variable initialization. 4072 AnalyzeImplicitConversions(*this, E, CC); 4073} 4074 4075void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 4076 FieldDecl *BitField, 4077 Expr *Init) { 4078 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 4079} 4080 4081/// CheckParmsForFunctionDef - Check that the parameters of the given 4082/// function are appropriate for the definition of a function. This 4083/// takes care of any checks that cannot be performed on the 4084/// declaration itself, e.g., that the types of each of the function 4085/// parameters are complete. 4086bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd, 4087 bool CheckParameterNames) { 4088 bool HasInvalidParm = false; 4089 for (; P != PEnd; ++P) { 4090 ParmVarDecl *Param = *P; 4091 4092 // C99 6.7.5.3p4: the parameters in a parameter type list in a 4093 // function declarator that is part of a function definition of 4094 // that function shall not have incomplete type. 4095 // 4096 // This is also C++ [dcl.fct]p6. 4097 if (!Param->isInvalidDecl() && 4098 RequireCompleteType(Param->getLocation(), Param->getType(), 4099 diag::err_typecheck_decl_incomplete_type)) { 4100 Param->setInvalidDecl(); 4101 HasInvalidParm = true; 4102 } 4103 4104 // C99 6.9.1p5: If the declarator includes a parameter type list, the 4105 // declaration of each parameter shall include an identifier. 4106 if (CheckParameterNames && 4107 Param->getIdentifier() == 0 && 4108 !Param->isImplicit() && 4109 !getLangOptions().CPlusPlus) 4110 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 4111 4112 // C99 6.7.5.3p12: 4113 // If the function declarator is not part of a definition of that 4114 // function, parameters may have incomplete type and may use the [*] 4115 // notation in their sequences of declarator specifiers to specify 4116 // variable length array types. 4117 QualType PType = Param->getOriginalType(); 4118 if (const ArrayType *AT = Context.getAsArrayType(PType)) { 4119 if (AT->getSizeModifier() == ArrayType::Star) { 4120 // FIXME: This diagnosic should point the the '[*]' if source-location 4121 // information is added for it. 4122 Diag(Param->getLocation(), diag::err_array_star_in_function_definition); 4123 } 4124 } 4125 } 4126 4127 return HasInvalidParm; 4128} 4129 4130/// CheckCastAlign - Implements -Wcast-align, which warns when a 4131/// pointer cast increases the alignment requirements. 4132void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 4133 // This is actually a lot of work to potentially be doing on every 4134 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 4135 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align, 4136 TRange.getBegin()) 4137 == DiagnosticsEngine::Ignored) 4138 return; 4139 4140 // Ignore dependent types. 4141 if (T->isDependentType() || Op->getType()->isDependentType()) 4142 return; 4143 4144 // Require that the destination be a pointer type. 4145 const PointerType *DestPtr = T->getAs<PointerType>(); 4146 if (!DestPtr) return; 4147 4148 // If the destination has alignment 1, we're done. 4149 QualType DestPointee = DestPtr->getPointeeType(); 4150 if (DestPointee->isIncompleteType()) return; 4151 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 4152 if (DestAlign.isOne()) return; 4153 4154 // Require that the source be a pointer type. 4155 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 4156 if (!SrcPtr) return; 4157 QualType SrcPointee = SrcPtr->getPointeeType(); 4158 4159 // Whitelist casts from cv void*. We already implicitly 4160 // whitelisted casts to cv void*, since they have alignment 1. 4161 // Also whitelist casts involving incomplete types, which implicitly 4162 // includes 'void'. 4163 if (SrcPointee->isIncompleteType()) return; 4164 4165 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee); 4166 if (SrcAlign >= DestAlign) return; 4167 4168 Diag(TRange.getBegin(), diag::warn_cast_align) 4169 << Op->getType() << T 4170 << static_cast<unsigned>(SrcAlign.getQuantity()) 4171 << static_cast<unsigned>(DestAlign.getQuantity()) 4172 << TRange << Op->getSourceRange(); 4173} 4174 4175static const Type* getElementType(const Expr *BaseExpr) { 4176 const Type* EltType = BaseExpr->getType().getTypePtr(); 4177 if (EltType->isAnyPointerType()) 4178 return EltType->getPointeeType().getTypePtr(); 4179 else if (EltType->isArrayType()) 4180 return EltType->getBaseElementTypeUnsafe(); 4181 return EltType; 4182} 4183 4184/// \brief Check whether this array fits the idiom of a size-one tail padded 4185/// array member of a struct. 4186/// 4187/// We avoid emitting out-of-bounds access warnings for such arrays as they are 4188/// commonly used to emulate flexible arrays in C89 code. 4189static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size, 4190 const NamedDecl *ND) { 4191 if (Size != 1 || !ND) return false; 4192 4193 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 4194 if (!FD) return false; 4195 4196 // Don't consider sizes resulting from macro expansions or template argument 4197 // substitution to form C89 tail-padded arrays. 4198 ConstantArrayTypeLoc TL = 4199 cast<ConstantArrayTypeLoc>(FD->getTypeSourceInfo()->getTypeLoc()); 4200 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(TL.getSizeExpr()); 4201 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 4202 return false; 4203 4204 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 4205 if (!RD || !RD->isStruct()) 4206 return false; 4207 4208 // See if this is the last field decl in the record. 4209 const Decl *D = FD; 4210 while ((D = D->getNextDeclInContext())) 4211 if (isa<FieldDecl>(D)) 4212 return false; 4213 return true; 4214} 4215 4216void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 4217 bool isSubscript, bool AllowOnePastEnd) { 4218 const Type* EffectiveType = getElementType(BaseExpr); 4219 BaseExpr = BaseExpr->IgnoreParenCasts(); 4220 IndexExpr = IndexExpr->IgnoreParenCasts(); 4221 4222 const ConstantArrayType *ArrayTy = 4223 Context.getAsConstantArrayType(BaseExpr->getType()); 4224 if (!ArrayTy) 4225 return; 4226 4227 if (IndexExpr->isValueDependent()) 4228 return; 4229 llvm::APSInt index; 4230 if (!IndexExpr->isIntegerConstantExpr(index, Context)) 4231 return; 4232 4233 const NamedDecl *ND = NULL; 4234 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 4235 ND = dyn_cast<NamedDecl>(DRE->getDecl()); 4236 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 4237 ND = dyn_cast<NamedDecl>(ME->getMemberDecl()); 4238 4239 if (index.isUnsigned() || !index.isNegative()) { 4240 llvm::APInt size = ArrayTy->getSize(); 4241 if (!size.isStrictlyPositive()) 4242 return; 4243 4244 const Type* BaseType = getElementType(BaseExpr); 4245 if (BaseType != EffectiveType) { 4246 // Make sure we're comparing apples to apples when comparing index to size 4247 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 4248 uint64_t array_typesize = Context.getTypeSize(BaseType); 4249 // Handle ptrarith_typesize being zero, such as when casting to void* 4250 if (!ptrarith_typesize) ptrarith_typesize = 1; 4251 if (ptrarith_typesize != array_typesize) { 4252 // There's a cast to a different size type involved 4253 uint64_t ratio = array_typesize / ptrarith_typesize; 4254 // TODO: Be smarter about handling cases where array_typesize is not a 4255 // multiple of ptrarith_typesize 4256 if (ptrarith_typesize * ratio == array_typesize) 4257 size *= llvm::APInt(size.getBitWidth(), ratio); 4258 } 4259 } 4260 4261 if (size.getBitWidth() > index.getBitWidth()) 4262 index = index.sext(size.getBitWidth()); 4263 else if (size.getBitWidth() < index.getBitWidth()) 4264 size = size.sext(index.getBitWidth()); 4265 4266 // For array subscripting the index must be less than size, but for pointer 4267 // arithmetic also allow the index (offset) to be equal to size since 4268 // computing the next address after the end of the array is legal and 4269 // commonly done e.g. in C++ iterators and range-based for loops. 4270 if (AllowOnePastEnd ? index.sle(size) : index.slt(size)) 4271 return; 4272 4273 // Also don't warn for arrays of size 1 which are members of some 4274 // structure. These are often used to approximate flexible arrays in C89 4275 // code. 4276 if (IsTailPaddedMemberArray(*this, size, ND)) 4277 return; 4278 4279 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 4280 if (isSubscript) 4281 DiagID = diag::warn_array_index_exceeds_bounds; 4282 4283 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 4284 PDiag(DiagID) << index.toString(10, true) 4285 << size.toString(10, true) 4286 << (unsigned)size.getLimitedValue(~0U) 4287 << IndexExpr->getSourceRange()); 4288 } else { 4289 unsigned DiagID = diag::warn_array_index_precedes_bounds; 4290 if (!isSubscript) { 4291 DiagID = diag::warn_ptr_arith_precedes_bounds; 4292 if (index.isNegative()) index = -index; 4293 } 4294 4295 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 4296 PDiag(DiagID) << index.toString(10, true) 4297 << IndexExpr->getSourceRange()); 4298 } 4299 4300 if (ND) 4301 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr, 4302 PDiag(diag::note_array_index_out_of_bounds) 4303 << ND->getDeclName()); 4304} 4305 4306void Sema::CheckArrayAccess(const Expr *expr) { 4307 int AllowOnePastEnd = 0; 4308 while (expr) { 4309 expr = expr->IgnoreParenImpCasts(); 4310 switch (expr->getStmtClass()) { 4311 case Stmt::ArraySubscriptExprClass: { 4312 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 4313 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), true, 4314 AllowOnePastEnd > 0); 4315 return; 4316 } 4317 case Stmt::UnaryOperatorClass: { 4318 // Only unwrap the * and & unary operators 4319 const UnaryOperator *UO = cast<UnaryOperator>(expr); 4320 expr = UO->getSubExpr(); 4321 switch (UO->getOpcode()) { 4322 case UO_AddrOf: 4323 AllowOnePastEnd++; 4324 break; 4325 case UO_Deref: 4326 AllowOnePastEnd--; 4327 break; 4328 default: 4329 return; 4330 } 4331 break; 4332 } 4333 case Stmt::ConditionalOperatorClass: { 4334 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 4335 if (const Expr *lhs = cond->getLHS()) 4336 CheckArrayAccess(lhs); 4337 if (const Expr *rhs = cond->getRHS()) 4338 CheckArrayAccess(rhs); 4339 return; 4340 } 4341 default: 4342 return; 4343 } 4344 } 4345} 4346 4347//===--- CHECK: Objective-C retain cycles ----------------------------------// 4348 4349namespace { 4350 struct RetainCycleOwner { 4351 RetainCycleOwner() : Variable(0), Indirect(false) {} 4352 VarDecl *Variable; 4353 SourceRange Range; 4354 SourceLocation Loc; 4355 bool Indirect; 4356 4357 void setLocsFrom(Expr *e) { 4358 Loc = e->getExprLoc(); 4359 Range = e->getSourceRange(); 4360 } 4361 }; 4362} 4363 4364/// Consider whether capturing the given variable can possibly lead to 4365/// a retain cycle. 4366static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 4367 // In ARC, it's captured strongly iff the variable has __strong 4368 // lifetime. In MRR, it's captured strongly if the variable is 4369 // __block and has an appropriate type. 4370 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 4371 return false; 4372 4373 owner.Variable = var; 4374 owner.setLocsFrom(ref); 4375 return true; 4376} 4377 4378static bool findRetainCycleOwner(Expr *e, RetainCycleOwner &owner) { 4379 while (true) { 4380 e = e->IgnoreParens(); 4381 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 4382 switch (cast->getCastKind()) { 4383 case CK_BitCast: 4384 case CK_LValueBitCast: 4385 case CK_LValueToRValue: 4386 case CK_ARCReclaimReturnedObject: 4387 e = cast->getSubExpr(); 4388 continue; 4389 4390 default: 4391 return false; 4392 } 4393 } 4394 4395 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 4396 ObjCIvarDecl *ivar = ref->getDecl(); 4397 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 4398 return false; 4399 4400 // Try to find a retain cycle in the base. 4401 if (!findRetainCycleOwner(ref->getBase(), owner)) 4402 return false; 4403 4404 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 4405 owner.Indirect = true; 4406 return true; 4407 } 4408 4409 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 4410 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 4411 if (!var) return false; 4412 return considerVariable(var, ref, owner); 4413 } 4414 4415 if (BlockDeclRefExpr *ref = dyn_cast<BlockDeclRefExpr>(e)) { 4416 owner.Variable = ref->getDecl(); 4417 owner.setLocsFrom(ref); 4418 return true; 4419 } 4420 4421 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 4422 if (member->isArrow()) return false; 4423 4424 // Don't count this as an indirect ownership. 4425 e = member->getBase(); 4426 continue; 4427 } 4428 4429 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 4430 // Only pay attention to pseudo-objects on property references. 4431 ObjCPropertyRefExpr *pre 4432 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 4433 ->IgnoreParens()); 4434 if (!pre) return false; 4435 if (pre->isImplicitProperty()) return false; 4436 ObjCPropertyDecl *property = pre->getExplicitProperty(); 4437 if (!property->isRetaining() && 4438 !(property->getPropertyIvarDecl() && 4439 property->getPropertyIvarDecl()->getType() 4440 .getObjCLifetime() == Qualifiers::OCL_Strong)) 4441 return false; 4442 4443 owner.Indirect = true; 4444 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 4445 ->getSourceExpr()); 4446 continue; 4447 } 4448 4449 // Array ivars? 4450 4451 return false; 4452 } 4453} 4454 4455namespace { 4456 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 4457 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 4458 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 4459 Variable(variable), Capturer(0) {} 4460 4461 VarDecl *Variable; 4462 Expr *Capturer; 4463 4464 void VisitDeclRefExpr(DeclRefExpr *ref) { 4465 if (ref->getDecl() == Variable && !Capturer) 4466 Capturer = ref; 4467 } 4468 4469 void VisitBlockDeclRefExpr(BlockDeclRefExpr *ref) { 4470 if (ref->getDecl() == Variable && !Capturer) 4471 Capturer = ref; 4472 } 4473 4474 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 4475 if (Capturer) return; 4476 Visit(ref->getBase()); 4477 if (Capturer && ref->isFreeIvar()) 4478 Capturer = ref; 4479 } 4480 4481 void VisitBlockExpr(BlockExpr *block) { 4482 // Look inside nested blocks 4483 if (block->getBlockDecl()->capturesVariable(Variable)) 4484 Visit(block->getBlockDecl()->getBody()); 4485 } 4486 }; 4487} 4488 4489/// Check whether the given argument is a block which captures a 4490/// variable. 4491static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 4492 assert(owner.Variable && owner.Loc.isValid()); 4493 4494 e = e->IgnoreParenCasts(); 4495 BlockExpr *block = dyn_cast<BlockExpr>(e); 4496 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 4497 return 0; 4498 4499 FindCaptureVisitor visitor(S.Context, owner.Variable); 4500 visitor.Visit(block->getBlockDecl()->getBody()); 4501 return visitor.Capturer; 4502} 4503 4504static void diagnoseRetainCycle(Sema &S, Expr *capturer, 4505 RetainCycleOwner &owner) { 4506 assert(capturer); 4507 assert(owner.Variable && owner.Loc.isValid()); 4508 4509 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 4510 << owner.Variable << capturer->getSourceRange(); 4511 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 4512 << owner.Indirect << owner.Range; 4513} 4514 4515/// Check for a keyword selector that starts with the word 'add' or 4516/// 'set'. 4517static bool isSetterLikeSelector(Selector sel) { 4518 if (sel.isUnarySelector()) return false; 4519 4520 StringRef str = sel.getNameForSlot(0); 4521 while (!str.empty() && str.front() == '_') str = str.substr(1); 4522 if (str.startswith("set") || str.startswith("add")) 4523 str = str.substr(3); 4524 else 4525 return false; 4526 4527 if (str.empty()) return true; 4528 return !islower(str.front()); 4529} 4530 4531/// Check a message send to see if it's likely to cause a retain cycle. 4532void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 4533 // Only check instance methods whose selector looks like a setter. 4534 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 4535 return; 4536 4537 // Try to find a variable that the receiver is strongly owned by. 4538 RetainCycleOwner owner; 4539 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 4540 if (!findRetainCycleOwner(msg->getInstanceReceiver(), owner)) 4541 return; 4542 } else { 4543 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 4544 owner.Variable = getCurMethodDecl()->getSelfDecl(); 4545 owner.Loc = msg->getSuperLoc(); 4546 owner.Range = msg->getSuperLoc(); 4547 } 4548 4549 // Check whether the receiver is captured by any of the arguments. 4550 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) 4551 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) 4552 return diagnoseRetainCycle(*this, capturer, owner); 4553} 4554 4555/// Check a property assign to see if it's likely to cause a retain cycle. 4556void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 4557 RetainCycleOwner owner; 4558 if (!findRetainCycleOwner(receiver, owner)) 4559 return; 4560 4561 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 4562 diagnoseRetainCycle(*this, capturer, owner); 4563} 4564 4565bool Sema::checkUnsafeAssigns(SourceLocation Loc, 4566 QualType LHS, Expr *RHS) { 4567 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 4568 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 4569 return false; 4570 // strip off any implicit cast added to get to the one arc-specific 4571 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 4572 if (cast->getCastKind() == CK_ARCConsumeObject) { 4573 Diag(Loc, diag::warn_arc_retained_assign) 4574 << (LT == Qualifiers::OCL_ExplicitNone) 4575 << RHS->getSourceRange(); 4576 return true; 4577 } 4578 RHS = cast->getSubExpr(); 4579 } 4580 return false; 4581} 4582 4583void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 4584 Expr *LHS, Expr *RHS) { 4585 QualType LHSType = LHS->getType(); 4586 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 4587 return; 4588 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 4589 // FIXME. Check for other life times. 4590 if (LT != Qualifiers::OCL_None) 4591 return; 4592 4593 if (ObjCPropertyRefExpr *PRE 4594 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens())) { 4595 if (PRE->isImplicitProperty()) 4596 return; 4597 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 4598 if (!PD) 4599 return; 4600 4601 unsigned Attributes = PD->getPropertyAttributes(); 4602 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) 4603 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 4604 if (cast->getCastKind() == CK_ARCConsumeObject) { 4605 Diag(Loc, diag::warn_arc_retained_property_assign) 4606 << RHS->getSourceRange(); 4607 return; 4608 } 4609 RHS = cast->getSubExpr(); 4610 } 4611 } 4612} 4613