SemaChecking.cpp revision e4b92761b43ced611c417ae478568610f1ad7b1e
14e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===// 24e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)// 34e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)// The LLVM Compiler Infrastructure 44e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)// 54e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)// This file is distributed under the University of Illinois Open Source 64e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)// License. See LICENSE.TXT for details. 7f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)// 81320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci//===----------------------------------------------------------------------===// 9f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)// 104e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)// This file implements extra semantic analysis beyond what is enforced 11f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)// by the C type system. 12a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)// 134e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)//===----------------------------------------------------------------------===// 144e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) 15a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#include "clang/Sema/Initialization.h" 164e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)#include "clang/Sema/Sema.h" 17f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)#include "clang/Sema/SemaInternal.h" 184e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)#include "clang/Sema/Initialization.h" 194e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)#include "clang/Sema/ScopeInfo.h" 20a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#include "clang/Analysis/Analyses/FormatString.h" 21a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#include "clang/AST/ASTContext.h" 224e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)#include "clang/AST/CharUnits.h" 234e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)#include "clang/AST/DeclCXX.h" 244e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)#include "clang/AST/DeclObjC.h" 25f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)#include "clang/AST/ExprCXX.h" 26f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)#include "clang/AST/ExprObjC.h" 27c5cede9ae108bb15f6b7a8aea21c7e1fefa2834cBen Murdoch#include "clang/AST/EvaluatedExprVisitor.h" 28c5cede9ae108bb15f6b7a8aea21c7e1fefa2834cBen Murdoch#include "clang/AST/DeclObjC.h" 29c5cede9ae108bb15f6b7a8aea21c7e1fefa2834cBen Murdoch#include "clang/AST/StmtCXX.h" 30f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)#include "clang/AST/StmtObjC.h" 31f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)#include "clang/Lex/Preprocessor.h" 32a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#include "llvm/ADT/BitVector.h" 33a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#include "llvm/ADT/STLExtras.h" 34f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)#include "llvm/Support/raw_ostream.h" 35e5d81f57cb97b3b6b7fccc9c5610d21eb81db09dBen Murdoch#include "clang/Basic/TargetBuiltins.h" 36f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)#include "clang/Basic/TargetInfo.h" 37f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)#include "clang/Basic/ConvertUTF.h" 38f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)#include <limits> 39f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)using namespace clang; 40f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)using namespace sema; 41f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles) 42f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL, 43a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles) unsigned ByteNo) const { 44f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles) return SL->getLocationOfByte(ByteNo, PP.getSourceManager(), 45f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles) PP.getLangOptions(), PP.getTargetInfo()); 46a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)} 47a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles) 48a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)bool Sema::CheckablePrintfAttr(const FormatAttr *Format, Expr **Args, 49a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles) unsigned NumArgs, bool IsCXXMemberCall) { 50a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles) StringRef Type = Format->getType(); 51a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles) // FIXME: add support for "CFString" Type. They are not string literal though, 52a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles) // so they need special handling. 53c5cede9ae108bb15f6b7a8aea21c7e1fefa2834cBen Murdoch if (Type == "printf" || Type == "NSString") return true; 54c5cede9ae108bb15f6b7a8aea21c7e1fefa2834cBen Murdoch if (Type == "printf0") { 55f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles) // printf0 allows null "format" string; if so don't check format/args 56f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles) unsigned format_idx = Format->getFormatIdx() - 1; 57f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles) // Does the index refer to the implicit object argument? 58a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles) if (IsCXXMemberCall) { 59f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles) if (format_idx == 0) 60f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles) return false; 61f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles) --format_idx; 62f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles) } 63f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles) if (format_idx < NumArgs) { 64f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles) Expr *Format = Args[format_idx]->IgnoreParenCasts(); 65f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles) if (!Format->isNullPointerConstant(Context, 66f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles) Expr::NPC_ValueDependentIsNull)) 674e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) return true; 684e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) } 694e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) } 704e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) return false; 714e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)} 724e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) 734e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)/// Checks that a call expression's argument count is the desired number. 744e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)/// This is useful when doing custom type-checking. Returns true on error. 754e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) { 764e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) unsigned argCount = call->getNumArgs(); 774e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) if (argCount == desiredArgCount) return false; 784e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) 794e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) if (argCount < desiredArgCount) 804e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args) 814e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) << 0 /*function call*/ << desiredArgCount << argCount 824e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) << call->getSourceRange(); 834e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) 844e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) // Highlight all the excess arguments. 855d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles) SourceRange range(call->getArg(desiredArgCount)->getLocStart(), 864e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) call->getArg(argCount - 1)->getLocEnd()); 874e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) 88f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles) return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args) 89f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles) << 0 /*function call*/ << desiredArgCount << argCount 90f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles) << call->getArg(1)->getSourceRange(); 91a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)} 92a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles) 93f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)/// CheckBuiltinAnnotationString - Checks that string argument to the builtin 94f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)/// annotation is a non wide string literal. 954e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)static bool CheckBuiltinAnnotationString(Sema &S, Expr *Arg) { 964e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) Arg = Arg->IgnoreParenCasts(); 974e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 984e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles) if (!Literal || !Literal->isAscii()) { 99 S.Diag(Arg->getLocStart(), diag::err_builtin_annotation_not_string_constant) 100 << Arg->getSourceRange(); 101 return true; 102 } 103 return false; 104} 105 106ExprResult 107Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 108 ExprResult TheCallResult(Owned(TheCall)); 109 110 // Find out if any arguments are required to be integer constant expressions. 111 unsigned ICEArguments = 0; 112 ASTContext::GetBuiltinTypeError Error; 113 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 114 if (Error != ASTContext::GE_None) 115 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 116 117 // If any arguments are required to be ICE's, check and diagnose. 118 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 119 // Skip arguments not required to be ICE's. 120 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 121 122 llvm::APSInt Result; 123 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 124 return true; 125 ICEArguments &= ~(1 << ArgNo); 126 } 127 128 switch (BuiltinID) { 129 case Builtin::BI__builtin___CFStringMakeConstantString: 130 assert(TheCall->getNumArgs() == 1 && 131 "Wrong # arguments to builtin CFStringMakeConstantString"); 132 if (CheckObjCString(TheCall->getArg(0))) 133 return ExprError(); 134 break; 135 case Builtin::BI__builtin_stdarg_start: 136 case Builtin::BI__builtin_va_start: 137 if (SemaBuiltinVAStart(TheCall)) 138 return ExprError(); 139 break; 140 case Builtin::BI__builtin_isgreater: 141 case Builtin::BI__builtin_isgreaterequal: 142 case Builtin::BI__builtin_isless: 143 case Builtin::BI__builtin_islessequal: 144 case Builtin::BI__builtin_islessgreater: 145 case Builtin::BI__builtin_isunordered: 146 if (SemaBuiltinUnorderedCompare(TheCall)) 147 return ExprError(); 148 break; 149 case Builtin::BI__builtin_fpclassify: 150 if (SemaBuiltinFPClassification(TheCall, 6)) 151 return ExprError(); 152 break; 153 case Builtin::BI__builtin_isfinite: 154 case Builtin::BI__builtin_isinf: 155 case Builtin::BI__builtin_isinf_sign: 156 case Builtin::BI__builtin_isnan: 157 case Builtin::BI__builtin_isnormal: 158 if (SemaBuiltinFPClassification(TheCall, 1)) 159 return ExprError(); 160 break; 161 case Builtin::BI__builtin_shufflevector: 162 return SemaBuiltinShuffleVector(TheCall); 163 // TheCall will be freed by the smart pointer here, but that's fine, since 164 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 165 case Builtin::BI__builtin_prefetch: 166 if (SemaBuiltinPrefetch(TheCall)) 167 return ExprError(); 168 break; 169 case Builtin::BI__builtin_object_size: 170 if (SemaBuiltinObjectSize(TheCall)) 171 return ExprError(); 172 break; 173 case Builtin::BI__builtin_longjmp: 174 if (SemaBuiltinLongjmp(TheCall)) 175 return ExprError(); 176 break; 177 178 case Builtin::BI__builtin_classify_type: 179 if (checkArgCount(*this, TheCall, 1)) return true; 180 TheCall->setType(Context.IntTy); 181 break; 182 case Builtin::BI__builtin_constant_p: 183 if (checkArgCount(*this, TheCall, 1)) return true; 184 TheCall->setType(Context.IntTy); 185 break; 186 case Builtin::BI__sync_fetch_and_add: 187 case Builtin::BI__sync_fetch_and_add_1: 188 case Builtin::BI__sync_fetch_and_add_2: 189 case Builtin::BI__sync_fetch_and_add_4: 190 case Builtin::BI__sync_fetch_and_add_8: 191 case Builtin::BI__sync_fetch_and_add_16: 192 case Builtin::BI__sync_fetch_and_sub: 193 case Builtin::BI__sync_fetch_and_sub_1: 194 case Builtin::BI__sync_fetch_and_sub_2: 195 case Builtin::BI__sync_fetch_and_sub_4: 196 case Builtin::BI__sync_fetch_and_sub_8: 197 case Builtin::BI__sync_fetch_and_sub_16: 198 case Builtin::BI__sync_fetch_and_or: 199 case Builtin::BI__sync_fetch_and_or_1: 200 case Builtin::BI__sync_fetch_and_or_2: 201 case Builtin::BI__sync_fetch_and_or_4: 202 case Builtin::BI__sync_fetch_and_or_8: 203 case Builtin::BI__sync_fetch_and_or_16: 204 case Builtin::BI__sync_fetch_and_and: 205 case Builtin::BI__sync_fetch_and_and_1: 206 case Builtin::BI__sync_fetch_and_and_2: 207 case Builtin::BI__sync_fetch_and_and_4: 208 case Builtin::BI__sync_fetch_and_and_8: 209 case Builtin::BI__sync_fetch_and_and_16: 210 case Builtin::BI__sync_fetch_and_xor: 211 case Builtin::BI__sync_fetch_and_xor_1: 212 case Builtin::BI__sync_fetch_and_xor_2: 213 case Builtin::BI__sync_fetch_and_xor_4: 214 case Builtin::BI__sync_fetch_and_xor_8: 215 case Builtin::BI__sync_fetch_and_xor_16: 216 case Builtin::BI__sync_add_and_fetch: 217 case Builtin::BI__sync_add_and_fetch_1: 218 case Builtin::BI__sync_add_and_fetch_2: 219 case Builtin::BI__sync_add_and_fetch_4: 220 case Builtin::BI__sync_add_and_fetch_8: 221 case Builtin::BI__sync_add_and_fetch_16: 222 case Builtin::BI__sync_sub_and_fetch: 223 case Builtin::BI__sync_sub_and_fetch_1: 224 case Builtin::BI__sync_sub_and_fetch_2: 225 case Builtin::BI__sync_sub_and_fetch_4: 226 case Builtin::BI__sync_sub_and_fetch_8: 227 case Builtin::BI__sync_sub_and_fetch_16: 228 case Builtin::BI__sync_and_and_fetch: 229 case Builtin::BI__sync_and_and_fetch_1: 230 case Builtin::BI__sync_and_and_fetch_2: 231 case Builtin::BI__sync_and_and_fetch_4: 232 case Builtin::BI__sync_and_and_fetch_8: 233 case Builtin::BI__sync_and_and_fetch_16: 234 case Builtin::BI__sync_or_and_fetch: 235 case Builtin::BI__sync_or_and_fetch_1: 236 case Builtin::BI__sync_or_and_fetch_2: 237 case Builtin::BI__sync_or_and_fetch_4: 238 case Builtin::BI__sync_or_and_fetch_8: 239 case Builtin::BI__sync_or_and_fetch_16: 240 case Builtin::BI__sync_xor_and_fetch: 241 case Builtin::BI__sync_xor_and_fetch_1: 242 case Builtin::BI__sync_xor_and_fetch_2: 243 case Builtin::BI__sync_xor_and_fetch_4: 244 case Builtin::BI__sync_xor_and_fetch_8: 245 case Builtin::BI__sync_xor_and_fetch_16: 246 case Builtin::BI__sync_val_compare_and_swap: 247 case Builtin::BI__sync_val_compare_and_swap_1: 248 case Builtin::BI__sync_val_compare_and_swap_2: 249 case Builtin::BI__sync_val_compare_and_swap_4: 250 case Builtin::BI__sync_val_compare_and_swap_8: 251 case Builtin::BI__sync_val_compare_and_swap_16: 252 case Builtin::BI__sync_bool_compare_and_swap: 253 case Builtin::BI__sync_bool_compare_and_swap_1: 254 case Builtin::BI__sync_bool_compare_and_swap_2: 255 case Builtin::BI__sync_bool_compare_and_swap_4: 256 case Builtin::BI__sync_bool_compare_and_swap_8: 257 case Builtin::BI__sync_bool_compare_and_swap_16: 258 case Builtin::BI__sync_lock_test_and_set: 259 case Builtin::BI__sync_lock_test_and_set_1: 260 case Builtin::BI__sync_lock_test_and_set_2: 261 case Builtin::BI__sync_lock_test_and_set_4: 262 case Builtin::BI__sync_lock_test_and_set_8: 263 case Builtin::BI__sync_lock_test_and_set_16: 264 case Builtin::BI__sync_lock_release: 265 case Builtin::BI__sync_lock_release_1: 266 case Builtin::BI__sync_lock_release_2: 267 case Builtin::BI__sync_lock_release_4: 268 case Builtin::BI__sync_lock_release_8: 269 case Builtin::BI__sync_lock_release_16: 270 case Builtin::BI__sync_swap: 271 case Builtin::BI__sync_swap_1: 272 case Builtin::BI__sync_swap_2: 273 case Builtin::BI__sync_swap_4: 274 case Builtin::BI__sync_swap_8: 275 case Builtin::BI__sync_swap_16: 276 return SemaBuiltinAtomicOverloaded(move(TheCallResult)); 277 case Builtin::BI__atomic_load: 278 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Load); 279 case Builtin::BI__atomic_store: 280 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Store); 281 case Builtin::BI__atomic_init: 282 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Init); 283 case Builtin::BI__atomic_exchange: 284 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Xchg); 285 case Builtin::BI__atomic_compare_exchange_strong: 286 return SemaAtomicOpsOverloaded(move(TheCallResult), 287 AtomicExpr::CmpXchgStrong); 288 case Builtin::BI__atomic_compare_exchange_weak: 289 return SemaAtomicOpsOverloaded(move(TheCallResult), 290 AtomicExpr::CmpXchgWeak); 291 case Builtin::BI__atomic_fetch_add: 292 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Add); 293 case Builtin::BI__atomic_fetch_sub: 294 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Sub); 295 case Builtin::BI__atomic_fetch_and: 296 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::And); 297 case Builtin::BI__atomic_fetch_or: 298 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Or); 299 case Builtin::BI__atomic_fetch_xor: 300 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Xor); 301 case Builtin::BI__builtin_annotation: 302 if (CheckBuiltinAnnotationString(*this, TheCall->getArg(1))) 303 return ExprError(); 304 break; 305 } 306 307 // Since the target specific builtins for each arch overlap, only check those 308 // of the arch we are compiling for. 309 if (BuiltinID >= Builtin::FirstTSBuiltin) { 310 switch (Context.getTargetInfo().getTriple().getArch()) { 311 case llvm::Triple::arm: 312 case llvm::Triple::thumb: 313 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall)) 314 return ExprError(); 315 break; 316 default: 317 break; 318 } 319 } 320 321 return move(TheCallResult); 322} 323 324// Get the valid immediate range for the specified NEON type code. 325static unsigned RFT(unsigned t, bool shift = false) { 326 NeonTypeFlags Type(t); 327 int IsQuad = Type.isQuad(); 328 switch (Type.getEltType()) { 329 case NeonTypeFlags::Int8: 330 case NeonTypeFlags::Poly8: 331 return shift ? 7 : (8 << IsQuad) - 1; 332 case NeonTypeFlags::Int16: 333 case NeonTypeFlags::Poly16: 334 return shift ? 15 : (4 << IsQuad) - 1; 335 case NeonTypeFlags::Int32: 336 return shift ? 31 : (2 << IsQuad) - 1; 337 case NeonTypeFlags::Int64: 338 return shift ? 63 : (1 << IsQuad) - 1; 339 case NeonTypeFlags::Float16: 340 assert(!shift && "cannot shift float types!"); 341 return (4 << IsQuad) - 1; 342 case NeonTypeFlags::Float32: 343 assert(!shift && "cannot shift float types!"); 344 return (2 << IsQuad) - 1; 345 } 346 llvm_unreachable("Invalid NeonTypeFlag!"); 347} 348 349/// getNeonEltType - Return the QualType corresponding to the elements of 350/// the vector type specified by the NeonTypeFlags. This is used to check 351/// the pointer arguments for Neon load/store intrinsics. 352static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context) { 353 switch (Flags.getEltType()) { 354 case NeonTypeFlags::Int8: 355 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 356 case NeonTypeFlags::Int16: 357 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 358 case NeonTypeFlags::Int32: 359 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 360 case NeonTypeFlags::Int64: 361 return Flags.isUnsigned() ? Context.UnsignedLongLongTy : Context.LongLongTy; 362 case NeonTypeFlags::Poly8: 363 return Context.SignedCharTy; 364 case NeonTypeFlags::Poly16: 365 return Context.ShortTy; 366 case NeonTypeFlags::Float16: 367 return Context.UnsignedShortTy; 368 case NeonTypeFlags::Float32: 369 return Context.FloatTy; 370 } 371 llvm_unreachable("Invalid NeonTypeFlag!"); 372} 373 374bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 375 llvm::APSInt Result; 376 377 unsigned mask = 0; 378 unsigned TV = 0; 379 int PtrArgNum = -1; 380 bool HasConstPtr = false; 381 switch (BuiltinID) { 382#define GET_NEON_OVERLOAD_CHECK 383#include "clang/Basic/arm_neon.inc" 384#undef GET_NEON_OVERLOAD_CHECK 385 } 386 387 // For NEON intrinsics which are overloaded on vector element type, validate 388 // the immediate which specifies which variant to emit. 389 unsigned ImmArg = TheCall->getNumArgs()-1; 390 if (mask) { 391 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 392 return true; 393 394 TV = Result.getLimitedValue(64); 395 if ((TV > 63) || (mask & (1 << TV)) == 0) 396 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code) 397 << TheCall->getArg(ImmArg)->getSourceRange(); 398 } 399 400 if (PtrArgNum >= 0) { 401 // Check that pointer arguments have the specified type. 402 Expr *Arg = TheCall->getArg(PtrArgNum); 403 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 404 Arg = ICE->getSubExpr(); 405 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 406 QualType RHSTy = RHS.get()->getType(); 407 QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context); 408 if (HasConstPtr) 409 EltTy = EltTy.withConst(); 410 QualType LHSTy = Context.getPointerType(EltTy); 411 AssignConvertType ConvTy; 412 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 413 if (RHS.isInvalid()) 414 return true; 415 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy, 416 RHS.get(), AA_Assigning)) 417 return true; 418 } 419 420 // For NEON intrinsics which take an immediate value as part of the 421 // instruction, range check them here. 422 unsigned i = 0, l = 0, u = 0; 423 switch (BuiltinID) { 424 default: return false; 425 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break; 426 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break; 427 case ARM::BI__builtin_arm_vcvtr_f: 428 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break; 429#define GET_NEON_IMMEDIATE_CHECK 430#include "clang/Basic/arm_neon.inc" 431#undef GET_NEON_IMMEDIATE_CHECK 432 }; 433 434 // Check that the immediate argument is actually a constant. 435 if (SemaBuiltinConstantArg(TheCall, i, Result)) 436 return true; 437 438 // Range check against the upper/lower values for this isntruction. 439 unsigned Val = Result.getZExtValue(); 440 if (Val < l || Val > (u + l)) 441 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 442 << l << u+l << TheCall->getArg(i)->getSourceRange(); 443 444 // FIXME: VFP Intrinsics should error if VFP not present. 445 return false; 446} 447 448/// CheckFunctionCall - Check a direct function call for various correctness 449/// and safety properties not strictly enforced by the C type system. 450bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) { 451 // Get the IdentifierInfo* for the called function. 452 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 453 454 // None of the checks below are needed for functions that don't have 455 // simple names (e.g., C++ conversion functions). 456 if (!FnInfo) 457 return false; 458 459 // FIXME: This mechanism should be abstracted to be less fragile and 460 // more efficient. For example, just map function ids to custom 461 // handlers. 462 463 // Printf and scanf checking. 464 for (specific_attr_iterator<FormatAttr> 465 i = FDecl->specific_attr_begin<FormatAttr>(), 466 e = FDecl->specific_attr_end<FormatAttr>(); i != e ; ++i) { 467 CheckFormatArguments(*i, TheCall); 468 } 469 470 for (specific_attr_iterator<NonNullAttr> 471 i = FDecl->specific_attr_begin<NonNullAttr>(), 472 e = FDecl->specific_attr_end<NonNullAttr>(); i != e; ++i) { 473 CheckNonNullArguments(*i, TheCall->getArgs(), 474 TheCall->getCallee()->getLocStart()); 475 } 476 477 unsigned CMId = FDecl->getMemoryFunctionKind(); 478 if (CMId == 0) 479 return false; 480 481 // Handle memory setting and copying functions. 482 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat) 483 CheckStrlcpycatArguments(TheCall, FnInfo); 484 else 485 CheckMemaccessArguments(TheCall, CMId, FnInfo); 486 487 return false; 488} 489 490bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 491 Expr **Args, unsigned NumArgs) { 492 for (specific_attr_iterator<FormatAttr> 493 i = Method->specific_attr_begin<FormatAttr>(), 494 e = Method->specific_attr_end<FormatAttr>(); i != e ; ++i) { 495 496 CheckFormatArguments(*i, Args, NumArgs, false, lbrac, 497 Method->getSourceRange()); 498 } 499 500 // diagnose nonnull arguments. 501 for (specific_attr_iterator<NonNullAttr> 502 i = Method->specific_attr_begin<NonNullAttr>(), 503 e = Method->specific_attr_end<NonNullAttr>(); i != e; ++i) { 504 CheckNonNullArguments(*i, Args, lbrac); 505 } 506 507 return false; 508} 509 510bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) { 511 const VarDecl *V = dyn_cast<VarDecl>(NDecl); 512 if (!V) 513 return false; 514 515 QualType Ty = V->getType(); 516 if (!Ty->isBlockPointerType()) 517 return false; 518 519 // format string checking. 520 for (specific_attr_iterator<FormatAttr> 521 i = NDecl->specific_attr_begin<FormatAttr>(), 522 e = NDecl->specific_attr_end<FormatAttr>(); i != e ; ++i) { 523 CheckFormatArguments(*i, TheCall); 524 } 525 526 return false; 527} 528 529ExprResult 530Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, AtomicExpr::AtomicOp Op) { 531 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 532 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 533 534 // All these operations take one of the following four forms: 535 // T __atomic_load(_Atomic(T)*, int) (loads) 536 // T* __atomic_add(_Atomic(T*)*, ptrdiff_t, int) (pointer add/sub) 537 // int __atomic_compare_exchange_strong(_Atomic(T)*, T*, T, int, int) 538 // (cmpxchg) 539 // T __atomic_exchange(_Atomic(T)*, T, int) (everything else) 540 // where T is an appropriate type, and the int paremeterss are for orderings. 541 unsigned NumVals = 1; 542 unsigned NumOrders = 1; 543 if (Op == AtomicExpr::Load) { 544 NumVals = 0; 545 } else if (Op == AtomicExpr::CmpXchgWeak || Op == AtomicExpr::CmpXchgStrong) { 546 NumVals = 2; 547 NumOrders = 2; 548 } 549 if (Op == AtomicExpr::Init) 550 NumOrders = 0; 551 552 if (TheCall->getNumArgs() < NumVals+NumOrders+1) { 553 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 554 << 0 << NumVals+NumOrders+1 << TheCall->getNumArgs() 555 << TheCall->getCallee()->getSourceRange(); 556 return ExprError(); 557 } else if (TheCall->getNumArgs() > NumVals+NumOrders+1) { 558 Diag(TheCall->getArg(NumVals+NumOrders+1)->getLocStart(), 559 diag::err_typecheck_call_too_many_args) 560 << 0 << NumVals+NumOrders+1 << TheCall->getNumArgs() 561 << TheCall->getCallee()->getSourceRange(); 562 return ExprError(); 563 } 564 565 // Inspect the first argument of the atomic operation. This should always be 566 // a pointer to an _Atomic type. 567 Expr *Ptr = TheCall->getArg(0); 568 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get(); 569 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 570 if (!pointerType) { 571 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic) 572 << Ptr->getType() << Ptr->getSourceRange(); 573 return ExprError(); 574 } 575 576 QualType AtomTy = pointerType->getPointeeType(); 577 if (!AtomTy->isAtomicType()) { 578 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic) 579 << Ptr->getType() << Ptr->getSourceRange(); 580 return ExprError(); 581 } 582 QualType ValType = AtomTy->getAs<AtomicType>()->getValueType(); 583 584 if ((Op == AtomicExpr::Add || Op == AtomicExpr::Sub) && 585 !ValType->isIntegerType() && !ValType->isPointerType()) { 586 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr) 587 << Ptr->getType() << Ptr->getSourceRange(); 588 return ExprError(); 589 } 590 591 if (!ValType->isIntegerType() && 592 (Op == AtomicExpr::And || Op == AtomicExpr::Or || Op == AtomicExpr::Xor)){ 593 Diag(DRE->getLocStart(), diag::err_atomic_op_logical_needs_atomic_int) 594 << Ptr->getType() << Ptr->getSourceRange(); 595 return ExprError(); 596 } 597 598 switch (ValType.getObjCLifetime()) { 599 case Qualifiers::OCL_None: 600 case Qualifiers::OCL_ExplicitNone: 601 // okay 602 break; 603 604 case Qualifiers::OCL_Weak: 605 case Qualifiers::OCL_Strong: 606 case Qualifiers::OCL_Autoreleasing: 607 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 608 << ValType << Ptr->getSourceRange(); 609 return ExprError(); 610 } 611 612 QualType ResultType = ValType; 613 if (Op == AtomicExpr::Store || Op == AtomicExpr::Init) 614 ResultType = Context.VoidTy; 615 else if (Op == AtomicExpr::CmpXchgWeak || Op == AtomicExpr::CmpXchgStrong) 616 ResultType = Context.BoolTy; 617 618 // The first argument --- the pointer --- has a fixed type; we 619 // deduce the types of the rest of the arguments accordingly. Walk 620 // the remaining arguments, converting them to the deduced value type. 621 for (unsigned i = 1; i != NumVals+NumOrders+1; ++i) { 622 ExprResult Arg = TheCall->getArg(i); 623 QualType Ty; 624 if (i < NumVals+1) { 625 // The second argument to a cmpxchg is a pointer to the data which will 626 // be exchanged. The second argument to a pointer add/subtract is the 627 // amount to add/subtract, which must be a ptrdiff_t. The third 628 // argument to a cmpxchg and the second argument in all other cases 629 // is the type of the value. 630 if (i == 1 && (Op == AtomicExpr::CmpXchgWeak || 631 Op == AtomicExpr::CmpXchgStrong)) 632 Ty = Context.getPointerType(ValType.getUnqualifiedType()); 633 else if (!ValType->isIntegerType() && 634 (Op == AtomicExpr::Add || Op == AtomicExpr::Sub)) 635 Ty = Context.getPointerDiffType(); 636 else 637 Ty = ValType; 638 } else { 639 // The order(s) are always converted to int. 640 Ty = Context.IntTy; 641 } 642 InitializedEntity Entity = 643 InitializedEntity::InitializeParameter(Context, Ty, false); 644 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 645 if (Arg.isInvalid()) 646 return true; 647 TheCall->setArg(i, Arg.get()); 648 } 649 650 SmallVector<Expr*, 5> SubExprs; 651 SubExprs.push_back(Ptr); 652 if (Op == AtomicExpr::Load) { 653 SubExprs.push_back(TheCall->getArg(1)); // Order 654 } else if (Op == AtomicExpr::Init) { 655 SubExprs.push_back(TheCall->getArg(1)); // Val1 656 } else if (Op != AtomicExpr::CmpXchgWeak && Op != AtomicExpr::CmpXchgStrong) { 657 SubExprs.push_back(TheCall->getArg(2)); // Order 658 SubExprs.push_back(TheCall->getArg(1)); // Val1 659 } else { 660 SubExprs.push_back(TheCall->getArg(3)); // Order 661 SubExprs.push_back(TheCall->getArg(1)); // Val1 662 SubExprs.push_back(TheCall->getArg(2)); // Val2 663 SubExprs.push_back(TheCall->getArg(4)); // OrderFail 664 } 665 666 return Owned(new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(), 667 SubExprs.data(), SubExprs.size(), 668 ResultType, Op, 669 TheCall->getRParenLoc())); 670} 671 672 673/// checkBuiltinArgument - Given a call to a builtin function, perform 674/// normal type-checking on the given argument, updating the call in 675/// place. This is useful when a builtin function requires custom 676/// type-checking for some of its arguments but not necessarily all of 677/// them. 678/// 679/// Returns true on error. 680static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 681 FunctionDecl *Fn = E->getDirectCallee(); 682 assert(Fn && "builtin call without direct callee!"); 683 684 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 685 InitializedEntity Entity = 686 InitializedEntity::InitializeParameter(S.Context, Param); 687 688 ExprResult Arg = E->getArg(0); 689 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 690 if (Arg.isInvalid()) 691 return true; 692 693 E->setArg(ArgIndex, Arg.take()); 694 return false; 695} 696 697/// SemaBuiltinAtomicOverloaded - We have a call to a function like 698/// __sync_fetch_and_add, which is an overloaded function based on the pointer 699/// type of its first argument. The main ActOnCallExpr routines have already 700/// promoted the types of arguments because all of these calls are prototyped as 701/// void(...). 702/// 703/// This function goes through and does final semantic checking for these 704/// builtins, 705ExprResult 706Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 707 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 708 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 709 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 710 711 // Ensure that we have at least one argument to do type inference from. 712 if (TheCall->getNumArgs() < 1) { 713 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 714 << 0 << 1 << TheCall->getNumArgs() 715 << TheCall->getCallee()->getSourceRange(); 716 return ExprError(); 717 } 718 719 // Inspect the first argument of the atomic builtin. This should always be 720 // a pointer type, whose element is an integral scalar or pointer type. 721 // Because it is a pointer type, we don't have to worry about any implicit 722 // casts here. 723 // FIXME: We don't allow floating point scalars as input. 724 Expr *FirstArg = TheCall->getArg(0); 725 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 726 if (FirstArgResult.isInvalid()) 727 return ExprError(); 728 FirstArg = FirstArgResult.take(); 729 TheCall->setArg(0, FirstArg); 730 731 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 732 if (!pointerType) { 733 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 734 << FirstArg->getType() << FirstArg->getSourceRange(); 735 return ExprError(); 736 } 737 738 QualType ValType = pointerType->getPointeeType(); 739 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 740 !ValType->isBlockPointerType()) { 741 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr) 742 << FirstArg->getType() << FirstArg->getSourceRange(); 743 return ExprError(); 744 } 745 746 switch (ValType.getObjCLifetime()) { 747 case Qualifiers::OCL_None: 748 case Qualifiers::OCL_ExplicitNone: 749 // okay 750 break; 751 752 case Qualifiers::OCL_Weak: 753 case Qualifiers::OCL_Strong: 754 case Qualifiers::OCL_Autoreleasing: 755 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 756 << ValType << FirstArg->getSourceRange(); 757 return ExprError(); 758 } 759 760 // Strip any qualifiers off ValType. 761 ValType = ValType.getUnqualifiedType(); 762 763 // The majority of builtins return a value, but a few have special return 764 // types, so allow them to override appropriately below. 765 QualType ResultType = ValType; 766 767 // We need to figure out which concrete builtin this maps onto. For example, 768 // __sync_fetch_and_add with a 2 byte object turns into 769 // __sync_fetch_and_add_2. 770#define BUILTIN_ROW(x) \ 771 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 772 Builtin::BI##x##_8, Builtin::BI##x##_16 } 773 774 static const unsigned BuiltinIndices[][5] = { 775 BUILTIN_ROW(__sync_fetch_and_add), 776 BUILTIN_ROW(__sync_fetch_and_sub), 777 BUILTIN_ROW(__sync_fetch_and_or), 778 BUILTIN_ROW(__sync_fetch_and_and), 779 BUILTIN_ROW(__sync_fetch_and_xor), 780 781 BUILTIN_ROW(__sync_add_and_fetch), 782 BUILTIN_ROW(__sync_sub_and_fetch), 783 BUILTIN_ROW(__sync_and_and_fetch), 784 BUILTIN_ROW(__sync_or_and_fetch), 785 BUILTIN_ROW(__sync_xor_and_fetch), 786 787 BUILTIN_ROW(__sync_val_compare_and_swap), 788 BUILTIN_ROW(__sync_bool_compare_and_swap), 789 BUILTIN_ROW(__sync_lock_test_and_set), 790 BUILTIN_ROW(__sync_lock_release), 791 BUILTIN_ROW(__sync_swap) 792 }; 793#undef BUILTIN_ROW 794 795 // Determine the index of the size. 796 unsigned SizeIndex; 797 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 798 case 1: SizeIndex = 0; break; 799 case 2: SizeIndex = 1; break; 800 case 4: SizeIndex = 2; break; 801 case 8: SizeIndex = 3; break; 802 case 16: SizeIndex = 4; break; 803 default: 804 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size) 805 << FirstArg->getType() << FirstArg->getSourceRange(); 806 return ExprError(); 807 } 808 809 // Each of these builtins has one pointer argument, followed by some number of 810 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 811 // that we ignore. Find out which row of BuiltinIndices to read from as well 812 // as the number of fixed args. 813 unsigned BuiltinID = FDecl->getBuiltinID(); 814 unsigned BuiltinIndex, NumFixed = 1; 815 switch (BuiltinID) { 816 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 817 case Builtin::BI__sync_fetch_and_add: 818 case Builtin::BI__sync_fetch_and_add_1: 819 case Builtin::BI__sync_fetch_and_add_2: 820 case Builtin::BI__sync_fetch_and_add_4: 821 case Builtin::BI__sync_fetch_and_add_8: 822 case Builtin::BI__sync_fetch_and_add_16: 823 BuiltinIndex = 0; 824 break; 825 826 case Builtin::BI__sync_fetch_and_sub: 827 case Builtin::BI__sync_fetch_and_sub_1: 828 case Builtin::BI__sync_fetch_and_sub_2: 829 case Builtin::BI__sync_fetch_and_sub_4: 830 case Builtin::BI__sync_fetch_and_sub_8: 831 case Builtin::BI__sync_fetch_and_sub_16: 832 BuiltinIndex = 1; 833 break; 834 835 case Builtin::BI__sync_fetch_and_or: 836 case Builtin::BI__sync_fetch_and_or_1: 837 case Builtin::BI__sync_fetch_and_or_2: 838 case Builtin::BI__sync_fetch_and_or_4: 839 case Builtin::BI__sync_fetch_and_or_8: 840 case Builtin::BI__sync_fetch_and_or_16: 841 BuiltinIndex = 2; 842 break; 843 844 case Builtin::BI__sync_fetch_and_and: 845 case Builtin::BI__sync_fetch_and_and_1: 846 case Builtin::BI__sync_fetch_and_and_2: 847 case Builtin::BI__sync_fetch_and_and_4: 848 case Builtin::BI__sync_fetch_and_and_8: 849 case Builtin::BI__sync_fetch_and_and_16: 850 BuiltinIndex = 3; 851 break; 852 853 case Builtin::BI__sync_fetch_and_xor: 854 case Builtin::BI__sync_fetch_and_xor_1: 855 case Builtin::BI__sync_fetch_and_xor_2: 856 case Builtin::BI__sync_fetch_and_xor_4: 857 case Builtin::BI__sync_fetch_and_xor_8: 858 case Builtin::BI__sync_fetch_and_xor_16: 859 BuiltinIndex = 4; 860 break; 861 862 case Builtin::BI__sync_add_and_fetch: 863 case Builtin::BI__sync_add_and_fetch_1: 864 case Builtin::BI__sync_add_and_fetch_2: 865 case Builtin::BI__sync_add_and_fetch_4: 866 case Builtin::BI__sync_add_and_fetch_8: 867 case Builtin::BI__sync_add_and_fetch_16: 868 BuiltinIndex = 5; 869 break; 870 871 case Builtin::BI__sync_sub_and_fetch: 872 case Builtin::BI__sync_sub_and_fetch_1: 873 case Builtin::BI__sync_sub_and_fetch_2: 874 case Builtin::BI__sync_sub_and_fetch_4: 875 case Builtin::BI__sync_sub_and_fetch_8: 876 case Builtin::BI__sync_sub_and_fetch_16: 877 BuiltinIndex = 6; 878 break; 879 880 case Builtin::BI__sync_and_and_fetch: 881 case Builtin::BI__sync_and_and_fetch_1: 882 case Builtin::BI__sync_and_and_fetch_2: 883 case Builtin::BI__sync_and_and_fetch_4: 884 case Builtin::BI__sync_and_and_fetch_8: 885 case Builtin::BI__sync_and_and_fetch_16: 886 BuiltinIndex = 7; 887 break; 888 889 case Builtin::BI__sync_or_and_fetch: 890 case Builtin::BI__sync_or_and_fetch_1: 891 case Builtin::BI__sync_or_and_fetch_2: 892 case Builtin::BI__sync_or_and_fetch_4: 893 case Builtin::BI__sync_or_and_fetch_8: 894 case Builtin::BI__sync_or_and_fetch_16: 895 BuiltinIndex = 8; 896 break; 897 898 case Builtin::BI__sync_xor_and_fetch: 899 case Builtin::BI__sync_xor_and_fetch_1: 900 case Builtin::BI__sync_xor_and_fetch_2: 901 case Builtin::BI__sync_xor_and_fetch_4: 902 case Builtin::BI__sync_xor_and_fetch_8: 903 case Builtin::BI__sync_xor_and_fetch_16: 904 BuiltinIndex = 9; 905 break; 906 907 case Builtin::BI__sync_val_compare_and_swap: 908 case Builtin::BI__sync_val_compare_and_swap_1: 909 case Builtin::BI__sync_val_compare_and_swap_2: 910 case Builtin::BI__sync_val_compare_and_swap_4: 911 case Builtin::BI__sync_val_compare_and_swap_8: 912 case Builtin::BI__sync_val_compare_and_swap_16: 913 BuiltinIndex = 10; 914 NumFixed = 2; 915 break; 916 917 case Builtin::BI__sync_bool_compare_and_swap: 918 case Builtin::BI__sync_bool_compare_and_swap_1: 919 case Builtin::BI__sync_bool_compare_and_swap_2: 920 case Builtin::BI__sync_bool_compare_and_swap_4: 921 case Builtin::BI__sync_bool_compare_and_swap_8: 922 case Builtin::BI__sync_bool_compare_and_swap_16: 923 BuiltinIndex = 11; 924 NumFixed = 2; 925 ResultType = Context.BoolTy; 926 break; 927 928 case Builtin::BI__sync_lock_test_and_set: 929 case Builtin::BI__sync_lock_test_and_set_1: 930 case Builtin::BI__sync_lock_test_and_set_2: 931 case Builtin::BI__sync_lock_test_and_set_4: 932 case Builtin::BI__sync_lock_test_and_set_8: 933 case Builtin::BI__sync_lock_test_and_set_16: 934 BuiltinIndex = 12; 935 break; 936 937 case Builtin::BI__sync_lock_release: 938 case Builtin::BI__sync_lock_release_1: 939 case Builtin::BI__sync_lock_release_2: 940 case Builtin::BI__sync_lock_release_4: 941 case Builtin::BI__sync_lock_release_8: 942 case Builtin::BI__sync_lock_release_16: 943 BuiltinIndex = 13; 944 NumFixed = 0; 945 ResultType = Context.VoidTy; 946 break; 947 948 case Builtin::BI__sync_swap: 949 case Builtin::BI__sync_swap_1: 950 case Builtin::BI__sync_swap_2: 951 case Builtin::BI__sync_swap_4: 952 case Builtin::BI__sync_swap_8: 953 case Builtin::BI__sync_swap_16: 954 BuiltinIndex = 14; 955 break; 956 } 957 958 // Now that we know how many fixed arguments we expect, first check that we 959 // have at least that many. 960 if (TheCall->getNumArgs() < 1+NumFixed) { 961 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 962 << 0 << 1+NumFixed << TheCall->getNumArgs() 963 << TheCall->getCallee()->getSourceRange(); 964 return ExprError(); 965 } 966 967 // Get the decl for the concrete builtin from this, we can tell what the 968 // concrete integer type we should convert to is. 969 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 970 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID); 971 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName); 972 FunctionDecl *NewBuiltinDecl = 973 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID, 974 TUScope, false, DRE->getLocStart())); 975 976 // The first argument --- the pointer --- has a fixed type; we 977 // deduce the types of the rest of the arguments accordingly. Walk 978 // the remaining arguments, converting them to the deduced value type. 979 for (unsigned i = 0; i != NumFixed; ++i) { 980 ExprResult Arg = TheCall->getArg(i+1); 981 982 // GCC does an implicit conversion to the pointer or integer ValType. This 983 // can fail in some cases (1i -> int**), check for this error case now. 984 // Initialize the argument. 985 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 986 ValType, /*consume*/ false); 987 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 988 if (Arg.isInvalid()) 989 return ExprError(); 990 991 // Okay, we have something that *can* be converted to the right type. Check 992 // to see if there is a potentially weird extension going on here. This can 993 // happen when you do an atomic operation on something like an char* and 994 // pass in 42. The 42 gets converted to char. This is even more strange 995 // for things like 45.123 -> char, etc. 996 // FIXME: Do this check. 997 TheCall->setArg(i+1, Arg.take()); 998 } 999 1000 ASTContext& Context = this->getASTContext(); 1001 1002 // Create a new DeclRefExpr to refer to the new decl. 1003 DeclRefExpr* NewDRE = DeclRefExpr::Create( 1004 Context, 1005 DRE->getQualifierLoc(), 1006 SourceLocation(), 1007 NewBuiltinDecl, 1008 DRE->getLocation(), 1009 NewBuiltinDecl->getType(), 1010 DRE->getValueKind()); 1011 1012 // Set the callee in the CallExpr. 1013 // FIXME: This leaks the original parens and implicit casts. 1014 ExprResult PromotedCall = UsualUnaryConversions(NewDRE); 1015 if (PromotedCall.isInvalid()) 1016 return ExprError(); 1017 TheCall->setCallee(PromotedCall.take()); 1018 1019 // Change the result type of the call to match the original value type. This 1020 // is arbitrary, but the codegen for these builtins ins design to handle it 1021 // gracefully. 1022 TheCall->setType(ResultType); 1023 1024 return move(TheCallResult); 1025} 1026 1027/// CheckObjCString - Checks that the argument to the builtin 1028/// CFString constructor is correct 1029/// Note: It might also make sense to do the UTF-16 conversion here (would 1030/// simplify the backend). 1031bool Sema::CheckObjCString(Expr *Arg) { 1032 Arg = Arg->IgnoreParenCasts(); 1033 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 1034 1035 if (!Literal || !Literal->isAscii()) { 1036 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant) 1037 << Arg->getSourceRange(); 1038 return true; 1039 } 1040 1041 if (Literal->containsNonAsciiOrNull()) { 1042 StringRef String = Literal->getString(); 1043 unsigned NumBytes = String.size(); 1044 SmallVector<UTF16, 128> ToBuf(NumBytes); 1045 const UTF8 *FromPtr = (UTF8 *)String.data(); 1046 UTF16 *ToPtr = &ToBuf[0]; 1047 1048 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, 1049 &ToPtr, ToPtr + NumBytes, 1050 strictConversion); 1051 // Check for conversion failure. 1052 if (Result != conversionOK) 1053 Diag(Arg->getLocStart(), 1054 diag::warn_cfstring_truncated) << Arg->getSourceRange(); 1055 } 1056 return false; 1057} 1058 1059/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity. 1060/// Emit an error and return true on failure, return false on success. 1061bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) { 1062 Expr *Fn = TheCall->getCallee(); 1063 if (TheCall->getNumArgs() > 2) { 1064 Diag(TheCall->getArg(2)->getLocStart(), 1065 diag::err_typecheck_call_too_many_args) 1066 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 1067 << Fn->getSourceRange() 1068 << SourceRange(TheCall->getArg(2)->getLocStart(), 1069 (*(TheCall->arg_end()-1))->getLocEnd()); 1070 return true; 1071 } 1072 1073 if (TheCall->getNumArgs() < 2) { 1074 return Diag(TheCall->getLocEnd(), 1075 diag::err_typecheck_call_too_few_args_at_least) 1076 << 0 /*function call*/ << 2 << TheCall->getNumArgs(); 1077 } 1078 1079 // Type-check the first argument normally. 1080 if (checkBuiltinArgument(*this, TheCall, 0)) 1081 return true; 1082 1083 // Determine whether the current function is variadic or not. 1084 BlockScopeInfo *CurBlock = getCurBlock(); 1085 bool isVariadic; 1086 if (CurBlock) 1087 isVariadic = CurBlock->TheDecl->isVariadic(); 1088 else if (FunctionDecl *FD = getCurFunctionDecl()) 1089 isVariadic = FD->isVariadic(); 1090 else 1091 isVariadic = getCurMethodDecl()->isVariadic(); 1092 1093 if (!isVariadic) { 1094 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function); 1095 return true; 1096 } 1097 1098 // Verify that the second argument to the builtin is the last argument of the 1099 // current function or method. 1100 bool SecondArgIsLastNamedArgument = false; 1101 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 1102 1103 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 1104 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 1105 // FIXME: This isn't correct for methods (results in bogus warning). 1106 // Get the last formal in the current function. 1107 const ParmVarDecl *LastArg; 1108 if (CurBlock) 1109 LastArg = *(CurBlock->TheDecl->param_end()-1); 1110 else if (FunctionDecl *FD = getCurFunctionDecl()) 1111 LastArg = *(FD->param_end()-1); 1112 else 1113 LastArg = *(getCurMethodDecl()->param_end()-1); 1114 SecondArgIsLastNamedArgument = PV == LastArg; 1115 } 1116 } 1117 1118 if (!SecondArgIsLastNamedArgument) 1119 Diag(TheCall->getArg(1)->getLocStart(), 1120 diag::warn_second_parameter_of_va_start_not_last_named_argument); 1121 return false; 1122} 1123 1124/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 1125/// friends. This is declared to take (...), so we have to check everything. 1126bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 1127 if (TheCall->getNumArgs() < 2) 1128 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 1129 << 0 << 2 << TheCall->getNumArgs()/*function call*/; 1130 if (TheCall->getNumArgs() > 2) 1131 return Diag(TheCall->getArg(2)->getLocStart(), 1132 diag::err_typecheck_call_too_many_args) 1133 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 1134 << SourceRange(TheCall->getArg(2)->getLocStart(), 1135 (*(TheCall->arg_end()-1))->getLocEnd()); 1136 1137 ExprResult OrigArg0 = TheCall->getArg(0); 1138 ExprResult OrigArg1 = TheCall->getArg(1); 1139 1140 // Do standard promotions between the two arguments, returning their common 1141 // type. 1142 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false); 1143 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 1144 return true; 1145 1146 // Make sure any conversions are pushed back into the call; this is 1147 // type safe since unordered compare builtins are declared as "_Bool 1148 // foo(...)". 1149 TheCall->setArg(0, OrigArg0.get()); 1150 TheCall->setArg(1, OrigArg1.get()); 1151 1152 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 1153 return false; 1154 1155 // If the common type isn't a real floating type, then the arguments were 1156 // invalid for this operation. 1157 if (!Res->isRealFloatingType()) 1158 return Diag(OrigArg0.get()->getLocStart(), 1159 diag::err_typecheck_call_invalid_ordered_compare) 1160 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 1161 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd()); 1162 1163 return false; 1164} 1165 1166/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 1167/// __builtin_isnan and friends. This is declared to take (...), so we have 1168/// to check everything. We expect the last argument to be a floating point 1169/// value. 1170bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 1171 if (TheCall->getNumArgs() < NumArgs) 1172 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 1173 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/; 1174 if (TheCall->getNumArgs() > NumArgs) 1175 return Diag(TheCall->getArg(NumArgs)->getLocStart(), 1176 diag::err_typecheck_call_too_many_args) 1177 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs() 1178 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(), 1179 (*(TheCall->arg_end()-1))->getLocEnd()); 1180 1181 Expr *OrigArg = TheCall->getArg(NumArgs-1); 1182 1183 if (OrigArg->isTypeDependent()) 1184 return false; 1185 1186 // This operation requires a non-_Complex floating-point number. 1187 if (!OrigArg->getType()->isRealFloatingType()) 1188 return Diag(OrigArg->getLocStart(), 1189 diag::err_typecheck_call_invalid_unary_fp) 1190 << OrigArg->getType() << OrigArg->getSourceRange(); 1191 1192 // If this is an implicit conversion from float -> double, remove it. 1193 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) { 1194 Expr *CastArg = Cast->getSubExpr(); 1195 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) { 1196 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) && 1197 "promotion from float to double is the only expected cast here"); 1198 Cast->setSubExpr(0); 1199 TheCall->setArg(NumArgs-1, CastArg); 1200 OrigArg = CastArg; 1201 } 1202 } 1203 1204 return false; 1205} 1206 1207/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 1208// This is declared to take (...), so we have to check everything. 1209ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 1210 if (TheCall->getNumArgs() < 2) 1211 return ExprError(Diag(TheCall->getLocEnd(), 1212 diag::err_typecheck_call_too_few_args_at_least) 1213 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 1214 << TheCall->getSourceRange()); 1215 1216 // Determine which of the following types of shufflevector we're checking: 1217 // 1) unary, vector mask: (lhs, mask) 1218 // 2) binary, vector mask: (lhs, rhs, mask) 1219 // 3) binary, scalar mask: (lhs, rhs, index, ..., index) 1220 QualType resType = TheCall->getArg(0)->getType(); 1221 unsigned numElements = 0; 1222 1223 if (!TheCall->getArg(0)->isTypeDependent() && 1224 !TheCall->getArg(1)->isTypeDependent()) { 1225 QualType LHSType = TheCall->getArg(0)->getType(); 1226 QualType RHSType = TheCall->getArg(1)->getType(); 1227 1228 if (!LHSType->isVectorType() || !RHSType->isVectorType()) { 1229 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector) 1230 << SourceRange(TheCall->getArg(0)->getLocStart(), 1231 TheCall->getArg(1)->getLocEnd()); 1232 return ExprError(); 1233 } 1234 1235 numElements = LHSType->getAs<VectorType>()->getNumElements(); 1236 unsigned numResElements = TheCall->getNumArgs() - 2; 1237 1238 // Check to see if we have a call with 2 vector arguments, the unary shuffle 1239 // with mask. If so, verify that RHS is an integer vector type with the 1240 // same number of elts as lhs. 1241 if (TheCall->getNumArgs() == 2) { 1242 if (!RHSType->hasIntegerRepresentation() || 1243 RHSType->getAs<VectorType>()->getNumElements() != numElements) 1244 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector) 1245 << SourceRange(TheCall->getArg(1)->getLocStart(), 1246 TheCall->getArg(1)->getLocEnd()); 1247 numResElements = numElements; 1248 } 1249 else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 1250 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector) 1251 << SourceRange(TheCall->getArg(0)->getLocStart(), 1252 TheCall->getArg(1)->getLocEnd()); 1253 return ExprError(); 1254 } else if (numElements != numResElements) { 1255 QualType eltType = LHSType->getAs<VectorType>()->getElementType(); 1256 resType = Context.getVectorType(eltType, numResElements, 1257 VectorType::GenericVector); 1258 } 1259 } 1260 1261 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 1262 if (TheCall->getArg(i)->isTypeDependent() || 1263 TheCall->getArg(i)->isValueDependent()) 1264 continue; 1265 1266 llvm::APSInt Result(32); 1267 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context)) 1268 return ExprError(Diag(TheCall->getLocStart(), 1269 diag::err_shufflevector_nonconstant_argument) 1270 << TheCall->getArg(i)->getSourceRange()); 1271 1272 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2) 1273 return ExprError(Diag(TheCall->getLocStart(), 1274 diag::err_shufflevector_argument_too_large) 1275 << TheCall->getArg(i)->getSourceRange()); 1276 } 1277 1278 SmallVector<Expr*, 32> exprs; 1279 1280 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 1281 exprs.push_back(TheCall->getArg(i)); 1282 TheCall->setArg(i, 0); 1283 } 1284 1285 return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(), 1286 exprs.size(), resType, 1287 TheCall->getCallee()->getLocStart(), 1288 TheCall->getRParenLoc())); 1289} 1290 1291/// SemaBuiltinPrefetch - Handle __builtin_prefetch. 1292// This is declared to take (const void*, ...) and can take two 1293// optional constant int args. 1294bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 1295 unsigned NumArgs = TheCall->getNumArgs(); 1296 1297 if (NumArgs > 3) 1298 return Diag(TheCall->getLocEnd(), 1299 diag::err_typecheck_call_too_many_args_at_most) 1300 << 0 /*function call*/ << 3 << NumArgs 1301 << TheCall->getSourceRange(); 1302 1303 // Argument 0 is checked for us and the remaining arguments must be 1304 // constant integers. 1305 for (unsigned i = 1; i != NumArgs; ++i) { 1306 Expr *Arg = TheCall->getArg(i); 1307 1308 llvm::APSInt Result; 1309 if (SemaBuiltinConstantArg(TheCall, i, Result)) 1310 return true; 1311 1312 // FIXME: gcc issues a warning and rewrites these to 0. These 1313 // seems especially odd for the third argument since the default 1314 // is 3. 1315 if (i == 1) { 1316 if (Result.getLimitedValue() > 1) 1317 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 1318 << "0" << "1" << Arg->getSourceRange(); 1319 } else { 1320 if (Result.getLimitedValue() > 3) 1321 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 1322 << "0" << "3" << Arg->getSourceRange(); 1323 } 1324 } 1325 1326 return false; 1327} 1328 1329/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 1330/// TheCall is a constant expression. 1331bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 1332 llvm::APSInt &Result) { 1333 Expr *Arg = TheCall->getArg(ArgNum); 1334 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 1335 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 1336 1337 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 1338 1339 if (!Arg->isIntegerConstantExpr(Result, Context)) 1340 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type) 1341 << FDecl->getDeclName() << Arg->getSourceRange(); 1342 1343 return false; 1344} 1345 1346/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr, 1347/// int type). This simply type checks that type is one of the defined 1348/// constants (0-3). 1349// For compatibility check 0-3, llvm only handles 0 and 2. 1350bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) { 1351 llvm::APSInt Result; 1352 1353 // Check constant-ness first. 1354 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 1355 return true; 1356 1357 Expr *Arg = TheCall->getArg(1); 1358 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) { 1359 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 1360 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 1361 } 1362 1363 return false; 1364} 1365 1366/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 1367/// This checks that val is a constant 1. 1368bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 1369 Expr *Arg = TheCall->getArg(1); 1370 llvm::APSInt Result; 1371 1372 // TODO: This is less than ideal. Overload this to take a value. 1373 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 1374 return true; 1375 1376 if (Result != 1) 1377 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val) 1378 << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 1379 1380 return false; 1381} 1382 1383// Handle i > 1 ? "x" : "y", recursively. 1384bool Sema::SemaCheckStringLiteral(const Expr *E, Expr **Args, 1385 unsigned NumArgs, bool HasVAListArg, 1386 unsigned format_idx, unsigned firstDataArg, 1387 bool isPrintf, bool inFunctionCall) { 1388 tryAgain: 1389 if (E->isTypeDependent() || E->isValueDependent()) 1390 return false; 1391 1392 E = E->IgnoreParens(); 1393 1394 switch (E->getStmtClass()) { 1395 case Stmt::BinaryConditionalOperatorClass: 1396 case Stmt::ConditionalOperatorClass: { 1397 const AbstractConditionalOperator *C = cast<AbstractConditionalOperator>(E); 1398 return SemaCheckStringLiteral(C->getTrueExpr(), Args, NumArgs, HasVAListArg, 1399 format_idx, firstDataArg, isPrintf, 1400 inFunctionCall) 1401 && SemaCheckStringLiteral(C->getFalseExpr(), Args, NumArgs, HasVAListArg, 1402 format_idx, firstDataArg, isPrintf, 1403 inFunctionCall); 1404 } 1405 1406 case Stmt::IntegerLiteralClass: 1407 // Technically -Wformat-nonliteral does not warn about this case. 1408 // The behavior of printf and friends in this case is implementation 1409 // dependent. Ideally if the format string cannot be null then 1410 // it should have a 'nonnull' attribute in the function prototype. 1411 return true; 1412 1413 case Stmt::ImplicitCastExprClass: { 1414 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 1415 goto tryAgain; 1416 } 1417 1418 case Stmt::OpaqueValueExprClass: 1419 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 1420 E = src; 1421 goto tryAgain; 1422 } 1423 return false; 1424 1425 case Stmt::PredefinedExprClass: 1426 // While __func__, etc., are technically not string literals, they 1427 // cannot contain format specifiers and thus are not a security 1428 // liability. 1429 return true; 1430 1431 case Stmt::DeclRefExprClass: { 1432 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 1433 1434 // As an exception, do not flag errors for variables binding to 1435 // const string literals. 1436 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 1437 bool isConstant = false; 1438 QualType T = DR->getType(); 1439 1440 if (const ArrayType *AT = Context.getAsArrayType(T)) { 1441 isConstant = AT->getElementType().isConstant(Context); 1442 } else if (const PointerType *PT = T->getAs<PointerType>()) { 1443 isConstant = T.isConstant(Context) && 1444 PT->getPointeeType().isConstant(Context); 1445 } else if (T->isObjCObjectPointerType()) { 1446 // In ObjC, there is usually no "const ObjectPointer" type, 1447 // so don't check if the pointee type is constant. 1448 isConstant = T.isConstant(Context); 1449 } 1450 1451 if (isConstant) { 1452 if (const Expr *Init = VD->getAnyInitializer()) 1453 return SemaCheckStringLiteral(Init, Args, NumArgs, 1454 HasVAListArg, format_idx, firstDataArg, 1455 isPrintf, /*inFunctionCall*/false); 1456 } 1457 1458 // For vprintf* functions (i.e., HasVAListArg==true), we add a 1459 // special check to see if the format string is a function parameter 1460 // of the function calling the printf function. If the function 1461 // has an attribute indicating it is a printf-like function, then we 1462 // should suppress warnings concerning non-literals being used in a call 1463 // to a vprintf function. For example: 1464 // 1465 // void 1466 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 1467 // va_list ap; 1468 // va_start(ap, fmt); 1469 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 1470 // ... 1471 // 1472 // 1473 // FIXME: We don't have full attribute support yet, so just check to see 1474 // if the argument is a DeclRefExpr that references a parameter. We'll 1475 // add proper support for checking the attribute later. 1476 if (HasVAListArg) 1477 if (isa<ParmVarDecl>(VD)) 1478 return true; 1479 } 1480 1481 return false; 1482 } 1483 1484 case Stmt::CallExprClass: { 1485 const CallExpr *CE = cast<CallExpr>(E); 1486 if (const ImplicitCastExpr *ICE 1487 = dyn_cast<ImplicitCastExpr>(CE->getCallee())) { 1488 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) { 1489 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) { 1490 if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) { 1491 unsigned ArgIndex = FA->getFormatIdx(); 1492 const Expr *Arg = CE->getArg(ArgIndex - 1); 1493 1494 return SemaCheckStringLiteral(Arg, Args, NumArgs, HasVAListArg, 1495 format_idx, firstDataArg, isPrintf, 1496 inFunctionCall); 1497 } 1498 } 1499 } 1500 } 1501 1502 return false; 1503 } 1504 case Stmt::ObjCStringLiteralClass: 1505 case Stmt::StringLiteralClass: { 1506 const StringLiteral *StrE = NULL; 1507 1508 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 1509 StrE = ObjCFExpr->getString(); 1510 else 1511 StrE = cast<StringLiteral>(E); 1512 1513 if (StrE) { 1514 CheckFormatString(StrE, E, Args, NumArgs, HasVAListArg, format_idx, 1515 firstDataArg, isPrintf, inFunctionCall); 1516 return true; 1517 } 1518 1519 return false; 1520 } 1521 1522 default: 1523 return false; 1524 } 1525} 1526 1527void 1528Sema::CheckNonNullArguments(const NonNullAttr *NonNull, 1529 const Expr * const *ExprArgs, 1530 SourceLocation CallSiteLoc) { 1531 for (NonNullAttr::args_iterator i = NonNull->args_begin(), 1532 e = NonNull->args_end(); 1533 i != e; ++i) { 1534 const Expr *ArgExpr = ExprArgs[*i]; 1535 if (ArgExpr->isNullPointerConstant(Context, 1536 Expr::NPC_ValueDependentIsNotNull)) 1537 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 1538 } 1539} 1540 1541/// CheckPrintfScanfArguments - Check calls to printf and scanf (and similar 1542/// functions) for correct use of format strings. 1543void Sema::CheckFormatArguments(const FormatAttr *Format, CallExpr *TheCall) { 1544 bool IsCXXMember = false; 1545 // The way the format attribute works in GCC, the implicit this argument 1546 // of member functions is counted. However, it doesn't appear in our own 1547 // lists, so decrement format_idx in that case. 1548 if (isa<CXXMemberCallExpr>(TheCall)) { 1549 const CXXMethodDecl *method_decl = 1550 dyn_cast<CXXMethodDecl>(TheCall->getCalleeDecl()); 1551 IsCXXMember = method_decl && method_decl->isInstance(); 1552 } 1553 CheckFormatArguments(Format, TheCall->getArgs(), TheCall->getNumArgs(), 1554 IsCXXMember, TheCall->getRParenLoc(), 1555 TheCall->getCallee()->getSourceRange()); 1556} 1557 1558void Sema::CheckFormatArguments(const FormatAttr *Format, Expr **Args, 1559 unsigned NumArgs, bool IsCXXMember, 1560 SourceLocation Loc, SourceRange Range) { 1561 const bool b = Format->getType() == "scanf"; 1562 if (b || CheckablePrintfAttr(Format, Args, NumArgs, IsCXXMember)) { 1563 bool HasVAListArg = Format->getFirstArg() == 0; 1564 unsigned format_idx = Format->getFormatIdx() - 1; 1565 unsigned firstDataArg = HasVAListArg ? 0 : Format->getFirstArg() - 1; 1566 if (IsCXXMember) { 1567 if (format_idx == 0) 1568 return; 1569 --format_idx; 1570 if(firstDataArg != 0) 1571 --firstDataArg; 1572 } 1573 CheckPrintfScanfArguments(Args, NumArgs, HasVAListArg, format_idx, 1574 firstDataArg, !b, Loc, Range); 1575 } 1576} 1577 1578void Sema::CheckPrintfScanfArguments(Expr **Args, unsigned NumArgs, 1579 bool HasVAListArg, unsigned format_idx, 1580 unsigned firstDataArg, bool isPrintf, 1581 SourceLocation Loc, SourceRange Range) { 1582 // CHECK: printf/scanf-like function is called with no format string. 1583 if (format_idx >= NumArgs) { 1584 Diag(Loc, diag::warn_missing_format_string) << Range; 1585 return; 1586 } 1587 1588 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 1589 1590 // CHECK: format string is not a string literal. 1591 // 1592 // Dynamically generated format strings are difficult to 1593 // automatically vet at compile time. Requiring that format strings 1594 // are string literals: (1) permits the checking of format strings by 1595 // the compiler and thereby (2) can practically remove the source of 1596 // many format string exploits. 1597 1598 // Format string can be either ObjC string (e.g. @"%d") or 1599 // C string (e.g. "%d") 1600 // ObjC string uses the same format specifiers as C string, so we can use 1601 // the same format string checking logic for both ObjC and C strings. 1602 if (SemaCheckStringLiteral(OrigFormatExpr, Args, NumArgs, HasVAListArg, 1603 format_idx, firstDataArg, isPrintf)) 1604 return; // Literal format string found, check done! 1605 1606 // If there are no arguments specified, warn with -Wformat-security, otherwise 1607 // warn only with -Wformat-nonliteral. 1608 if (NumArgs == format_idx+1) 1609 Diag(Args[format_idx]->getLocStart(), 1610 diag::warn_format_nonliteral_noargs) 1611 << OrigFormatExpr->getSourceRange(); 1612 else 1613 Diag(Args[format_idx]->getLocStart(), 1614 diag::warn_format_nonliteral) 1615 << OrigFormatExpr->getSourceRange(); 1616} 1617 1618namespace { 1619class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 1620protected: 1621 Sema &S; 1622 const StringLiteral *FExpr; 1623 const Expr *OrigFormatExpr; 1624 const unsigned FirstDataArg; 1625 const unsigned NumDataArgs; 1626 const bool IsObjCLiteral; 1627 const char *Beg; // Start of format string. 1628 const bool HasVAListArg; 1629 const Expr * const *Args; 1630 const unsigned NumArgs; 1631 unsigned FormatIdx; 1632 llvm::BitVector CoveredArgs; 1633 bool usesPositionalArgs; 1634 bool atFirstArg; 1635 bool inFunctionCall; 1636public: 1637 CheckFormatHandler(Sema &s, const StringLiteral *fexpr, 1638 const Expr *origFormatExpr, unsigned firstDataArg, 1639 unsigned numDataArgs, bool isObjCLiteral, 1640 const char *beg, bool hasVAListArg, 1641 Expr **args, unsigned numArgs, 1642 unsigned formatIdx, bool inFunctionCall) 1643 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), 1644 FirstDataArg(firstDataArg), 1645 NumDataArgs(numDataArgs), 1646 IsObjCLiteral(isObjCLiteral), Beg(beg), 1647 HasVAListArg(hasVAListArg), 1648 Args(args), NumArgs(numArgs), FormatIdx(formatIdx), 1649 usesPositionalArgs(false), atFirstArg(true), 1650 inFunctionCall(inFunctionCall) { 1651 CoveredArgs.resize(numDataArgs); 1652 CoveredArgs.reset(); 1653 } 1654 1655 void DoneProcessing(); 1656 1657 void HandleIncompleteSpecifier(const char *startSpecifier, 1658 unsigned specifierLen); 1659 1660 virtual void HandleInvalidPosition(const char *startSpecifier, 1661 unsigned specifierLen, 1662 analyze_format_string::PositionContext p); 1663 1664 virtual void HandleZeroPosition(const char *startPos, unsigned posLen); 1665 1666 void HandleNullChar(const char *nullCharacter); 1667 1668 template <typename Range> 1669 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall, 1670 const Expr *ArgumentExpr, 1671 PartialDiagnostic PDiag, 1672 SourceLocation StringLoc, 1673 bool IsStringLocation, Range StringRange, 1674 FixItHint Fixit = FixItHint()); 1675 1676protected: 1677 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 1678 const char *startSpec, 1679 unsigned specifierLen, 1680 const char *csStart, unsigned csLen); 1681 1682 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 1683 const char *startSpec, 1684 unsigned specifierLen); 1685 1686 SourceRange getFormatStringRange(); 1687 CharSourceRange getSpecifierRange(const char *startSpecifier, 1688 unsigned specifierLen); 1689 SourceLocation getLocationOfByte(const char *x); 1690 1691 const Expr *getDataArg(unsigned i) const; 1692 1693 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 1694 const analyze_format_string::ConversionSpecifier &CS, 1695 const char *startSpecifier, unsigned specifierLen, 1696 unsigned argIndex); 1697 1698 template <typename Range> 1699 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 1700 bool IsStringLocation, Range StringRange, 1701 FixItHint Fixit = FixItHint()); 1702 1703 void CheckPositionalAndNonpositionalArgs( 1704 const analyze_format_string::FormatSpecifier *FS); 1705}; 1706} 1707 1708SourceRange CheckFormatHandler::getFormatStringRange() { 1709 return OrigFormatExpr->getSourceRange(); 1710} 1711 1712CharSourceRange CheckFormatHandler:: 1713getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 1714 SourceLocation Start = getLocationOfByte(startSpecifier); 1715 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 1716 1717 // Advance the end SourceLocation by one due to half-open ranges. 1718 End = End.getLocWithOffset(1); 1719 1720 return CharSourceRange::getCharRange(Start, End); 1721} 1722 1723SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 1724 return S.getLocationOfStringLiteralByte(FExpr, x - Beg); 1725} 1726 1727void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 1728 unsigned specifierLen){ 1729 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 1730 getLocationOfByte(startSpecifier), 1731 /*IsStringLocation*/true, 1732 getSpecifierRange(startSpecifier, specifierLen)); 1733} 1734 1735void 1736CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 1737 analyze_format_string::PositionContext p) { 1738 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 1739 << (unsigned) p, 1740 getLocationOfByte(startPos), /*IsStringLocation*/true, 1741 getSpecifierRange(startPos, posLen)); 1742} 1743 1744void CheckFormatHandler::HandleZeroPosition(const char *startPos, 1745 unsigned posLen) { 1746 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 1747 getLocationOfByte(startPos), 1748 /*IsStringLocation*/true, 1749 getSpecifierRange(startPos, posLen)); 1750} 1751 1752void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 1753 if (!IsObjCLiteral) { 1754 // The presence of a null character is likely an error. 1755 EmitFormatDiagnostic( 1756 S.PDiag(diag::warn_printf_format_string_contains_null_char), 1757 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 1758 getFormatStringRange()); 1759 } 1760} 1761 1762const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 1763 return Args[FirstDataArg + i]; 1764} 1765 1766void CheckFormatHandler::DoneProcessing() { 1767 // Does the number of data arguments exceed the number of 1768 // format conversions in the format string? 1769 if (!HasVAListArg) { 1770 // Find any arguments that weren't covered. 1771 CoveredArgs.flip(); 1772 signed notCoveredArg = CoveredArgs.find_first(); 1773 if (notCoveredArg >= 0) { 1774 assert((unsigned)notCoveredArg < NumDataArgs); 1775 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used), 1776 getDataArg((unsigned) notCoveredArg)->getLocStart(), 1777 /*IsStringLocation*/false, getFormatStringRange()); 1778 } 1779 } 1780} 1781 1782bool 1783CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 1784 SourceLocation Loc, 1785 const char *startSpec, 1786 unsigned specifierLen, 1787 const char *csStart, 1788 unsigned csLen) { 1789 1790 bool keepGoing = true; 1791 if (argIndex < NumDataArgs) { 1792 // Consider the argument coverered, even though the specifier doesn't 1793 // make sense. 1794 CoveredArgs.set(argIndex); 1795 } 1796 else { 1797 // If argIndex exceeds the number of data arguments we 1798 // don't issue a warning because that is just a cascade of warnings (and 1799 // they may have intended '%%' anyway). We don't want to continue processing 1800 // the format string after this point, however, as we will like just get 1801 // gibberish when trying to match arguments. 1802 keepGoing = false; 1803 } 1804 1805 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion) 1806 << StringRef(csStart, csLen), 1807 Loc, /*IsStringLocation*/true, 1808 getSpecifierRange(startSpec, specifierLen)); 1809 1810 return keepGoing; 1811} 1812 1813void 1814CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 1815 const char *startSpec, 1816 unsigned specifierLen) { 1817 EmitFormatDiagnostic( 1818 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 1819 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 1820} 1821 1822bool 1823CheckFormatHandler::CheckNumArgs( 1824 const analyze_format_string::FormatSpecifier &FS, 1825 const analyze_format_string::ConversionSpecifier &CS, 1826 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 1827 1828 if (argIndex >= NumDataArgs) { 1829 PartialDiagnostic PDiag = FS.usesPositionalArg() 1830 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 1831 << (argIndex+1) << NumDataArgs) 1832 : S.PDiag(diag::warn_printf_insufficient_data_args); 1833 EmitFormatDiagnostic( 1834 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 1835 getSpecifierRange(startSpecifier, specifierLen)); 1836 return false; 1837 } 1838 return true; 1839} 1840 1841template<typename Range> 1842void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 1843 SourceLocation Loc, 1844 bool IsStringLocation, 1845 Range StringRange, 1846 FixItHint FixIt) { 1847 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 1848 Loc, IsStringLocation, StringRange, FixIt); 1849} 1850 1851/// \brief If the format string is not within the funcion call, emit a note 1852/// so that the function call and string are in diagnostic messages. 1853/// 1854/// \param inFunctionCall if true, the format string is within the function 1855/// call and only one diagnostic message will be produced. Otherwise, an 1856/// extra note will be emitted pointing to location of the format string. 1857/// 1858/// \param ArgumentExpr the expression that is passed as the format string 1859/// argument in the function call. Used for getting locations when two 1860/// diagnostics are emitted. 1861/// 1862/// \param PDiag the callee should already have provided any strings for the 1863/// diagnostic message. This function only adds locations and fixits 1864/// to diagnostics. 1865/// 1866/// \param Loc primary location for diagnostic. If two diagnostics are 1867/// required, one will be at Loc and a new SourceLocation will be created for 1868/// the other one. 1869/// 1870/// \param IsStringLocation if true, Loc points to the format string should be 1871/// used for the note. Otherwise, Loc points to the argument list and will 1872/// be used with PDiag. 1873/// 1874/// \param StringRange some or all of the string to highlight. This is 1875/// templated so it can accept either a CharSourceRange or a SourceRange. 1876/// 1877/// \param Fixit optional fix it hint for the format string. 1878template<typename Range> 1879void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall, 1880 const Expr *ArgumentExpr, 1881 PartialDiagnostic PDiag, 1882 SourceLocation Loc, 1883 bool IsStringLocation, 1884 Range StringRange, 1885 FixItHint FixIt) { 1886 if (InFunctionCall) 1887 S.Diag(Loc, PDiag) << StringRange << FixIt; 1888 else { 1889 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 1890 << ArgumentExpr->getSourceRange(); 1891 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 1892 diag::note_format_string_defined) 1893 << StringRange << FixIt; 1894 } 1895} 1896 1897//===--- CHECK: Printf format string checking ------------------------------===// 1898 1899namespace { 1900class CheckPrintfHandler : public CheckFormatHandler { 1901public: 1902 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr, 1903 const Expr *origFormatExpr, unsigned firstDataArg, 1904 unsigned numDataArgs, bool isObjCLiteral, 1905 const char *beg, bool hasVAListArg, 1906 Expr **Args, unsigned NumArgs, 1907 unsigned formatIdx, bool inFunctionCall) 1908 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg, 1909 numDataArgs, isObjCLiteral, beg, hasVAListArg, 1910 Args, NumArgs, formatIdx, inFunctionCall) {} 1911 1912 1913 bool HandleInvalidPrintfConversionSpecifier( 1914 const analyze_printf::PrintfSpecifier &FS, 1915 const char *startSpecifier, 1916 unsigned specifierLen); 1917 1918 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 1919 const char *startSpecifier, 1920 unsigned specifierLen); 1921 1922 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 1923 const char *startSpecifier, unsigned specifierLen); 1924 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 1925 const analyze_printf::OptionalAmount &Amt, 1926 unsigned type, 1927 const char *startSpecifier, unsigned specifierLen); 1928 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 1929 const analyze_printf::OptionalFlag &flag, 1930 const char *startSpecifier, unsigned specifierLen); 1931 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 1932 const analyze_printf::OptionalFlag &ignoredFlag, 1933 const analyze_printf::OptionalFlag &flag, 1934 const char *startSpecifier, unsigned specifierLen); 1935}; 1936} 1937 1938bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 1939 const analyze_printf::PrintfSpecifier &FS, 1940 const char *startSpecifier, 1941 unsigned specifierLen) { 1942 const analyze_printf::PrintfConversionSpecifier &CS = 1943 FS.getConversionSpecifier(); 1944 1945 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 1946 getLocationOfByte(CS.getStart()), 1947 startSpecifier, specifierLen, 1948 CS.getStart(), CS.getLength()); 1949} 1950 1951bool CheckPrintfHandler::HandleAmount( 1952 const analyze_format_string::OptionalAmount &Amt, 1953 unsigned k, const char *startSpecifier, 1954 unsigned specifierLen) { 1955 1956 if (Amt.hasDataArgument()) { 1957 if (!HasVAListArg) { 1958 unsigned argIndex = Amt.getArgIndex(); 1959 if (argIndex >= NumDataArgs) { 1960 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 1961 << k, 1962 getLocationOfByte(Amt.getStart()), 1963 /*IsStringLocation*/true, 1964 getSpecifierRange(startSpecifier, specifierLen)); 1965 // Don't do any more checking. We will just emit 1966 // spurious errors. 1967 return false; 1968 } 1969 1970 // Type check the data argument. It should be an 'int'. 1971 // Although not in conformance with C99, we also allow the argument to be 1972 // an 'unsigned int' as that is a reasonably safe case. GCC also 1973 // doesn't emit a warning for that case. 1974 CoveredArgs.set(argIndex); 1975 const Expr *Arg = getDataArg(argIndex); 1976 QualType T = Arg->getType(); 1977 1978 const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context); 1979 assert(ATR.isValid()); 1980 1981 if (!ATR.matchesType(S.Context, T)) { 1982 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 1983 << k << ATR.getRepresentativeTypeName(S.Context) 1984 << T << Arg->getSourceRange(), 1985 getLocationOfByte(Amt.getStart()), 1986 /*IsStringLocation*/true, 1987 getSpecifierRange(startSpecifier, specifierLen)); 1988 // Don't do any more checking. We will just emit 1989 // spurious errors. 1990 return false; 1991 } 1992 } 1993 } 1994 return true; 1995} 1996 1997void CheckPrintfHandler::HandleInvalidAmount( 1998 const analyze_printf::PrintfSpecifier &FS, 1999 const analyze_printf::OptionalAmount &Amt, 2000 unsigned type, 2001 const char *startSpecifier, 2002 unsigned specifierLen) { 2003 const analyze_printf::PrintfConversionSpecifier &CS = 2004 FS.getConversionSpecifier(); 2005 2006 FixItHint fixit = 2007 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 2008 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 2009 Amt.getConstantLength())) 2010 : FixItHint(); 2011 2012 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 2013 << type << CS.toString(), 2014 getLocationOfByte(Amt.getStart()), 2015 /*IsStringLocation*/true, 2016 getSpecifierRange(startSpecifier, specifierLen), 2017 fixit); 2018} 2019 2020void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 2021 const analyze_printf::OptionalFlag &flag, 2022 const char *startSpecifier, 2023 unsigned specifierLen) { 2024 // Warn about pointless flag with a fixit removal. 2025 const analyze_printf::PrintfConversionSpecifier &CS = 2026 FS.getConversionSpecifier(); 2027 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 2028 << flag.toString() << CS.toString(), 2029 getLocationOfByte(flag.getPosition()), 2030 /*IsStringLocation*/true, 2031 getSpecifierRange(startSpecifier, specifierLen), 2032 FixItHint::CreateRemoval( 2033 getSpecifierRange(flag.getPosition(), 1))); 2034} 2035 2036void CheckPrintfHandler::HandleIgnoredFlag( 2037 const analyze_printf::PrintfSpecifier &FS, 2038 const analyze_printf::OptionalFlag &ignoredFlag, 2039 const analyze_printf::OptionalFlag &flag, 2040 const char *startSpecifier, 2041 unsigned specifierLen) { 2042 // Warn about ignored flag with a fixit removal. 2043 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 2044 << ignoredFlag.toString() << flag.toString(), 2045 getLocationOfByte(ignoredFlag.getPosition()), 2046 /*IsStringLocation*/true, 2047 getSpecifierRange(startSpecifier, specifierLen), 2048 FixItHint::CreateRemoval( 2049 getSpecifierRange(ignoredFlag.getPosition(), 1))); 2050} 2051 2052bool 2053CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 2054 &FS, 2055 const char *startSpecifier, 2056 unsigned specifierLen) { 2057 2058 using namespace analyze_format_string; 2059 using namespace analyze_printf; 2060 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 2061 2062 if (FS.consumesDataArgument()) { 2063 if (atFirstArg) { 2064 atFirstArg = false; 2065 usesPositionalArgs = FS.usesPositionalArg(); 2066 } 2067 else if (usesPositionalArgs != FS.usesPositionalArg()) { 2068 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 2069 startSpecifier, specifierLen); 2070 return false; 2071 } 2072 } 2073 2074 // First check if the field width, precision, and conversion specifier 2075 // have matching data arguments. 2076 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 2077 startSpecifier, specifierLen)) { 2078 return false; 2079 } 2080 2081 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 2082 startSpecifier, specifierLen)) { 2083 return false; 2084 } 2085 2086 if (!CS.consumesDataArgument()) { 2087 // FIXME: Technically specifying a precision or field width here 2088 // makes no sense. Worth issuing a warning at some point. 2089 return true; 2090 } 2091 2092 // Consume the argument. 2093 unsigned argIndex = FS.getArgIndex(); 2094 if (argIndex < NumDataArgs) { 2095 // The check to see if the argIndex is valid will come later. 2096 // We set the bit here because we may exit early from this 2097 // function if we encounter some other error. 2098 CoveredArgs.set(argIndex); 2099 } 2100 2101 // Check for using an Objective-C specific conversion specifier 2102 // in a non-ObjC literal. 2103 if (!IsObjCLiteral && CS.isObjCArg()) { 2104 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 2105 specifierLen); 2106 } 2107 2108 // Check for invalid use of field width 2109 if (!FS.hasValidFieldWidth()) { 2110 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 2111 startSpecifier, specifierLen); 2112 } 2113 2114 // Check for invalid use of precision 2115 if (!FS.hasValidPrecision()) { 2116 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 2117 startSpecifier, specifierLen); 2118 } 2119 2120 // Check each flag does not conflict with any other component. 2121 if (!FS.hasValidThousandsGroupingPrefix()) 2122 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 2123 if (!FS.hasValidLeadingZeros()) 2124 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 2125 if (!FS.hasValidPlusPrefix()) 2126 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 2127 if (!FS.hasValidSpacePrefix()) 2128 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 2129 if (!FS.hasValidAlternativeForm()) 2130 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 2131 if (!FS.hasValidLeftJustified()) 2132 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 2133 2134 // Check that flags are not ignored by another flag 2135 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 2136 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 2137 startSpecifier, specifierLen); 2138 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 2139 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 2140 startSpecifier, specifierLen); 2141 2142 // Check the length modifier is valid with the given conversion specifier. 2143 const LengthModifier &LM = FS.getLengthModifier(); 2144 if (!FS.hasValidLengthModifier()) 2145 EmitFormatDiagnostic(S.PDiag(diag::warn_format_nonsensical_length) 2146 << LM.toString() << CS.toString(), 2147 getLocationOfByte(LM.getStart()), 2148 /*IsStringLocation*/true, 2149 getSpecifierRange(startSpecifier, specifierLen), 2150 FixItHint::CreateRemoval( 2151 getSpecifierRange(LM.getStart(), 2152 LM.getLength()))); 2153 2154 // Are we using '%n'? 2155 if (CS.getKind() == ConversionSpecifier::nArg) { 2156 // Issue a warning about this being a possible security issue. 2157 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_write_back), 2158 getLocationOfByte(CS.getStart()), 2159 /*IsStringLocation*/true, 2160 getSpecifierRange(startSpecifier, specifierLen)); 2161 // Continue checking the other format specifiers. 2162 return true; 2163 } 2164 2165 // The remaining checks depend on the data arguments. 2166 if (HasVAListArg) 2167 return true; 2168 2169 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 2170 return false; 2171 2172 // Now type check the data expression that matches the 2173 // format specifier. 2174 const Expr *Ex = getDataArg(argIndex); 2175 const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context); 2176 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) { 2177 // Check if we didn't match because of an implicit cast from a 'char' 2178 // or 'short' to an 'int'. This is done because printf is a varargs 2179 // function. 2180 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex)) 2181 if (ICE->getType() == S.Context.IntTy) { 2182 // All further checking is done on the subexpression. 2183 Ex = ICE->getSubExpr(); 2184 if (ATR.matchesType(S.Context, Ex->getType())) 2185 return true; 2186 } 2187 2188 // We may be able to offer a FixItHint if it is a supported type. 2189 PrintfSpecifier fixedFS = FS; 2190 bool success = fixedFS.fixType(Ex->getType(), S.getLangOptions()); 2191 2192 if (success) { 2193 // Get the fix string from the fixed format specifier 2194 llvm::SmallString<128> buf; 2195 llvm::raw_svector_ostream os(buf); 2196 fixedFS.toString(os); 2197 2198 EmitFormatDiagnostic( 2199 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch) 2200 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType() 2201 << Ex->getSourceRange(), 2202 getLocationOfByte(CS.getStart()), 2203 /*IsStringLocation*/true, 2204 getSpecifierRange(startSpecifier, specifierLen), 2205 FixItHint::CreateReplacement( 2206 getSpecifierRange(startSpecifier, specifierLen), 2207 os.str())); 2208 } 2209 else { 2210 S.Diag(getLocationOfByte(CS.getStart()), 2211 diag::warn_printf_conversion_argument_type_mismatch) 2212 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType() 2213 << getSpecifierRange(startSpecifier, specifierLen) 2214 << Ex->getSourceRange(); 2215 } 2216 } 2217 2218 return true; 2219} 2220 2221//===--- CHECK: Scanf format string checking ------------------------------===// 2222 2223namespace { 2224class CheckScanfHandler : public CheckFormatHandler { 2225public: 2226 CheckScanfHandler(Sema &s, const StringLiteral *fexpr, 2227 const Expr *origFormatExpr, unsigned firstDataArg, 2228 unsigned numDataArgs, bool isObjCLiteral, 2229 const char *beg, bool hasVAListArg, 2230 Expr **Args, unsigned NumArgs, 2231 unsigned formatIdx, bool inFunctionCall) 2232 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg, 2233 numDataArgs, isObjCLiteral, beg, hasVAListArg, 2234 Args, NumArgs, formatIdx, inFunctionCall) {} 2235 2236 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 2237 const char *startSpecifier, 2238 unsigned specifierLen); 2239 2240 bool HandleInvalidScanfConversionSpecifier( 2241 const analyze_scanf::ScanfSpecifier &FS, 2242 const char *startSpecifier, 2243 unsigned specifierLen); 2244 2245 void HandleIncompleteScanList(const char *start, const char *end); 2246}; 2247} 2248 2249void CheckScanfHandler::HandleIncompleteScanList(const char *start, 2250 const char *end) { 2251 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 2252 getLocationOfByte(end), /*IsStringLocation*/true, 2253 getSpecifierRange(start, end - start)); 2254} 2255 2256bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 2257 const analyze_scanf::ScanfSpecifier &FS, 2258 const char *startSpecifier, 2259 unsigned specifierLen) { 2260 2261 const analyze_scanf::ScanfConversionSpecifier &CS = 2262 FS.getConversionSpecifier(); 2263 2264 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 2265 getLocationOfByte(CS.getStart()), 2266 startSpecifier, specifierLen, 2267 CS.getStart(), CS.getLength()); 2268} 2269 2270bool CheckScanfHandler::HandleScanfSpecifier( 2271 const analyze_scanf::ScanfSpecifier &FS, 2272 const char *startSpecifier, 2273 unsigned specifierLen) { 2274 2275 using namespace analyze_scanf; 2276 using namespace analyze_format_string; 2277 2278 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 2279 2280 // Handle case where '%' and '*' don't consume an argument. These shouldn't 2281 // be used to decide if we are using positional arguments consistently. 2282 if (FS.consumesDataArgument()) { 2283 if (atFirstArg) { 2284 atFirstArg = false; 2285 usesPositionalArgs = FS.usesPositionalArg(); 2286 } 2287 else if (usesPositionalArgs != FS.usesPositionalArg()) { 2288 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 2289 startSpecifier, specifierLen); 2290 return false; 2291 } 2292 } 2293 2294 // Check if the field with is non-zero. 2295 const OptionalAmount &Amt = FS.getFieldWidth(); 2296 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 2297 if (Amt.getConstantAmount() == 0) { 2298 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 2299 Amt.getConstantLength()); 2300 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 2301 getLocationOfByte(Amt.getStart()), 2302 /*IsStringLocation*/true, R, 2303 FixItHint::CreateRemoval(R)); 2304 } 2305 } 2306 2307 if (!FS.consumesDataArgument()) { 2308 // FIXME: Technically specifying a precision or field width here 2309 // makes no sense. Worth issuing a warning at some point. 2310 return true; 2311 } 2312 2313 // Consume the argument. 2314 unsigned argIndex = FS.getArgIndex(); 2315 if (argIndex < NumDataArgs) { 2316 // The check to see if the argIndex is valid will come later. 2317 // We set the bit here because we may exit early from this 2318 // function if we encounter some other error. 2319 CoveredArgs.set(argIndex); 2320 } 2321 2322 // Check the length modifier is valid with the given conversion specifier. 2323 const LengthModifier &LM = FS.getLengthModifier(); 2324 if (!FS.hasValidLengthModifier()) { 2325 S.Diag(getLocationOfByte(LM.getStart()), 2326 diag::warn_format_nonsensical_length) 2327 << LM.toString() << CS.toString() 2328 << getSpecifierRange(startSpecifier, specifierLen) 2329 << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(), 2330 LM.getLength())); 2331 } 2332 2333 // The remaining checks depend on the data arguments. 2334 if (HasVAListArg) 2335 return true; 2336 2337 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 2338 return false; 2339 2340 // Check that the argument type matches the format specifier. 2341 const Expr *Ex = getDataArg(argIndex); 2342 const analyze_scanf::ScanfArgTypeResult &ATR = FS.getArgType(S.Context); 2343 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) { 2344 ScanfSpecifier fixedFS = FS; 2345 bool success = fixedFS.fixType(Ex->getType(), S.getLangOptions()); 2346 2347 if (success) { 2348 // Get the fix string from the fixed format specifier. 2349 llvm::SmallString<128> buf; 2350 llvm::raw_svector_ostream os(buf); 2351 fixedFS.toString(os); 2352 2353 EmitFormatDiagnostic( 2354 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch) 2355 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType() 2356 << Ex->getSourceRange(), 2357 getLocationOfByte(CS.getStart()), 2358 /*IsStringLocation*/true, 2359 getSpecifierRange(startSpecifier, specifierLen), 2360 FixItHint::CreateReplacement( 2361 getSpecifierRange(startSpecifier, specifierLen), 2362 os.str())); 2363 } else { 2364 S.Diag(getLocationOfByte(CS.getStart()), 2365 diag::warn_printf_conversion_argument_type_mismatch) 2366 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType() 2367 << getSpecifierRange(startSpecifier, specifierLen) 2368 << Ex->getSourceRange(); 2369 } 2370 } 2371 2372 return true; 2373} 2374 2375void Sema::CheckFormatString(const StringLiteral *FExpr, 2376 const Expr *OrigFormatExpr, 2377 Expr **Args, unsigned NumArgs, 2378 bool HasVAListArg, unsigned format_idx, 2379 unsigned firstDataArg, bool isPrintf, 2380 bool inFunctionCall) { 2381 2382 // CHECK: is the format string a wide literal? 2383 if (!FExpr->isAscii()) { 2384 CheckFormatHandler::EmitFormatDiagnostic( 2385 *this, inFunctionCall, Args[format_idx], 2386 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(), 2387 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 2388 return; 2389 } 2390 2391 // Str - The format string. NOTE: this is NOT null-terminated! 2392 StringRef StrRef = FExpr->getString(); 2393 const char *Str = StrRef.data(); 2394 unsigned StrLen = StrRef.size(); 2395 const unsigned numDataArgs = NumArgs - firstDataArg; 2396 2397 // CHECK: empty format string? 2398 if (StrLen == 0 && numDataArgs > 0) { 2399 CheckFormatHandler::EmitFormatDiagnostic( 2400 *this, inFunctionCall, Args[format_idx], 2401 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(), 2402 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 2403 return; 2404 } 2405 2406 if (isPrintf) { 2407 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, 2408 numDataArgs, isa<ObjCStringLiteral>(OrigFormatExpr), 2409 Str, HasVAListArg, Args, NumArgs, format_idx, 2410 inFunctionCall); 2411 2412 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 2413 getLangOptions())) 2414 H.DoneProcessing(); 2415 } 2416 else { 2417 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, 2418 numDataArgs, isa<ObjCStringLiteral>(OrigFormatExpr), 2419 Str, HasVAListArg, Args, NumArgs, format_idx, 2420 inFunctionCall); 2421 2422 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 2423 getLangOptions())) 2424 H.DoneProcessing(); 2425 } 2426} 2427 2428//===--- CHECK: Standard memory functions ---------------------------------===// 2429 2430/// \brief Determine whether the given type is a dynamic class type (e.g., 2431/// whether it has a vtable). 2432static bool isDynamicClassType(QualType T) { 2433 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 2434 if (CXXRecordDecl *Definition = Record->getDefinition()) 2435 if (Definition->isDynamicClass()) 2436 return true; 2437 2438 return false; 2439} 2440 2441/// \brief If E is a sizeof expression, returns its argument expression, 2442/// otherwise returns NULL. 2443static const Expr *getSizeOfExprArg(const Expr* E) { 2444 if (const UnaryExprOrTypeTraitExpr *SizeOf = 2445 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 2446 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType()) 2447 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 2448 2449 return 0; 2450} 2451 2452/// \brief If E is a sizeof expression, returns its argument type. 2453static QualType getSizeOfArgType(const Expr* E) { 2454 if (const UnaryExprOrTypeTraitExpr *SizeOf = 2455 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 2456 if (SizeOf->getKind() == clang::UETT_SizeOf) 2457 return SizeOf->getTypeOfArgument(); 2458 2459 return QualType(); 2460} 2461 2462/// \brief Check for dangerous or invalid arguments to memset(). 2463/// 2464/// This issues warnings on known problematic, dangerous or unspecified 2465/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 2466/// function calls. 2467/// 2468/// \param Call The call expression to diagnose. 2469void Sema::CheckMemaccessArguments(const CallExpr *Call, 2470 unsigned BId, 2471 IdentifierInfo *FnName) { 2472 assert(BId != 0); 2473 2474 // It is possible to have a non-standard definition of memset. Validate 2475 // we have enough arguments, and if not, abort further checking. 2476 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3); 2477 if (Call->getNumArgs() < ExpectedNumArgs) 2478 return; 2479 2480 unsigned LastArg = (BId == Builtin::BImemset || 2481 BId == Builtin::BIstrndup ? 1 : 2); 2482 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2); 2483 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 2484 2485 // We have special checking when the length is a sizeof expression. 2486 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 2487 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 2488 llvm::FoldingSetNodeID SizeOfArgID; 2489 2490 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 2491 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 2492 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 2493 2494 QualType DestTy = Dest->getType(); 2495 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 2496 QualType PointeeTy = DestPtrTy->getPointeeType(); 2497 2498 // Never warn about void type pointers. This can be used to suppress 2499 // false positives. 2500 if (PointeeTy->isVoidType()) 2501 continue; 2502 2503 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 2504 // actually comparing the expressions for equality. Because computing the 2505 // expression IDs can be expensive, we only do this if the diagnostic is 2506 // enabled. 2507 if (SizeOfArg && 2508 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess, 2509 SizeOfArg->getExprLoc())) { 2510 // We only compute IDs for expressions if the warning is enabled, and 2511 // cache the sizeof arg's ID. 2512 if (SizeOfArgID == llvm::FoldingSetNodeID()) 2513 SizeOfArg->Profile(SizeOfArgID, Context, true); 2514 llvm::FoldingSetNodeID DestID; 2515 Dest->Profile(DestID, Context, true); 2516 if (DestID == SizeOfArgID) { 2517 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 2518 // over sizeof(src) as well. 2519 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 2520 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 2521 if (UnaryOp->getOpcode() == UO_AddrOf) 2522 ActionIdx = 1; // If its an address-of operator, just remove it. 2523 if (Context.getTypeSize(PointeeTy) == Context.getCharWidth()) 2524 ActionIdx = 2; // If the pointee's size is sizeof(char), 2525 // suggest an explicit length. 2526 unsigned DestSrcSelect = 2527 (BId == Builtin::BIstrndup ? 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 2555 unsigned OperationType = 0; 2556 // "overwritten" if we're warning about the destination for any call 2557 // but memcmp; otherwise a verb appropriate to the call. 2558 if (ArgIdx != 0 || BId == Builtin::BImemcmp) { 2559 if (BId == Builtin::BImemcpy) 2560 OperationType = 1; 2561 else if(BId == Builtin::BImemmove) 2562 OperationType = 2; 2563 else if (BId == Builtin::BImemcmp) 2564 OperationType = 3; 2565 } 2566 2567 DiagRuntimeBehavior( 2568 Dest->getExprLoc(), Dest, 2569 PDiag(diag::warn_dyn_class_memaccess) 2570 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx) 2571 << FnName << PointeeTy 2572 << OperationType 2573 << Call->getCallee()->getSourceRange()); 2574 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 2575 BId != Builtin::BImemset) 2576 DiagRuntimeBehavior( 2577 Dest->getExprLoc(), Dest, 2578 PDiag(diag::warn_arc_object_memaccess) 2579 << ArgIdx << FnName << PointeeTy 2580 << Call->getCallee()->getSourceRange()); 2581 else 2582 continue; 2583 2584 DiagRuntimeBehavior( 2585 Dest->getExprLoc(), Dest, 2586 PDiag(diag::note_bad_memaccess_silence) 2587 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 2588 break; 2589 } 2590 } 2591} 2592 2593// A little helper routine: ignore addition and subtraction of integer literals. 2594// This intentionally does not ignore all integer constant expressions because 2595// we don't want to remove sizeof(). 2596static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 2597 Ex = Ex->IgnoreParenCasts(); 2598 2599 for (;;) { 2600 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 2601 if (!BO || !BO->isAdditiveOp()) 2602 break; 2603 2604 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 2605 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 2606 2607 if (isa<IntegerLiteral>(RHS)) 2608 Ex = LHS; 2609 else if (isa<IntegerLiteral>(LHS)) 2610 Ex = RHS; 2611 else 2612 break; 2613 } 2614 2615 return Ex; 2616} 2617 2618// Warn if the user has made the 'size' argument to strlcpy or strlcat 2619// be the size of the source, instead of the destination. 2620void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 2621 IdentifierInfo *FnName) { 2622 2623 // Don't crash if the user has the wrong number of arguments 2624 if (Call->getNumArgs() != 3) 2625 return; 2626 2627 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 2628 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 2629 const Expr *CompareWithSrc = NULL; 2630 2631 // Look for 'strlcpy(dst, x, sizeof(x))' 2632 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 2633 CompareWithSrc = Ex; 2634 else { 2635 // Look for 'strlcpy(dst, x, strlen(x))' 2636 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 2637 if (SizeCall->isBuiltinCall() == Builtin::BIstrlen 2638 && SizeCall->getNumArgs() == 1) 2639 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 2640 } 2641 } 2642 2643 if (!CompareWithSrc) 2644 return; 2645 2646 // Determine if the argument to sizeof/strlen is equal to the source 2647 // argument. In principle there's all kinds of things you could do 2648 // here, for instance creating an == expression and evaluating it with 2649 // EvaluateAsBooleanCondition, but this uses a more direct technique: 2650 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 2651 if (!SrcArgDRE) 2652 return; 2653 2654 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 2655 if (!CompareWithSrcDRE || 2656 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 2657 return; 2658 2659 const Expr *OriginalSizeArg = Call->getArg(2); 2660 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size) 2661 << OriginalSizeArg->getSourceRange() << FnName; 2662 2663 // Output a FIXIT hint if the destination is an array (rather than a 2664 // pointer to an array). This could be enhanced to handle some 2665 // pointers if we know the actual size, like if DstArg is 'array+2' 2666 // we could say 'sizeof(array)-2'. 2667 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 2668 QualType DstArgTy = DstArg->getType(); 2669 2670 // Only handle constant-sized or VLAs, but not flexible members. 2671 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(DstArgTy)) { 2672 // Only issue the FIXIT for arrays of size > 1. 2673 if (CAT->getSize().getSExtValue() <= 1) 2674 return; 2675 } else if (!DstArgTy->isVariableArrayType()) { 2676 return; 2677 } 2678 2679 llvm::SmallString<128> sizeString; 2680 llvm::raw_svector_ostream OS(sizeString); 2681 OS << "sizeof("; 2682 DstArg->printPretty(OS, Context, 0, getPrintingPolicy()); 2683 OS << ")"; 2684 2685 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size) 2686 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 2687 OS.str()); 2688} 2689 2690//===--- CHECK: Return Address of Stack Variable --------------------------===// 2691 2692static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars); 2693static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars); 2694 2695/// CheckReturnStackAddr - Check if a return statement returns the address 2696/// of a stack variable. 2697void 2698Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType, 2699 SourceLocation ReturnLoc) { 2700 2701 Expr *stackE = 0; 2702 SmallVector<DeclRefExpr *, 8> refVars; 2703 2704 // Perform checking for returned stack addresses, local blocks, 2705 // label addresses or references to temporaries. 2706 if (lhsType->isPointerType() || 2707 (!getLangOptions().ObjCAutoRefCount && lhsType->isBlockPointerType())) { 2708 stackE = EvalAddr(RetValExp, refVars); 2709 } else if (lhsType->isReferenceType()) { 2710 stackE = EvalVal(RetValExp, refVars); 2711 } 2712 2713 if (stackE == 0) 2714 return; // Nothing suspicious was found. 2715 2716 SourceLocation diagLoc; 2717 SourceRange diagRange; 2718 if (refVars.empty()) { 2719 diagLoc = stackE->getLocStart(); 2720 diagRange = stackE->getSourceRange(); 2721 } else { 2722 // We followed through a reference variable. 'stackE' contains the 2723 // problematic expression but we will warn at the return statement pointing 2724 // at the reference variable. We will later display the "trail" of 2725 // reference variables using notes. 2726 diagLoc = refVars[0]->getLocStart(); 2727 diagRange = refVars[0]->getSourceRange(); 2728 } 2729 2730 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var. 2731 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref 2732 : diag::warn_ret_stack_addr) 2733 << DR->getDecl()->getDeclName() << diagRange; 2734 } else if (isa<BlockExpr>(stackE)) { // local block. 2735 Diag(diagLoc, diag::err_ret_local_block) << diagRange; 2736 } else if (isa<AddrLabelExpr>(stackE)) { // address of label. 2737 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange; 2738 } else { // local temporary. 2739 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref 2740 : diag::warn_ret_local_temp_addr) 2741 << diagRange; 2742 } 2743 2744 // Display the "trail" of reference variables that we followed until we 2745 // found the problematic expression using notes. 2746 for (unsigned i = 0, e = refVars.size(); i != e; ++i) { 2747 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl()); 2748 // If this var binds to another reference var, show the range of the next 2749 // var, otherwise the var binds to the problematic expression, in which case 2750 // show the range of the expression. 2751 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange() 2752 : stackE->getSourceRange(); 2753 Diag(VD->getLocation(), diag::note_ref_var_local_bind) 2754 << VD->getDeclName() << range; 2755 } 2756} 2757 2758/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that 2759/// check if the expression in a return statement evaluates to an address 2760/// to a location on the stack, a local block, an address of a label, or a 2761/// reference to local temporary. The recursion is used to traverse the 2762/// AST of the return expression, with recursion backtracking when we 2763/// encounter a subexpression that (1) clearly does not lead to one of the 2764/// above problematic expressions (2) is something we cannot determine leads to 2765/// a problematic expression based on such local checking. 2766/// 2767/// Both EvalAddr and EvalVal follow through reference variables to evaluate 2768/// the expression that they point to. Such variables are added to the 2769/// 'refVars' vector so that we know what the reference variable "trail" was. 2770/// 2771/// EvalAddr processes expressions that are pointers that are used as 2772/// references (and not L-values). EvalVal handles all other values. 2773/// At the base case of the recursion is a check for the above problematic 2774/// expressions. 2775/// 2776/// This implementation handles: 2777/// 2778/// * pointer-to-pointer casts 2779/// * implicit conversions from array references to pointers 2780/// * taking the address of fields 2781/// * arbitrary interplay between "&" and "*" operators 2782/// * pointer arithmetic from an address of a stack variable 2783/// * taking the address of an array element where the array is on the stack 2784static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars) { 2785 if (E->isTypeDependent()) 2786 return NULL; 2787 2788 // We should only be called for evaluating pointer expressions. 2789 assert((E->getType()->isAnyPointerType() || 2790 E->getType()->isBlockPointerType() || 2791 E->getType()->isObjCQualifiedIdType()) && 2792 "EvalAddr only works on pointers"); 2793 2794 E = E->IgnoreParens(); 2795 2796 // Our "symbolic interpreter" is just a dispatch off the currently 2797 // viewed AST node. We then recursively traverse the AST by calling 2798 // EvalAddr and EvalVal appropriately. 2799 switch (E->getStmtClass()) { 2800 case Stmt::DeclRefExprClass: { 2801 DeclRefExpr *DR = cast<DeclRefExpr>(E); 2802 2803 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) 2804 // If this is a reference variable, follow through to the expression that 2805 // it points to. 2806 if (V->hasLocalStorage() && 2807 V->getType()->isReferenceType() && V->hasInit()) { 2808 // Add the reference variable to the "trail". 2809 refVars.push_back(DR); 2810 return EvalAddr(V->getInit(), refVars); 2811 } 2812 2813 return NULL; 2814 } 2815 2816 case Stmt::UnaryOperatorClass: { 2817 // The only unary operator that make sense to handle here 2818 // is AddrOf. All others don't make sense as pointers. 2819 UnaryOperator *U = cast<UnaryOperator>(E); 2820 2821 if (U->getOpcode() == UO_AddrOf) 2822 return EvalVal(U->getSubExpr(), refVars); 2823 else 2824 return NULL; 2825 } 2826 2827 case Stmt::BinaryOperatorClass: { 2828 // Handle pointer arithmetic. All other binary operators are not valid 2829 // in this context. 2830 BinaryOperator *B = cast<BinaryOperator>(E); 2831 BinaryOperatorKind op = B->getOpcode(); 2832 2833 if (op != BO_Add && op != BO_Sub) 2834 return NULL; 2835 2836 Expr *Base = B->getLHS(); 2837 2838 // Determine which argument is the real pointer base. It could be 2839 // the RHS argument instead of the LHS. 2840 if (!Base->getType()->isPointerType()) Base = B->getRHS(); 2841 2842 assert (Base->getType()->isPointerType()); 2843 return EvalAddr(Base, refVars); 2844 } 2845 2846 // For conditional operators we need to see if either the LHS or RHS are 2847 // valid DeclRefExpr*s. If one of them is valid, we return it. 2848 case Stmt::ConditionalOperatorClass: { 2849 ConditionalOperator *C = cast<ConditionalOperator>(E); 2850 2851 // Handle the GNU extension for missing LHS. 2852 if (Expr *lhsExpr = C->getLHS()) { 2853 // In C++, we can have a throw-expression, which has 'void' type. 2854 if (!lhsExpr->getType()->isVoidType()) 2855 if (Expr* LHS = EvalAddr(lhsExpr, refVars)) 2856 return LHS; 2857 } 2858 2859 // In C++, we can have a throw-expression, which has 'void' type. 2860 if (C->getRHS()->getType()->isVoidType()) 2861 return NULL; 2862 2863 return EvalAddr(C->getRHS(), refVars); 2864 } 2865 2866 case Stmt::BlockExprClass: 2867 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures()) 2868 return E; // local block. 2869 return NULL; 2870 2871 case Stmt::AddrLabelExprClass: 2872 return E; // address of label. 2873 2874 case Stmt::ExprWithCleanupsClass: 2875 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars); 2876 2877 // For casts, we need to handle conversions from arrays to 2878 // pointer values, and pointer-to-pointer conversions. 2879 case Stmt::ImplicitCastExprClass: 2880 case Stmt::CStyleCastExprClass: 2881 case Stmt::CXXFunctionalCastExprClass: 2882 case Stmt::ObjCBridgedCastExprClass: { 2883 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr(); 2884 QualType T = SubExpr->getType(); 2885 2886 if (SubExpr->getType()->isPointerType() || 2887 SubExpr->getType()->isBlockPointerType() || 2888 SubExpr->getType()->isObjCQualifiedIdType()) 2889 return EvalAddr(SubExpr, refVars); 2890 else if (T->isArrayType()) 2891 return EvalVal(SubExpr, refVars); 2892 else 2893 return 0; 2894 } 2895 2896 // C++ casts. For dynamic casts, static casts, and const casts, we 2897 // are always converting from a pointer-to-pointer, so we just blow 2898 // through the cast. In the case the dynamic cast doesn't fail (and 2899 // return NULL), we take the conservative route and report cases 2900 // where we return the address of a stack variable. For Reinterpre 2901 // FIXME: The comment about is wrong; we're not always converting 2902 // from pointer to pointer. I'm guessing that this code should also 2903 // handle references to objects. 2904 case Stmt::CXXStaticCastExprClass: 2905 case Stmt::CXXDynamicCastExprClass: 2906 case Stmt::CXXConstCastExprClass: 2907 case Stmt::CXXReinterpretCastExprClass: { 2908 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr(); 2909 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType()) 2910 return EvalAddr(S, refVars); 2911 else 2912 return NULL; 2913 } 2914 2915 case Stmt::MaterializeTemporaryExprClass: 2916 if (Expr *Result = EvalAddr( 2917 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 2918 refVars)) 2919 return Result; 2920 2921 return E; 2922 2923 // Everything else: we simply don't reason about them. 2924 default: 2925 return NULL; 2926 } 2927} 2928 2929 2930/// EvalVal - This function is complements EvalAddr in the mutual recursion. 2931/// See the comments for EvalAddr for more details. 2932static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars) { 2933do { 2934 // We should only be called for evaluating non-pointer expressions, or 2935 // expressions with a pointer type that are not used as references but instead 2936 // are l-values (e.g., DeclRefExpr with a pointer type). 2937 2938 // Our "symbolic interpreter" is just a dispatch off the currently 2939 // viewed AST node. We then recursively traverse the AST by calling 2940 // EvalAddr and EvalVal appropriately. 2941 2942 E = E->IgnoreParens(); 2943 switch (E->getStmtClass()) { 2944 case Stmt::ImplicitCastExprClass: { 2945 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E); 2946 if (IE->getValueKind() == VK_LValue) { 2947 E = IE->getSubExpr(); 2948 continue; 2949 } 2950 return NULL; 2951 } 2952 2953 case Stmt::ExprWithCleanupsClass: 2954 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars); 2955 2956 case Stmt::DeclRefExprClass: { 2957 // When we hit a DeclRefExpr we are looking at code that refers to a 2958 // variable's name. If it's not a reference variable we check if it has 2959 // local storage within the function, and if so, return the expression. 2960 DeclRefExpr *DR = cast<DeclRefExpr>(E); 2961 2962 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) 2963 if (V->hasLocalStorage()) { 2964 if (!V->getType()->isReferenceType()) 2965 return DR; 2966 2967 // Reference variable, follow through to the expression that 2968 // it points to. 2969 if (V->hasInit()) { 2970 // Add the reference variable to the "trail". 2971 refVars.push_back(DR); 2972 return EvalVal(V->getInit(), refVars); 2973 } 2974 } 2975 2976 return NULL; 2977 } 2978 2979 case Stmt::UnaryOperatorClass: { 2980 // The only unary operator that make sense to handle here 2981 // is Deref. All others don't resolve to a "name." This includes 2982 // handling all sorts of rvalues passed to a unary operator. 2983 UnaryOperator *U = cast<UnaryOperator>(E); 2984 2985 if (U->getOpcode() == UO_Deref) 2986 return EvalAddr(U->getSubExpr(), refVars); 2987 2988 return NULL; 2989 } 2990 2991 case Stmt::ArraySubscriptExprClass: { 2992 // Array subscripts are potential references to data on the stack. We 2993 // retrieve the DeclRefExpr* for the array variable if it indeed 2994 // has local storage. 2995 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars); 2996 } 2997 2998 case Stmt::ConditionalOperatorClass: { 2999 // For conditional operators we need to see if either the LHS or RHS are 3000 // non-NULL Expr's. If one is non-NULL, we return it. 3001 ConditionalOperator *C = cast<ConditionalOperator>(E); 3002 3003 // Handle the GNU extension for missing LHS. 3004 if (Expr *lhsExpr = C->getLHS()) 3005 if (Expr *LHS = EvalVal(lhsExpr, refVars)) 3006 return LHS; 3007 3008 return EvalVal(C->getRHS(), refVars); 3009 } 3010 3011 // Accesses to members are potential references to data on the stack. 3012 case Stmt::MemberExprClass: { 3013 MemberExpr *M = cast<MemberExpr>(E); 3014 3015 // Check for indirect access. We only want direct field accesses. 3016 if (M->isArrow()) 3017 return NULL; 3018 3019 // Check whether the member type is itself a reference, in which case 3020 // we're not going to refer to the member, but to what the member refers to. 3021 if (M->getMemberDecl()->getType()->isReferenceType()) 3022 return NULL; 3023 3024 return EvalVal(M->getBase(), refVars); 3025 } 3026 3027 case Stmt::MaterializeTemporaryExprClass: 3028 if (Expr *Result = EvalVal( 3029 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 3030 refVars)) 3031 return Result; 3032 3033 return E; 3034 3035 default: 3036 // Check that we don't return or take the address of a reference to a 3037 // temporary. This is only useful in C++. 3038 if (!E->isTypeDependent() && E->isRValue()) 3039 return E; 3040 3041 // Everything else: we simply don't reason about them. 3042 return NULL; 3043 } 3044} while (true); 3045} 3046 3047//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 3048 3049/// Check for comparisons of floating point operands using != and ==. 3050/// Issue a warning if these are no self-comparisons, as they are not likely 3051/// to do what the programmer intended. 3052void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 3053 bool EmitWarning = true; 3054 3055 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 3056 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 3057 3058 // Special case: check for x == x (which is OK). 3059 // Do not emit warnings for such cases. 3060 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 3061 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 3062 if (DRL->getDecl() == DRR->getDecl()) 3063 EmitWarning = false; 3064 3065 3066 // Special case: check for comparisons against literals that can be exactly 3067 // represented by APFloat. In such cases, do not emit a warning. This 3068 // is a heuristic: often comparison against such literals are used to 3069 // detect if a value in a variable has not changed. This clearly can 3070 // lead to false negatives. 3071 if (EmitWarning) { 3072 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 3073 if (FLL->isExact()) 3074 EmitWarning = false; 3075 } else 3076 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){ 3077 if (FLR->isExact()) 3078 EmitWarning = false; 3079 } 3080 } 3081 3082 // Check for comparisons with builtin types. 3083 if (EmitWarning) 3084 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 3085 if (CL->isBuiltinCall()) 3086 EmitWarning = false; 3087 3088 if (EmitWarning) 3089 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 3090 if (CR->isBuiltinCall()) 3091 EmitWarning = false; 3092 3093 // Emit the diagnostic. 3094 if (EmitWarning) 3095 Diag(Loc, diag::warn_floatingpoint_eq) 3096 << LHS->getSourceRange() << RHS->getSourceRange(); 3097} 3098 3099//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 3100//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 3101 3102namespace { 3103 3104/// Structure recording the 'active' range of an integer-valued 3105/// expression. 3106struct IntRange { 3107 /// The number of bits active in the int. 3108 unsigned Width; 3109 3110 /// True if the int is known not to have negative values. 3111 bool NonNegative; 3112 3113 IntRange(unsigned Width, bool NonNegative) 3114 : Width(Width), NonNegative(NonNegative) 3115 {} 3116 3117 /// Returns the range of the bool type. 3118 static IntRange forBoolType() { 3119 return IntRange(1, true); 3120 } 3121 3122 /// Returns the range of an opaque value of the given integral type. 3123 static IntRange forValueOfType(ASTContext &C, QualType T) { 3124 return forValueOfCanonicalType(C, 3125 T->getCanonicalTypeInternal().getTypePtr()); 3126 } 3127 3128 /// Returns the range of an opaque value of a canonical integral type. 3129 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 3130 assert(T->isCanonicalUnqualified()); 3131 3132 if (const VectorType *VT = dyn_cast<VectorType>(T)) 3133 T = VT->getElementType().getTypePtr(); 3134 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 3135 T = CT->getElementType().getTypePtr(); 3136 3137 // For enum types, use the known bit width of the enumerators. 3138 if (const EnumType *ET = dyn_cast<EnumType>(T)) { 3139 EnumDecl *Enum = ET->getDecl(); 3140 if (!Enum->isCompleteDefinition()) 3141 return IntRange(C.getIntWidth(QualType(T, 0)), false); 3142 3143 unsigned NumPositive = Enum->getNumPositiveBits(); 3144 unsigned NumNegative = Enum->getNumNegativeBits(); 3145 3146 return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0); 3147 } 3148 3149 const BuiltinType *BT = cast<BuiltinType>(T); 3150 assert(BT->isInteger()); 3151 3152 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 3153 } 3154 3155 /// Returns the "target" range of a canonical integral type, i.e. 3156 /// the range of values expressible in the type. 3157 /// 3158 /// This matches forValueOfCanonicalType except that enums have the 3159 /// full range of their type, not the range of their enumerators. 3160 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 3161 assert(T->isCanonicalUnqualified()); 3162 3163 if (const VectorType *VT = dyn_cast<VectorType>(T)) 3164 T = VT->getElementType().getTypePtr(); 3165 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 3166 T = CT->getElementType().getTypePtr(); 3167 if (const EnumType *ET = dyn_cast<EnumType>(T)) 3168 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 3169 3170 const BuiltinType *BT = cast<BuiltinType>(T); 3171 assert(BT->isInteger()); 3172 3173 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 3174 } 3175 3176 /// Returns the supremum of two ranges: i.e. their conservative merge. 3177 static IntRange join(IntRange L, IntRange R) { 3178 return IntRange(std::max(L.Width, R.Width), 3179 L.NonNegative && R.NonNegative); 3180 } 3181 3182 /// Returns the infinum of two ranges: i.e. their aggressive merge. 3183 static IntRange meet(IntRange L, IntRange R) { 3184 return IntRange(std::min(L.Width, R.Width), 3185 L.NonNegative || R.NonNegative); 3186 } 3187}; 3188 3189IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) { 3190 if (value.isSigned() && value.isNegative()) 3191 return IntRange(value.getMinSignedBits(), false); 3192 3193 if (value.getBitWidth() > MaxWidth) 3194 value = value.trunc(MaxWidth); 3195 3196 // isNonNegative() just checks the sign bit without considering 3197 // signedness. 3198 return IntRange(value.getActiveBits(), true); 3199} 3200 3201IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 3202 unsigned MaxWidth) { 3203 if (result.isInt()) 3204 return GetValueRange(C, result.getInt(), MaxWidth); 3205 3206 if (result.isVector()) { 3207 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 3208 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 3209 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 3210 R = IntRange::join(R, El); 3211 } 3212 return R; 3213 } 3214 3215 if (result.isComplexInt()) { 3216 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 3217 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 3218 return IntRange::join(R, I); 3219 } 3220 3221 // This can happen with lossless casts to intptr_t of "based" lvalues. 3222 // Assume it might use arbitrary bits. 3223 // FIXME: The only reason we need to pass the type in here is to get 3224 // the sign right on this one case. It would be nice if APValue 3225 // preserved this. 3226 assert(result.isLValue() || result.isAddrLabelDiff()); 3227 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 3228} 3229 3230/// Pseudo-evaluate the given integer expression, estimating the 3231/// range of values it might take. 3232/// 3233/// \param MaxWidth - the width to which the value will be truncated 3234IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) { 3235 E = E->IgnoreParens(); 3236 3237 // Try a full evaluation first. 3238 Expr::EvalResult result; 3239 if (E->EvaluateAsRValue(result, C)) 3240 return GetValueRange(C, result.Val, E->getType(), MaxWidth); 3241 3242 // I think we only want to look through implicit casts here; if the 3243 // user has an explicit widening cast, we should treat the value as 3244 // being of the new, wider type. 3245 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) { 3246 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 3247 return GetExprRange(C, CE->getSubExpr(), MaxWidth); 3248 3249 IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType()); 3250 3251 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast); 3252 3253 // Assume that non-integer casts can span the full range of the type. 3254 if (!isIntegerCast) 3255 return OutputTypeRange; 3256 3257 IntRange SubRange 3258 = GetExprRange(C, CE->getSubExpr(), 3259 std::min(MaxWidth, OutputTypeRange.Width)); 3260 3261 // Bail out if the subexpr's range is as wide as the cast type. 3262 if (SubRange.Width >= OutputTypeRange.Width) 3263 return OutputTypeRange; 3264 3265 // Otherwise, we take the smaller width, and we're non-negative if 3266 // either the output type or the subexpr is. 3267 return IntRange(SubRange.Width, 3268 SubRange.NonNegative || OutputTypeRange.NonNegative); 3269 } 3270 3271 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 3272 // If we can fold the condition, just take that operand. 3273 bool CondResult; 3274 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 3275 return GetExprRange(C, CondResult ? CO->getTrueExpr() 3276 : CO->getFalseExpr(), 3277 MaxWidth); 3278 3279 // Otherwise, conservatively merge. 3280 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth); 3281 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth); 3282 return IntRange::join(L, R); 3283 } 3284 3285 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 3286 switch (BO->getOpcode()) { 3287 3288 // Boolean-valued operations are single-bit and positive. 3289 case BO_LAnd: 3290 case BO_LOr: 3291 case BO_LT: 3292 case BO_GT: 3293 case BO_LE: 3294 case BO_GE: 3295 case BO_EQ: 3296 case BO_NE: 3297 return IntRange::forBoolType(); 3298 3299 // The type of the assignments is the type of the LHS, so the RHS 3300 // is not necessarily the same type. 3301 case BO_MulAssign: 3302 case BO_DivAssign: 3303 case BO_RemAssign: 3304 case BO_AddAssign: 3305 case BO_SubAssign: 3306 case BO_XorAssign: 3307 case BO_OrAssign: 3308 // TODO: bitfields? 3309 return IntRange::forValueOfType(C, E->getType()); 3310 3311 // Simple assignments just pass through the RHS, which will have 3312 // been coerced to the LHS type. 3313 case BO_Assign: 3314 // TODO: bitfields? 3315 return GetExprRange(C, BO->getRHS(), MaxWidth); 3316 3317 // Operations with opaque sources are black-listed. 3318 case BO_PtrMemD: 3319 case BO_PtrMemI: 3320 return IntRange::forValueOfType(C, E->getType()); 3321 3322 // Bitwise-and uses the *infinum* of the two source ranges. 3323 case BO_And: 3324 case BO_AndAssign: 3325 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth), 3326 GetExprRange(C, BO->getRHS(), MaxWidth)); 3327 3328 // Left shift gets black-listed based on a judgement call. 3329 case BO_Shl: 3330 // ...except that we want to treat '1 << (blah)' as logically 3331 // positive. It's an important idiom. 3332 if (IntegerLiteral *I 3333 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 3334 if (I->getValue() == 1) { 3335 IntRange R = IntRange::forValueOfType(C, E->getType()); 3336 return IntRange(R.Width, /*NonNegative*/ true); 3337 } 3338 } 3339 // fallthrough 3340 3341 case BO_ShlAssign: 3342 return IntRange::forValueOfType(C, E->getType()); 3343 3344 // Right shift by a constant can narrow its left argument. 3345 case BO_Shr: 3346 case BO_ShrAssign: { 3347 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 3348 3349 // If the shift amount is a positive constant, drop the width by 3350 // that much. 3351 llvm::APSInt shift; 3352 if (BO->getRHS()->isIntegerConstantExpr(shift, C) && 3353 shift.isNonNegative()) { 3354 unsigned zext = shift.getZExtValue(); 3355 if (zext >= L.Width) 3356 L.Width = (L.NonNegative ? 0 : 1); 3357 else 3358 L.Width -= zext; 3359 } 3360 3361 return L; 3362 } 3363 3364 // Comma acts as its right operand. 3365 case BO_Comma: 3366 return GetExprRange(C, BO->getRHS(), MaxWidth); 3367 3368 // Black-list pointer subtractions. 3369 case BO_Sub: 3370 if (BO->getLHS()->getType()->isPointerType()) 3371 return IntRange::forValueOfType(C, E->getType()); 3372 break; 3373 3374 // The width of a division result is mostly determined by the size 3375 // of the LHS. 3376 case BO_Div: { 3377 // Don't 'pre-truncate' the operands. 3378 unsigned opWidth = C.getIntWidth(E->getType()); 3379 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 3380 3381 // If the divisor is constant, use that. 3382 llvm::APSInt divisor; 3383 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) { 3384 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor)) 3385 if (log2 >= L.Width) 3386 L.Width = (L.NonNegative ? 0 : 1); 3387 else 3388 L.Width = std::min(L.Width - log2, MaxWidth); 3389 return L; 3390 } 3391 3392 // Otherwise, just use the LHS's width. 3393 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 3394 return IntRange(L.Width, L.NonNegative && R.NonNegative); 3395 } 3396 3397 // The result of a remainder can't be larger than the result of 3398 // either side. 3399 case BO_Rem: { 3400 // Don't 'pre-truncate' the operands. 3401 unsigned opWidth = C.getIntWidth(E->getType()); 3402 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 3403 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 3404 3405 IntRange meet = IntRange::meet(L, R); 3406 meet.Width = std::min(meet.Width, MaxWidth); 3407 return meet; 3408 } 3409 3410 // The default behavior is okay for these. 3411 case BO_Mul: 3412 case BO_Add: 3413 case BO_Xor: 3414 case BO_Or: 3415 break; 3416 } 3417 3418 // The default case is to treat the operation as if it were closed 3419 // on the narrowest type that encompasses both operands. 3420 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 3421 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth); 3422 return IntRange::join(L, R); 3423 } 3424 3425 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 3426 switch (UO->getOpcode()) { 3427 // Boolean-valued operations are white-listed. 3428 case UO_LNot: 3429 return IntRange::forBoolType(); 3430 3431 // Operations with opaque sources are black-listed. 3432 case UO_Deref: 3433 case UO_AddrOf: // should be impossible 3434 return IntRange::forValueOfType(C, E->getType()); 3435 3436 default: 3437 return GetExprRange(C, UO->getSubExpr(), MaxWidth); 3438 } 3439 } 3440 3441 if (dyn_cast<OffsetOfExpr>(E)) { 3442 IntRange::forValueOfType(C, E->getType()); 3443 } 3444 3445 if (FieldDecl *BitField = E->getBitField()) 3446 return IntRange(BitField->getBitWidthValue(C), 3447 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 3448 3449 return IntRange::forValueOfType(C, E->getType()); 3450} 3451 3452IntRange GetExprRange(ASTContext &C, Expr *E) { 3453 return GetExprRange(C, E, C.getIntWidth(E->getType())); 3454} 3455 3456/// Checks whether the given value, which currently has the given 3457/// source semantics, has the same value when coerced through the 3458/// target semantics. 3459bool IsSameFloatAfterCast(const llvm::APFloat &value, 3460 const llvm::fltSemantics &Src, 3461 const llvm::fltSemantics &Tgt) { 3462 llvm::APFloat truncated = value; 3463 3464 bool ignored; 3465 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 3466 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 3467 3468 return truncated.bitwiseIsEqual(value); 3469} 3470 3471/// Checks whether the given value, which currently has the given 3472/// source semantics, has the same value when coerced through the 3473/// target semantics. 3474/// 3475/// The value might be a vector of floats (or a complex number). 3476bool IsSameFloatAfterCast(const APValue &value, 3477 const llvm::fltSemantics &Src, 3478 const llvm::fltSemantics &Tgt) { 3479 if (value.isFloat()) 3480 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 3481 3482 if (value.isVector()) { 3483 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 3484 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 3485 return false; 3486 return true; 3487 } 3488 3489 assert(value.isComplexFloat()); 3490 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 3491 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 3492} 3493 3494void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC); 3495 3496static bool IsZero(Sema &S, Expr *E) { 3497 // Suppress cases where we are comparing against an enum constant. 3498 if (const DeclRefExpr *DR = 3499 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 3500 if (isa<EnumConstantDecl>(DR->getDecl())) 3501 return false; 3502 3503 // Suppress cases where the '0' value is expanded from a macro. 3504 if (E->getLocStart().isMacroID()) 3505 return false; 3506 3507 llvm::APSInt Value; 3508 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0; 3509} 3510 3511static bool HasEnumType(Expr *E) { 3512 // Strip off implicit integral promotions. 3513 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 3514 if (ICE->getCastKind() != CK_IntegralCast && 3515 ICE->getCastKind() != CK_NoOp) 3516 break; 3517 E = ICE->getSubExpr(); 3518 } 3519 3520 return E->getType()->isEnumeralType(); 3521} 3522 3523void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) { 3524 BinaryOperatorKind op = E->getOpcode(); 3525 if (E->isValueDependent()) 3526 return; 3527 3528 if (op == BO_LT && IsZero(S, E->getRHS())) { 3529 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison) 3530 << "< 0" << "false" << HasEnumType(E->getLHS()) 3531 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 3532 } else if (op == BO_GE && IsZero(S, E->getRHS())) { 3533 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison) 3534 << ">= 0" << "true" << HasEnumType(E->getLHS()) 3535 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 3536 } else if (op == BO_GT && IsZero(S, E->getLHS())) { 3537 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison) 3538 << "0 >" << "false" << HasEnumType(E->getRHS()) 3539 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 3540 } else if (op == BO_LE && IsZero(S, E->getLHS())) { 3541 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison) 3542 << "0 <=" << "true" << HasEnumType(E->getRHS()) 3543 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 3544 } 3545} 3546 3547/// Analyze the operands of the given comparison. Implements the 3548/// fallback case from AnalyzeComparison. 3549void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 3550 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 3551 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 3552} 3553 3554/// \brief Implements -Wsign-compare. 3555/// 3556/// \param E the binary operator to check for warnings 3557void AnalyzeComparison(Sema &S, BinaryOperator *E) { 3558 // The type the comparison is being performed in. 3559 QualType T = E->getLHS()->getType(); 3560 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()) 3561 && "comparison with mismatched types"); 3562 3563 // We don't do anything special if this isn't an unsigned integral 3564 // comparison: we're only interested in integral comparisons, and 3565 // signed comparisons only happen in cases we don't care to warn about. 3566 // 3567 // We also don't care about value-dependent expressions or expressions 3568 // whose result is a constant. 3569 if (!T->hasUnsignedIntegerRepresentation() 3570 || E->isValueDependent() || E->isIntegerConstantExpr(S.Context)) 3571 return AnalyzeImpConvsInComparison(S, E); 3572 3573 Expr *LHS = E->getLHS()->IgnoreParenImpCasts(); 3574 Expr *RHS = E->getRHS()->IgnoreParenImpCasts(); 3575 3576 // Check to see if one of the (unmodified) operands is of different 3577 // signedness. 3578 Expr *signedOperand, *unsignedOperand; 3579 if (LHS->getType()->hasSignedIntegerRepresentation()) { 3580 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 3581 "unsigned comparison between two signed integer expressions?"); 3582 signedOperand = LHS; 3583 unsignedOperand = RHS; 3584 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 3585 signedOperand = RHS; 3586 unsignedOperand = LHS; 3587 } else { 3588 CheckTrivialUnsignedComparison(S, E); 3589 return AnalyzeImpConvsInComparison(S, E); 3590 } 3591 3592 // Otherwise, calculate the effective range of the signed operand. 3593 IntRange signedRange = GetExprRange(S.Context, signedOperand); 3594 3595 // Go ahead and analyze implicit conversions in the operands. Note 3596 // that we skip the implicit conversions on both sides. 3597 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 3598 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 3599 3600 // If the signed range is non-negative, -Wsign-compare won't fire, 3601 // but we should still check for comparisons which are always true 3602 // or false. 3603 if (signedRange.NonNegative) 3604 return CheckTrivialUnsignedComparison(S, E); 3605 3606 // For (in)equality comparisons, if the unsigned operand is a 3607 // constant which cannot collide with a overflowed signed operand, 3608 // then reinterpreting the signed operand as unsigned will not 3609 // change the result of the comparison. 3610 if (E->isEqualityOp()) { 3611 unsigned comparisonWidth = S.Context.getIntWidth(T); 3612 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand); 3613 3614 // We should never be unable to prove that the unsigned operand is 3615 // non-negative. 3616 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 3617 3618 if (unsignedRange.Width < comparisonWidth) 3619 return; 3620 } 3621 3622 S.Diag(E->getOperatorLoc(), diag::warn_mixed_sign_comparison) 3623 << LHS->getType() << RHS->getType() 3624 << LHS->getSourceRange() << RHS->getSourceRange(); 3625} 3626 3627/// Analyzes an attempt to assign the given value to a bitfield. 3628/// 3629/// Returns true if there was something fishy about the attempt. 3630bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 3631 SourceLocation InitLoc) { 3632 assert(Bitfield->isBitField()); 3633 if (Bitfield->isInvalidDecl()) 3634 return false; 3635 3636 // White-list bool bitfields. 3637 if (Bitfield->getType()->isBooleanType()) 3638 return false; 3639 3640 // Ignore value- or type-dependent expressions. 3641 if (Bitfield->getBitWidth()->isValueDependent() || 3642 Bitfield->getBitWidth()->isTypeDependent() || 3643 Init->isValueDependent() || 3644 Init->isTypeDependent()) 3645 return false; 3646 3647 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 3648 3649 llvm::APSInt Value; 3650 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) 3651 return false; 3652 3653 unsigned OriginalWidth = Value.getBitWidth(); 3654 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 3655 3656 if (OriginalWidth <= FieldWidth) 3657 return false; 3658 3659 // Compute the value which the bitfield will contain. 3660 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 3661 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType()); 3662 3663 // Check whether the stored value is equal to the original value. 3664 TruncatedValue = TruncatedValue.extend(OriginalWidth); 3665 if (Value == TruncatedValue) 3666 return false; 3667 3668 // Special-case bitfields of width 1: booleans are naturally 0/1, and 3669 // therefore don't strictly fit into a bitfield of width 1. 3670 if (FieldWidth == 1 && Value.getBoolValue() == TruncatedValue.getBoolValue()) 3671 return false; 3672 3673 std::string PrettyValue = Value.toString(10); 3674 std::string PrettyTrunc = TruncatedValue.toString(10); 3675 3676 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 3677 << PrettyValue << PrettyTrunc << OriginalInit->getType() 3678 << Init->getSourceRange(); 3679 3680 return true; 3681} 3682 3683/// Analyze the given simple or compound assignment for warning-worthy 3684/// operations. 3685void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 3686 // Just recurse on the LHS. 3687 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 3688 3689 // We want to recurse on the RHS as normal unless we're assigning to 3690 // a bitfield. 3691 if (FieldDecl *Bitfield = E->getLHS()->getBitField()) { 3692 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 3693 E->getOperatorLoc())) { 3694 // Recurse, ignoring any implicit conversions on the RHS. 3695 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 3696 E->getOperatorLoc()); 3697 } 3698 } 3699 3700 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 3701} 3702 3703/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 3704void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 3705 SourceLocation CContext, unsigned diag) { 3706 S.Diag(E->getExprLoc(), diag) 3707 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 3708} 3709 3710/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 3711void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext, 3712 unsigned diag) { 3713 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag); 3714} 3715 3716/// Diagnose an implicit cast from a literal expression. Does not warn when the 3717/// cast wouldn't lose information. 3718void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T, 3719 SourceLocation CContext) { 3720 // Try to convert the literal exactly to an integer. If we can, don't warn. 3721 bool isExact = false; 3722 const llvm::APFloat &Value = FL->getValue(); 3723 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 3724 T->hasUnsignedIntegerRepresentation()); 3725 if (Value.convertToInteger(IntegerValue, 3726 llvm::APFloat::rmTowardZero, &isExact) 3727 == llvm::APFloat::opOK && isExact) 3728 return; 3729 3730 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer) 3731 << FL->getType() << T << FL->getSourceRange() << SourceRange(CContext); 3732} 3733 3734std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) { 3735 if (!Range.Width) return "0"; 3736 3737 llvm::APSInt ValueInRange = Value; 3738 ValueInRange.setIsSigned(!Range.NonNegative); 3739 ValueInRange = ValueInRange.trunc(Range.Width); 3740 return ValueInRange.toString(10); 3741} 3742 3743void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 3744 SourceLocation CC, bool *ICContext = 0) { 3745 if (E->isTypeDependent() || E->isValueDependent()) return; 3746 3747 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 3748 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 3749 if (Source == Target) return; 3750 if (Target->isDependentType()) return; 3751 3752 // If the conversion context location is invalid don't complain. We also 3753 // don't want to emit a warning if the issue occurs from the expansion of 3754 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 3755 // delay this check as long as possible. Once we detect we are in that 3756 // scenario, we just return. 3757 if (CC.isInvalid()) 3758 return; 3759 3760 // Diagnose implicit casts to bool. 3761 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 3762 if (isa<StringLiteral>(E)) 3763 // Warn on string literal to bool. Checks for string literals in logical 3764 // expressions, for instances, assert(0 && "error here"), is prevented 3765 // by a check in AnalyzeImplicitConversions(). 3766 return DiagnoseImpCast(S, E, T, CC, 3767 diag::warn_impcast_string_literal_to_bool); 3768 if (Source->isFunctionType()) { 3769 // Warn on function to bool. Checks free functions and static member 3770 // functions. Weakly imported functions are excluded from the check, 3771 // since it's common to test their value to check whether the linker 3772 // found a definition for them. 3773 ValueDecl *D = 0; 3774 if (DeclRefExpr* R = dyn_cast<DeclRefExpr>(E)) { 3775 D = R->getDecl(); 3776 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 3777 D = M->getMemberDecl(); 3778 } 3779 3780 if (D && !D->isWeak()) { 3781 if (FunctionDecl* F = dyn_cast<FunctionDecl>(D)) { 3782 S.Diag(E->getExprLoc(), diag::warn_impcast_function_to_bool) 3783 << F << E->getSourceRange() << SourceRange(CC); 3784 S.Diag(E->getExprLoc(), diag::note_function_to_bool_silence) 3785 << FixItHint::CreateInsertion(E->getExprLoc(), "&"); 3786 QualType ReturnType; 3787 UnresolvedSet<4> NonTemplateOverloads; 3788 S.isExprCallable(*E, ReturnType, NonTemplateOverloads); 3789 if (!ReturnType.isNull() 3790 && ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 3791 S.Diag(E->getExprLoc(), diag::note_function_to_bool_call) 3792 << FixItHint::CreateInsertion( 3793 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()"); 3794 return; 3795 } 3796 } 3797 } 3798 return; // Other casts to bool are not checked. 3799 } 3800 3801 // Strip vector types. 3802 if (isa<VectorType>(Source)) { 3803 if (!isa<VectorType>(Target)) { 3804 if (S.SourceMgr.isInSystemMacro(CC)) 3805 return; 3806 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 3807 } 3808 3809 // If the vector cast is cast between two vectors of the same size, it is 3810 // a bitcast, not a conversion. 3811 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 3812 return; 3813 3814 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 3815 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 3816 } 3817 3818 // Strip complex types. 3819 if (isa<ComplexType>(Source)) { 3820 if (!isa<ComplexType>(Target)) { 3821 if (S.SourceMgr.isInSystemMacro(CC)) 3822 return; 3823 3824 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar); 3825 } 3826 3827 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 3828 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 3829 } 3830 3831 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 3832 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 3833 3834 // If the source is floating point... 3835 if (SourceBT && SourceBT->isFloatingPoint()) { 3836 // ...and the target is floating point... 3837 if (TargetBT && TargetBT->isFloatingPoint()) { 3838 // ...then warn if we're dropping FP rank. 3839 3840 // Builtin FP kinds are ordered by increasing FP rank. 3841 if (SourceBT->getKind() > TargetBT->getKind()) { 3842 // Don't warn about float constants that are precisely 3843 // representable in the target type. 3844 Expr::EvalResult result; 3845 if (E->EvaluateAsRValue(result, S.Context)) { 3846 // Value might be a float, a float vector, or a float complex. 3847 if (IsSameFloatAfterCast(result.Val, 3848 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 3849 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 3850 return; 3851 } 3852 3853 if (S.SourceMgr.isInSystemMacro(CC)) 3854 return; 3855 3856 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 3857 } 3858 return; 3859 } 3860 3861 // If the target is integral, always warn. 3862 if ((TargetBT && TargetBT->isInteger())) { 3863 if (S.SourceMgr.isInSystemMacro(CC)) 3864 return; 3865 3866 Expr *InnerE = E->IgnoreParenImpCasts(); 3867 // We also want to warn on, e.g., "int i = -1.234" 3868 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 3869 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 3870 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 3871 3872 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) { 3873 DiagnoseFloatingLiteralImpCast(S, FL, T, CC); 3874 } else { 3875 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer); 3876 } 3877 } 3878 3879 return; 3880 } 3881 3882 if (!Source->isIntegerType() || !Target->isIntegerType()) 3883 return; 3884 3885 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) 3886 == Expr::NPCK_GNUNull) && Target->isIntegerType()) { 3887 S.Diag(E->getExprLoc(), diag::warn_impcast_null_pointer_to_integer) 3888 << E->getSourceRange() << clang::SourceRange(CC); 3889 return; 3890 } 3891 3892 IntRange SourceRange = GetExprRange(S.Context, E); 3893 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 3894 3895 if (SourceRange.Width > TargetRange.Width) { 3896 // If the source is a constant, use a default-on diagnostic. 3897 // TODO: this should happen for bitfield stores, too. 3898 llvm::APSInt Value(32); 3899 if (E->isIntegerConstantExpr(Value, S.Context)) { 3900 if (S.SourceMgr.isInSystemMacro(CC)) 3901 return; 3902 3903 std::string PrettySourceValue = Value.toString(10); 3904 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 3905 3906 S.DiagRuntimeBehavior(E->getExprLoc(), E, 3907 S.PDiag(diag::warn_impcast_integer_precision_constant) 3908 << PrettySourceValue << PrettyTargetValue 3909 << E->getType() << T << E->getSourceRange() 3910 << clang::SourceRange(CC)); 3911 return; 3912 } 3913 3914 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 3915 if (S.SourceMgr.isInSystemMacro(CC)) 3916 return; 3917 3918 if (SourceRange.Width == 64 && TargetRange.Width == 32) 3919 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32); 3920 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 3921 } 3922 3923 if ((TargetRange.NonNegative && !SourceRange.NonNegative) || 3924 (!TargetRange.NonNegative && SourceRange.NonNegative && 3925 SourceRange.Width == TargetRange.Width)) { 3926 3927 if (S.SourceMgr.isInSystemMacro(CC)) 3928 return; 3929 3930 unsigned DiagID = diag::warn_impcast_integer_sign; 3931 3932 // Traditionally, gcc has warned about this under -Wsign-compare. 3933 // We also want to warn about it in -Wconversion. 3934 // So if -Wconversion is off, use a completely identical diagnostic 3935 // in the sign-compare group. 3936 // The conditional-checking code will 3937 if (ICContext) { 3938 DiagID = diag::warn_impcast_integer_sign_conditional; 3939 *ICContext = true; 3940 } 3941 3942 return DiagnoseImpCast(S, E, T, CC, DiagID); 3943 } 3944 3945 // Diagnose conversions between different enumeration types. 3946 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 3947 // type, to give us better diagnostics. 3948 QualType SourceType = E->getType(); 3949 if (!S.getLangOptions().CPlusPlus) { 3950 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 3951 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 3952 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 3953 SourceType = S.Context.getTypeDeclType(Enum); 3954 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 3955 } 3956 } 3957 3958 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 3959 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 3960 if ((SourceEnum->getDecl()->getIdentifier() || 3961 SourceEnum->getDecl()->getTypedefNameForAnonDecl()) && 3962 (TargetEnum->getDecl()->getIdentifier() || 3963 TargetEnum->getDecl()->getTypedefNameForAnonDecl()) && 3964 SourceEnum != TargetEnum) { 3965 if (S.SourceMgr.isInSystemMacro(CC)) 3966 return; 3967 3968 return DiagnoseImpCast(S, E, SourceType, T, CC, 3969 diag::warn_impcast_different_enum_types); 3970 } 3971 3972 return; 3973} 3974 3975void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T); 3976 3977void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 3978 SourceLocation CC, bool &ICContext) { 3979 E = E->IgnoreParenImpCasts(); 3980 3981 if (isa<ConditionalOperator>(E)) 3982 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), T); 3983 3984 AnalyzeImplicitConversions(S, E, CC); 3985 if (E->getType() != T) 3986 return CheckImplicitConversion(S, E, T, CC, &ICContext); 3987 return; 3988} 3989 3990void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T) { 3991 SourceLocation CC = E->getQuestionLoc(); 3992 3993 AnalyzeImplicitConversions(S, E->getCond(), CC); 3994 3995 bool Suspicious = false; 3996 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious); 3997 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 3998 3999 // If -Wconversion would have warned about either of the candidates 4000 // for a signedness conversion to the context type... 4001 if (!Suspicious) return; 4002 4003 // ...but it's currently ignored... 4004 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional, 4005 CC)) 4006 return; 4007 4008 // ...then check whether it would have warned about either of the 4009 // candidates for a signedness conversion to the condition type. 4010 if (E->getType() == T) return; 4011 4012 Suspicious = false; 4013 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(), 4014 E->getType(), CC, &Suspicious); 4015 if (!Suspicious) 4016 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 4017 E->getType(), CC, &Suspicious); 4018} 4019 4020/// AnalyzeImplicitConversions - Find and report any interesting 4021/// implicit conversions in the given expression. There are a couple 4022/// of competing diagnostics here, -Wconversion and -Wsign-compare. 4023void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) { 4024 QualType T = OrigE->getType(); 4025 Expr *E = OrigE->IgnoreParenImpCasts(); 4026 4027 if (E->isTypeDependent() || E->isValueDependent()) 4028 return; 4029 4030 // For conditional operators, we analyze the arguments as if they 4031 // were being fed directly into the output. 4032 if (isa<ConditionalOperator>(E)) { 4033 ConditionalOperator *CO = cast<ConditionalOperator>(E); 4034 CheckConditionalOperator(S, CO, T); 4035 return; 4036 } 4037 4038 // Go ahead and check any implicit conversions we might have skipped. 4039 // The non-canonical typecheck is just an optimization; 4040 // CheckImplicitConversion will filter out dead implicit conversions. 4041 if (E->getType() != T) 4042 CheckImplicitConversion(S, E, T, CC); 4043 4044 // Now continue drilling into this expression. 4045 4046 // Skip past explicit casts. 4047 if (isa<ExplicitCastExpr>(E)) { 4048 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts(); 4049 return AnalyzeImplicitConversions(S, E, CC); 4050 } 4051 4052 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 4053 // Do a somewhat different check with comparison operators. 4054 if (BO->isComparisonOp()) 4055 return AnalyzeComparison(S, BO); 4056 4057 // And with simple assignments. 4058 if (BO->getOpcode() == BO_Assign) 4059 return AnalyzeAssignment(S, BO); 4060 } 4061 4062 // These break the otherwise-useful invariant below. Fortunately, 4063 // we don't really need to recurse into them, because any internal 4064 // expressions should have been analyzed already when they were 4065 // built into statements. 4066 if (isa<StmtExpr>(E)) return; 4067 4068 // Don't descend into unevaluated contexts. 4069 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 4070 4071 // Now just recurse over the expression's children. 4072 CC = E->getExprLoc(); 4073 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 4074 bool IsLogicalOperator = BO && BO->isLogicalOp(); 4075 for (Stmt::child_range I = E->children(); I; ++I) { 4076 Expr *ChildExpr = cast<Expr>(*I); 4077 if (IsLogicalOperator && 4078 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 4079 // Ignore checking string literals that are in logical operators. 4080 continue; 4081 AnalyzeImplicitConversions(S, ChildExpr, CC); 4082 } 4083} 4084 4085} // end anonymous namespace 4086 4087/// Diagnoses "dangerous" implicit conversions within the given 4088/// expression (which is a full expression). Implements -Wconversion 4089/// and -Wsign-compare. 4090/// 4091/// \param CC the "context" location of the implicit conversion, i.e. 4092/// the most location of the syntactic entity requiring the implicit 4093/// conversion 4094void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 4095 // Don't diagnose in unevaluated contexts. 4096 if (ExprEvalContexts.back().Context == Sema::Unevaluated) 4097 return; 4098 4099 // Don't diagnose for value- or type-dependent expressions. 4100 if (E->isTypeDependent() || E->isValueDependent()) 4101 return; 4102 4103 // Check for array bounds violations in cases where the check isn't triggered 4104 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 4105 // ArraySubscriptExpr is on the RHS of a variable initialization. 4106 CheckArrayAccess(E); 4107 4108 // This is not the right CC for (e.g.) a variable initialization. 4109 AnalyzeImplicitConversions(*this, E, CC); 4110} 4111 4112void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 4113 FieldDecl *BitField, 4114 Expr *Init) { 4115 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 4116} 4117 4118/// CheckParmsForFunctionDef - Check that the parameters of the given 4119/// function are appropriate for the definition of a function. This 4120/// takes care of any checks that cannot be performed on the 4121/// declaration itself, e.g., that the types of each of the function 4122/// parameters are complete. 4123bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd, 4124 bool CheckParameterNames) { 4125 bool HasInvalidParm = false; 4126 for (; P != PEnd; ++P) { 4127 ParmVarDecl *Param = *P; 4128 4129 // C99 6.7.5.3p4: the parameters in a parameter type list in a 4130 // function declarator that is part of a function definition of 4131 // that function shall not have incomplete type. 4132 // 4133 // This is also C++ [dcl.fct]p6. 4134 if (!Param->isInvalidDecl() && 4135 RequireCompleteType(Param->getLocation(), Param->getType(), 4136 diag::err_typecheck_decl_incomplete_type)) { 4137 Param->setInvalidDecl(); 4138 HasInvalidParm = true; 4139 } 4140 4141 // C99 6.9.1p5: If the declarator includes a parameter type list, the 4142 // declaration of each parameter shall include an identifier. 4143 if (CheckParameterNames && 4144 Param->getIdentifier() == 0 && 4145 !Param->isImplicit() && 4146 !getLangOptions().CPlusPlus) 4147 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 4148 4149 // C99 6.7.5.3p12: 4150 // If the function declarator is not part of a definition of that 4151 // function, parameters may have incomplete type and may use the [*] 4152 // notation in their sequences of declarator specifiers to specify 4153 // variable length array types. 4154 QualType PType = Param->getOriginalType(); 4155 if (const ArrayType *AT = Context.getAsArrayType(PType)) { 4156 if (AT->getSizeModifier() == ArrayType::Star) { 4157 // FIXME: This diagnosic should point the the '[*]' if source-location 4158 // information is added for it. 4159 Diag(Param->getLocation(), diag::err_array_star_in_function_definition); 4160 } 4161 } 4162 } 4163 4164 return HasInvalidParm; 4165} 4166 4167/// CheckCastAlign - Implements -Wcast-align, which warns when a 4168/// pointer cast increases the alignment requirements. 4169void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 4170 // This is actually a lot of work to potentially be doing on every 4171 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 4172 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align, 4173 TRange.getBegin()) 4174 == DiagnosticsEngine::Ignored) 4175 return; 4176 4177 // Ignore dependent types. 4178 if (T->isDependentType() || Op->getType()->isDependentType()) 4179 return; 4180 4181 // Require that the destination be a pointer type. 4182 const PointerType *DestPtr = T->getAs<PointerType>(); 4183 if (!DestPtr) return; 4184 4185 // If the destination has alignment 1, we're done. 4186 QualType DestPointee = DestPtr->getPointeeType(); 4187 if (DestPointee->isIncompleteType()) return; 4188 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 4189 if (DestAlign.isOne()) return; 4190 4191 // Require that the source be a pointer type. 4192 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 4193 if (!SrcPtr) return; 4194 QualType SrcPointee = SrcPtr->getPointeeType(); 4195 4196 // Whitelist casts from cv void*. We already implicitly 4197 // whitelisted casts to cv void*, since they have alignment 1. 4198 // Also whitelist casts involving incomplete types, which implicitly 4199 // includes 'void'. 4200 if (SrcPointee->isIncompleteType()) return; 4201 4202 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee); 4203 if (SrcAlign >= DestAlign) return; 4204 4205 Diag(TRange.getBegin(), diag::warn_cast_align) 4206 << Op->getType() << T 4207 << static_cast<unsigned>(SrcAlign.getQuantity()) 4208 << static_cast<unsigned>(DestAlign.getQuantity()) 4209 << TRange << Op->getSourceRange(); 4210} 4211 4212static const Type* getElementType(const Expr *BaseExpr) { 4213 const Type* EltType = BaseExpr->getType().getTypePtr(); 4214 if (EltType->isAnyPointerType()) 4215 return EltType->getPointeeType().getTypePtr(); 4216 else if (EltType->isArrayType()) 4217 return EltType->getBaseElementTypeUnsafe(); 4218 return EltType; 4219} 4220 4221/// \brief Check whether this array fits the idiom of a size-one tail padded 4222/// array member of a struct. 4223/// 4224/// We avoid emitting out-of-bounds access warnings for such arrays as they are 4225/// commonly used to emulate flexible arrays in C89 code. 4226static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size, 4227 const NamedDecl *ND) { 4228 if (Size != 1 || !ND) return false; 4229 4230 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 4231 if (!FD) return false; 4232 4233 // Don't consider sizes resulting from macro expansions or template argument 4234 // substitution to form C89 tail-padded arrays. 4235 ConstantArrayTypeLoc TL = 4236 cast<ConstantArrayTypeLoc>(FD->getTypeSourceInfo()->getTypeLoc()); 4237 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(TL.getSizeExpr()); 4238 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 4239 return false; 4240 4241 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 4242 if (!RD) return false; 4243 if (RD->isUnion()) return false; 4244 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 4245 if (!CRD->isStandardLayout()) return false; 4246 } 4247 4248 // See if this is the last field decl in the record. 4249 const Decl *D = FD; 4250 while ((D = D->getNextDeclInContext())) 4251 if (isa<FieldDecl>(D)) 4252 return false; 4253 return true; 4254} 4255 4256void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 4257 const ArraySubscriptExpr *ASE, 4258 bool AllowOnePastEnd, bool IndexNegated) { 4259 IndexExpr = IndexExpr->IgnoreParenCasts(); 4260 if (IndexExpr->isValueDependent()) 4261 return; 4262 4263 const Type *EffectiveType = getElementType(BaseExpr); 4264 BaseExpr = BaseExpr->IgnoreParenCasts(); 4265 const ConstantArrayType *ArrayTy = 4266 Context.getAsConstantArrayType(BaseExpr->getType()); 4267 if (!ArrayTy) 4268 return; 4269 4270 llvm::APSInt index; 4271 if (!IndexExpr->EvaluateAsInt(index, Context)) 4272 return; 4273 if (IndexNegated) 4274 index = -index; 4275 4276 const NamedDecl *ND = NULL; 4277 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 4278 ND = dyn_cast<NamedDecl>(DRE->getDecl()); 4279 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 4280 ND = dyn_cast<NamedDecl>(ME->getMemberDecl()); 4281 4282 if (index.isUnsigned() || !index.isNegative()) { 4283 llvm::APInt size = ArrayTy->getSize(); 4284 if (!size.isStrictlyPositive()) 4285 return; 4286 4287 const Type* BaseType = getElementType(BaseExpr); 4288 if (BaseType != EffectiveType) { 4289 // Make sure we're comparing apples to apples when comparing index to size 4290 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 4291 uint64_t array_typesize = Context.getTypeSize(BaseType); 4292 // Handle ptrarith_typesize being zero, such as when casting to void* 4293 if (!ptrarith_typesize) ptrarith_typesize = 1; 4294 if (ptrarith_typesize != array_typesize) { 4295 // There's a cast to a different size type involved 4296 uint64_t ratio = array_typesize / ptrarith_typesize; 4297 // TODO: Be smarter about handling cases where array_typesize is not a 4298 // multiple of ptrarith_typesize 4299 if (ptrarith_typesize * ratio == array_typesize) 4300 size *= llvm::APInt(size.getBitWidth(), ratio); 4301 } 4302 } 4303 4304 if (size.getBitWidth() > index.getBitWidth()) 4305 index = index.sext(size.getBitWidth()); 4306 else if (size.getBitWidth() < index.getBitWidth()) 4307 size = size.sext(index.getBitWidth()); 4308 4309 // For array subscripting the index must be less than size, but for pointer 4310 // arithmetic also allow the index (offset) to be equal to size since 4311 // computing the next address after the end of the array is legal and 4312 // commonly done e.g. in C++ iterators and range-based for loops. 4313 if (AllowOnePastEnd ? index.sle(size) : index.slt(size)) 4314 return; 4315 4316 // Also don't warn for arrays of size 1 which are members of some 4317 // structure. These are often used to approximate flexible arrays in C89 4318 // code. 4319 if (IsTailPaddedMemberArray(*this, size, ND)) 4320 return; 4321 4322 // Suppress the warning if the subscript expression (as identified by the 4323 // ']' location) and the index expression are both from macro expansions 4324 // within a system header. 4325 if (ASE) { 4326 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 4327 ASE->getRBracketLoc()); 4328 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 4329 SourceLocation IndexLoc = SourceMgr.getSpellingLoc( 4330 IndexExpr->getLocStart()); 4331 if (SourceMgr.isFromSameFile(RBracketLoc, IndexLoc)) 4332 return; 4333 } 4334 } 4335 4336 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 4337 if (ASE) 4338 DiagID = diag::warn_array_index_exceeds_bounds; 4339 4340 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 4341 PDiag(DiagID) << index.toString(10, true) 4342 << size.toString(10, true) 4343 << (unsigned)size.getLimitedValue(~0U) 4344 << IndexExpr->getSourceRange()); 4345 } else { 4346 unsigned DiagID = diag::warn_array_index_precedes_bounds; 4347 if (!ASE) { 4348 DiagID = diag::warn_ptr_arith_precedes_bounds; 4349 if (index.isNegative()) index = -index; 4350 } 4351 4352 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 4353 PDiag(DiagID) << index.toString(10, true) 4354 << IndexExpr->getSourceRange()); 4355 } 4356 4357 if (!ND) { 4358 // Try harder to find a NamedDecl to point at in the note. 4359 while (const ArraySubscriptExpr *ASE = 4360 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 4361 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 4362 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 4363 ND = dyn_cast<NamedDecl>(DRE->getDecl()); 4364 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 4365 ND = dyn_cast<NamedDecl>(ME->getMemberDecl()); 4366 } 4367 4368 if (ND) 4369 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr, 4370 PDiag(diag::note_array_index_out_of_bounds) 4371 << ND->getDeclName()); 4372} 4373 4374void Sema::CheckArrayAccess(const Expr *expr) { 4375 int AllowOnePastEnd = 0; 4376 while (expr) { 4377 expr = expr->IgnoreParenImpCasts(); 4378 switch (expr->getStmtClass()) { 4379 case Stmt::ArraySubscriptExprClass: { 4380 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 4381 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 4382 AllowOnePastEnd > 0); 4383 return; 4384 } 4385 case Stmt::UnaryOperatorClass: { 4386 // Only unwrap the * and & unary operators 4387 const UnaryOperator *UO = cast<UnaryOperator>(expr); 4388 expr = UO->getSubExpr(); 4389 switch (UO->getOpcode()) { 4390 case UO_AddrOf: 4391 AllowOnePastEnd++; 4392 break; 4393 case UO_Deref: 4394 AllowOnePastEnd--; 4395 break; 4396 default: 4397 return; 4398 } 4399 break; 4400 } 4401 case Stmt::ConditionalOperatorClass: { 4402 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 4403 if (const Expr *lhs = cond->getLHS()) 4404 CheckArrayAccess(lhs); 4405 if (const Expr *rhs = cond->getRHS()) 4406 CheckArrayAccess(rhs); 4407 return; 4408 } 4409 default: 4410 return; 4411 } 4412 } 4413} 4414 4415//===--- CHECK: Objective-C retain cycles ----------------------------------// 4416 4417namespace { 4418 struct RetainCycleOwner { 4419 RetainCycleOwner() : Variable(0), Indirect(false) {} 4420 VarDecl *Variable; 4421 SourceRange Range; 4422 SourceLocation Loc; 4423 bool Indirect; 4424 4425 void setLocsFrom(Expr *e) { 4426 Loc = e->getExprLoc(); 4427 Range = e->getSourceRange(); 4428 } 4429 }; 4430} 4431 4432/// Consider whether capturing the given variable can possibly lead to 4433/// a retain cycle. 4434static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 4435 // In ARC, it's captured strongly iff the variable has __strong 4436 // lifetime. In MRR, it's captured strongly if the variable is 4437 // __block and has an appropriate type. 4438 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 4439 return false; 4440 4441 owner.Variable = var; 4442 owner.setLocsFrom(ref); 4443 return true; 4444} 4445 4446static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 4447 while (true) { 4448 e = e->IgnoreParens(); 4449 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 4450 switch (cast->getCastKind()) { 4451 case CK_BitCast: 4452 case CK_LValueBitCast: 4453 case CK_LValueToRValue: 4454 case CK_ARCReclaimReturnedObject: 4455 e = cast->getSubExpr(); 4456 continue; 4457 4458 default: 4459 return false; 4460 } 4461 } 4462 4463 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 4464 ObjCIvarDecl *ivar = ref->getDecl(); 4465 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 4466 return false; 4467 4468 // Try to find a retain cycle in the base. 4469 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 4470 return false; 4471 4472 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 4473 owner.Indirect = true; 4474 return true; 4475 } 4476 4477 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 4478 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 4479 if (!var) return false; 4480 return considerVariable(var, ref, owner); 4481 } 4482 4483 if (BlockDeclRefExpr *ref = dyn_cast<BlockDeclRefExpr>(e)) { 4484 owner.Variable = ref->getDecl(); 4485 owner.setLocsFrom(ref); 4486 return true; 4487 } 4488 4489 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 4490 if (member->isArrow()) return false; 4491 4492 // Don't count this as an indirect ownership. 4493 e = member->getBase(); 4494 continue; 4495 } 4496 4497 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 4498 // Only pay attention to pseudo-objects on property references. 4499 ObjCPropertyRefExpr *pre 4500 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 4501 ->IgnoreParens()); 4502 if (!pre) return false; 4503 if (pre->isImplicitProperty()) return false; 4504 ObjCPropertyDecl *property = pre->getExplicitProperty(); 4505 if (!property->isRetaining() && 4506 !(property->getPropertyIvarDecl() && 4507 property->getPropertyIvarDecl()->getType() 4508 .getObjCLifetime() == Qualifiers::OCL_Strong)) 4509 return false; 4510 4511 owner.Indirect = true; 4512 if (pre->isSuperReceiver()) { 4513 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 4514 if (!owner.Variable) 4515 return false; 4516 owner.Loc = pre->getLocation(); 4517 owner.Range = pre->getSourceRange(); 4518 return true; 4519 } 4520 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 4521 ->getSourceExpr()); 4522 continue; 4523 } 4524 4525 // Array ivars? 4526 4527 return false; 4528 } 4529} 4530 4531namespace { 4532 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 4533 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 4534 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 4535 Variable(variable), Capturer(0) {} 4536 4537 VarDecl *Variable; 4538 Expr *Capturer; 4539 4540 void VisitDeclRefExpr(DeclRefExpr *ref) { 4541 if (ref->getDecl() == Variable && !Capturer) 4542 Capturer = ref; 4543 } 4544 4545 void VisitBlockDeclRefExpr(BlockDeclRefExpr *ref) { 4546 if (ref->getDecl() == Variable && !Capturer) 4547 Capturer = ref; 4548 } 4549 4550 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 4551 if (Capturer) return; 4552 Visit(ref->getBase()); 4553 if (Capturer && ref->isFreeIvar()) 4554 Capturer = ref; 4555 } 4556 4557 void VisitBlockExpr(BlockExpr *block) { 4558 // Look inside nested blocks 4559 if (block->getBlockDecl()->capturesVariable(Variable)) 4560 Visit(block->getBlockDecl()->getBody()); 4561 } 4562 }; 4563} 4564 4565/// Check whether the given argument is a block which captures a 4566/// variable. 4567static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 4568 assert(owner.Variable && owner.Loc.isValid()); 4569 4570 e = e->IgnoreParenCasts(); 4571 BlockExpr *block = dyn_cast<BlockExpr>(e); 4572 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 4573 return 0; 4574 4575 FindCaptureVisitor visitor(S.Context, owner.Variable); 4576 visitor.Visit(block->getBlockDecl()->getBody()); 4577 return visitor.Capturer; 4578} 4579 4580static void diagnoseRetainCycle(Sema &S, Expr *capturer, 4581 RetainCycleOwner &owner) { 4582 assert(capturer); 4583 assert(owner.Variable && owner.Loc.isValid()); 4584 4585 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 4586 << owner.Variable << capturer->getSourceRange(); 4587 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 4588 << owner.Indirect << owner.Range; 4589} 4590 4591/// Check for a keyword selector that starts with the word 'add' or 4592/// 'set'. 4593static bool isSetterLikeSelector(Selector sel) { 4594 if (sel.isUnarySelector()) return false; 4595 4596 StringRef str = sel.getNameForSlot(0); 4597 while (!str.empty() && str.front() == '_') str = str.substr(1); 4598 if (str.startswith("set")) 4599 str = str.substr(3); 4600 else if (str.startswith("add")) { 4601 // Specially whitelist 'addOperationWithBlock:'. 4602 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 4603 return false; 4604 str = str.substr(3); 4605 } 4606 else 4607 return false; 4608 4609 if (str.empty()) return true; 4610 return !islower(str.front()); 4611} 4612 4613/// Check a message send to see if it's likely to cause a retain cycle. 4614void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 4615 // Only check instance methods whose selector looks like a setter. 4616 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 4617 return; 4618 4619 // Try to find a variable that the receiver is strongly owned by. 4620 RetainCycleOwner owner; 4621 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 4622 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 4623 return; 4624 } else { 4625 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 4626 owner.Variable = getCurMethodDecl()->getSelfDecl(); 4627 owner.Loc = msg->getSuperLoc(); 4628 owner.Range = msg->getSuperLoc(); 4629 } 4630 4631 // Check whether the receiver is captured by any of the arguments. 4632 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) 4633 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) 4634 return diagnoseRetainCycle(*this, capturer, owner); 4635} 4636 4637/// Check a property assign to see if it's likely to cause a retain cycle. 4638void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 4639 RetainCycleOwner owner; 4640 if (!findRetainCycleOwner(*this, receiver, owner)) 4641 return; 4642 4643 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 4644 diagnoseRetainCycle(*this, capturer, owner); 4645} 4646 4647bool Sema::checkUnsafeAssigns(SourceLocation Loc, 4648 QualType LHS, Expr *RHS) { 4649 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 4650 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 4651 return false; 4652 // strip off any implicit cast added to get to the one arc-specific 4653 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 4654 if (cast->getCastKind() == CK_ARCConsumeObject) { 4655 Diag(Loc, diag::warn_arc_retained_assign) 4656 << (LT == Qualifiers::OCL_ExplicitNone) 4657 << RHS->getSourceRange(); 4658 return true; 4659 } 4660 RHS = cast->getSubExpr(); 4661 } 4662 return false; 4663} 4664 4665void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 4666 Expr *LHS, Expr *RHS) { 4667 QualType LHSType; 4668 // PropertyRef on LHS type need be directly obtained from 4669 // its declaration as it has a PsuedoType. 4670 ObjCPropertyRefExpr *PRE 4671 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 4672 if (PRE && !PRE->isImplicitProperty()) { 4673 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 4674 if (PD) 4675 LHSType = PD->getType(); 4676 } 4677 4678 if (LHSType.isNull()) 4679 LHSType = LHS->getType(); 4680 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 4681 return; 4682 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 4683 // FIXME. Check for other life times. 4684 if (LT != Qualifiers::OCL_None) 4685 return; 4686 4687 if (PRE) { 4688 if (PRE->isImplicitProperty()) 4689 return; 4690 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 4691 if (!PD) 4692 return; 4693 4694 unsigned Attributes = PD->getPropertyAttributes(); 4695 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) { 4696 // when 'assign' attribute was not explicitly specified 4697 // by user, ignore it and rely on property type itself 4698 // for lifetime info. 4699 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 4700 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) && 4701 LHSType->isObjCRetainableType()) 4702 return; 4703 4704 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 4705 if (cast->getCastKind() == CK_ARCConsumeObject) { 4706 Diag(Loc, diag::warn_arc_retained_property_assign) 4707 << RHS->getSourceRange(); 4708 return; 4709 } 4710 RHS = cast->getSubExpr(); 4711 } 4712 } 4713 } 4714} 4715