SemaChecking.cpp revision d69ec16b1b03b4a97c571ff14f15769fe13c1e5a
1//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10//  This file implements extra semantic analysis beyond what is enforced
11//  by the C type system.
12//
13//===----------------------------------------------------------------------===//
14
15#include "Sema.h"
16#include "clang/Analysis/Analyses/PrintfFormatString.h"
17#include "clang/AST/ASTContext.h"
18#include "clang/AST/CharUnits.h"
19#include "clang/AST/DeclObjC.h"
20#include "clang/AST/ExprCXX.h"
21#include "clang/AST/ExprObjC.h"
22#include "clang/AST/DeclObjC.h"
23#include "clang/AST/StmtCXX.h"
24#include "clang/AST/StmtObjC.h"
25#include "clang/Lex/LiteralSupport.h"
26#include "clang/Lex/Preprocessor.h"
27#include "llvm/ADT/BitVector.h"
28#include "llvm/ADT/STLExtras.h"
29#include "llvm/ADT/StringExtras.h"
30#include "llvm/Support/raw_ostream.h"
31#include "clang/Basic/TargetBuiltins.h"
32#include "clang/Basic/TargetInfo.h"
33#include <limits>
34using namespace clang;
35
36/// getLocationOfStringLiteralByte - Return a source location that points to the
37/// specified byte of the specified string literal.
38///
39/// Strings are amazingly complex.  They can be formed from multiple tokens and
40/// can have escape sequences in them in addition to the usual trigraph and
41/// escaped newline business.  This routine handles this complexity.
42///
43SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
44                                                    unsigned ByteNo) const {
45  assert(!SL->isWide() && "This doesn't work for wide strings yet");
46
47  // Loop over all of the tokens in this string until we find the one that
48  // contains the byte we're looking for.
49  unsigned TokNo = 0;
50  while (1) {
51    assert(TokNo < SL->getNumConcatenated() && "Invalid byte number!");
52    SourceLocation StrTokLoc = SL->getStrTokenLoc(TokNo);
53
54    // Get the spelling of the string so that we can get the data that makes up
55    // the string literal, not the identifier for the macro it is potentially
56    // expanded through.
57    SourceLocation StrTokSpellingLoc = SourceMgr.getSpellingLoc(StrTokLoc);
58
59    // Re-lex the token to get its length and original spelling.
60    std::pair<FileID, unsigned> LocInfo =
61      SourceMgr.getDecomposedLoc(StrTokSpellingLoc);
62    bool Invalid = false;
63    llvm::StringRef Buffer = SourceMgr.getBufferData(LocInfo.first, &Invalid);
64    if (Invalid)
65      return StrTokSpellingLoc;
66
67    const char *StrData = Buffer.data()+LocInfo.second;
68
69    // Create a langops struct and enable trigraphs.  This is sufficient for
70    // relexing tokens.
71    LangOptions LangOpts;
72    LangOpts.Trigraphs = true;
73
74    // Create a lexer starting at the beginning of this token.
75    Lexer TheLexer(StrTokSpellingLoc, LangOpts, Buffer.begin(), StrData,
76                   Buffer.end());
77    Token TheTok;
78    TheLexer.LexFromRawLexer(TheTok);
79
80    // Use the StringLiteralParser to compute the length of the string in bytes.
81    StringLiteralParser SLP(&TheTok, 1, PP, /*Complain=*/false);
82    unsigned TokNumBytes = SLP.GetStringLength();
83
84    // If the byte is in this token, return the location of the byte.
85    if (ByteNo < TokNumBytes ||
86        (ByteNo == TokNumBytes && TokNo == SL->getNumConcatenated())) {
87      unsigned Offset =
88        StringLiteralParser::getOffsetOfStringByte(TheTok, ByteNo, PP,
89                                                   /*Complain=*/false);
90
91      // Now that we know the offset of the token in the spelling, use the
92      // preprocessor to get the offset in the original source.
93      return PP.AdvanceToTokenCharacter(StrTokLoc, Offset);
94    }
95
96    // Move to the next string token.
97    ++TokNo;
98    ByteNo -= TokNumBytes;
99  }
100}
101
102/// CheckablePrintfAttr - does a function call have a "printf" attribute
103/// and arguments that merit checking?
104bool Sema::CheckablePrintfAttr(const FormatAttr *Format, CallExpr *TheCall) {
105  if (Format->getType() == "printf") return true;
106  if (Format->getType() == "printf0") {
107    // printf0 allows null "format" string; if so don't check format/args
108    unsigned format_idx = Format->getFormatIdx() - 1;
109    // Does the index refer to the implicit object argument?
110    if (isa<CXXMemberCallExpr>(TheCall)) {
111      if (format_idx == 0)
112        return false;
113      --format_idx;
114    }
115    if (format_idx < TheCall->getNumArgs()) {
116      Expr *Format = TheCall->getArg(format_idx)->IgnoreParenCasts();
117      if (!Format->isNullPointerConstant(Context,
118                                         Expr::NPC_ValueDependentIsNull))
119        return true;
120    }
121  }
122  return false;
123}
124
125Action::OwningExprResult
126Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
127  OwningExprResult TheCallResult(Owned(TheCall));
128
129  switch (BuiltinID) {
130  case Builtin::BI__builtin___CFStringMakeConstantString:
131    assert(TheCall->getNumArgs() == 1 &&
132           "Wrong # arguments to builtin CFStringMakeConstantString");
133    if (CheckObjCString(TheCall->getArg(0)))
134      return ExprError();
135    break;
136  case Builtin::BI__builtin_stdarg_start:
137  case Builtin::BI__builtin_va_start:
138    if (SemaBuiltinVAStart(TheCall))
139      return ExprError();
140    break;
141  case Builtin::BI__builtin_isgreater:
142  case Builtin::BI__builtin_isgreaterequal:
143  case Builtin::BI__builtin_isless:
144  case Builtin::BI__builtin_islessequal:
145  case Builtin::BI__builtin_islessgreater:
146  case Builtin::BI__builtin_isunordered:
147    if (SemaBuiltinUnorderedCompare(TheCall))
148      return ExprError();
149    break;
150  case Builtin::BI__builtin_fpclassify:
151    if (SemaBuiltinFPClassification(TheCall, 6))
152      return ExprError();
153    break;
154  case Builtin::BI__builtin_isfinite:
155  case Builtin::BI__builtin_isinf:
156  case Builtin::BI__builtin_isinf_sign:
157  case Builtin::BI__builtin_isnan:
158  case Builtin::BI__builtin_isnormal:
159    if (SemaBuiltinFPClassification(TheCall, 1))
160      return ExprError();
161    break;
162  case Builtin::BI__builtin_return_address:
163  case Builtin::BI__builtin_frame_address: {
164    llvm::APSInt Result;
165    if (SemaBuiltinConstantArg(TheCall, 0, Result))
166      return ExprError();
167    break;
168  }
169  case Builtin::BI__builtin_eh_return_data_regno: {
170    llvm::APSInt Result;
171    if (SemaBuiltinConstantArg(TheCall, 0, Result))
172      return ExprError();
173    break;
174  }
175  case Builtin::BI__builtin_shufflevector:
176    return SemaBuiltinShuffleVector(TheCall);
177    // TheCall will be freed by the smart pointer here, but that's fine, since
178    // SemaBuiltinShuffleVector guts it, but then doesn't release it.
179  case Builtin::BI__builtin_prefetch:
180    if (SemaBuiltinPrefetch(TheCall))
181      return ExprError();
182    break;
183  case Builtin::BI__builtin_object_size:
184    if (SemaBuiltinObjectSize(TheCall))
185      return ExprError();
186    break;
187  case Builtin::BI__builtin_longjmp:
188    if (SemaBuiltinLongjmp(TheCall))
189      return ExprError();
190    break;
191  case Builtin::BI__sync_fetch_and_add:
192  case Builtin::BI__sync_fetch_and_sub:
193  case Builtin::BI__sync_fetch_and_or:
194  case Builtin::BI__sync_fetch_and_and:
195  case Builtin::BI__sync_fetch_and_xor:
196  case Builtin::BI__sync_add_and_fetch:
197  case Builtin::BI__sync_sub_and_fetch:
198  case Builtin::BI__sync_and_and_fetch:
199  case Builtin::BI__sync_or_and_fetch:
200  case Builtin::BI__sync_xor_and_fetch:
201  case Builtin::BI__sync_val_compare_and_swap:
202  case Builtin::BI__sync_bool_compare_and_swap:
203  case Builtin::BI__sync_lock_test_and_set:
204  case Builtin::BI__sync_lock_release:
205    if (SemaBuiltinAtomicOverloaded(TheCall))
206      return ExprError();
207    break;
208  }
209
210  // Since the target specific builtins for each arch overlap, only check those
211  // of the arch we are compiling for.
212  if (BuiltinID >= Builtin::FirstTSBuiltin) {
213    switch (Context.Target.getTriple().getArch()) {
214      case llvm::Triple::arm:
215      case llvm::Triple::thumb:
216        if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
217          return ExprError();
218        break;
219      case llvm::Triple::x86:
220      case llvm::Triple::x86_64:
221        if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
222          return ExprError();
223        break;
224      default:
225        break;
226    }
227  }
228
229  return move(TheCallResult);
230}
231
232bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
233  switch (BuiltinID) {
234  case X86::BI__builtin_ia32_palignr128:
235  case X86::BI__builtin_ia32_palignr: {
236    llvm::APSInt Result;
237    if (SemaBuiltinConstantArg(TheCall, 2, Result))
238      return true;
239    break;
240  }
241  }
242  return false;
243}
244
245// Get the valid immediate range for the specified NEON type code.
246static unsigned RFT(unsigned t, bool shift = false) {
247  bool quad = t & 0x10;
248
249  switch (t & 0x7) {
250    case 0: // i8
251      return shift ? 7 : (8 << (int)quad) - 1;
252    case 1: // i16
253      return shift ? 15 : (4 << (int)quad) - 1;
254    case 2: // i32
255      return shift ? 31 : (2 << (int)quad) - 1;
256    case 3: // i64
257      return shift ? 63 : (1 << (int)quad) - 1;
258    case 4: // f32
259      assert(!shift && "cannot shift float types!");
260      return (2 << (int)quad) - 1;
261    case 5: // poly8
262      assert(!shift && "cannot shift polynomial types!");
263      return (8 << (int)quad) - 1;
264    case 6: // poly16
265      assert(!shift && "cannot shift polynomial types!");
266      return (4 << (int)quad) - 1;
267    case 7: // float16
268      assert(!shift && "cannot shift float types!");
269      return (4 << (int)quad) - 1;
270  }
271  return 0;
272}
273
274bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
275  llvm::APSInt Result;
276
277  unsigned mask = 0;
278  unsigned TV = 0;
279  switch (BuiltinID) {
280  case ARM::BI__builtin_neon_vaba_v: mask = 0x707; break;
281  case ARM::BI__builtin_neon_vabaq_v: mask = 0x7070000; break;
282  case ARM::BI__builtin_neon_vabal_v: mask = 0xE0E0000; break;
283  case ARM::BI__builtin_neon_vabd_v: mask = 0x717; break;
284  case ARM::BI__builtin_neon_vabdq_v: mask = 0x7170000; break;
285  case ARM::BI__builtin_neon_vabdl_v: mask = 0xE0E0000; break;
286  case ARM::BI__builtin_neon_vabs_v: mask = 0x17; break;
287  case ARM::BI__builtin_neon_vabsq_v: mask = 0x170000; break;
288  case ARM::BI__builtin_neon_vaddhn_v: mask = 0x707; break;
289  case ARM::BI__builtin_neon_vaddl_v: mask = 0xE0E0000; break;
290  case ARM::BI__builtin_neon_vaddw_v: mask = 0xE0E0000; break;
291  case ARM::BI__builtin_neon_vcage_v: mask = 0x400; break;
292  case ARM::BI__builtin_neon_vcageq_v: mask = 0x4000000; break;
293  case ARM::BI__builtin_neon_vcagt_v: mask = 0x400; break;
294  case ARM::BI__builtin_neon_vcagtq_v: mask = 0x4000000; break;
295  case ARM::BI__builtin_neon_vcale_v: mask = 0x400; break;
296  case ARM::BI__builtin_neon_vcaleq_v: mask = 0x4000000; break;
297  case ARM::BI__builtin_neon_vcalt_v: mask = 0x400; break;
298  case ARM::BI__builtin_neon_vcaltq_v: mask = 0x4000000; break;
299  case ARM::BI__builtin_neon_vcls_v: mask = 0x7; break;
300  case ARM::BI__builtin_neon_vclsq_v: mask = 0x70000; break;
301  case ARM::BI__builtin_neon_vclz_v: mask = 0x707; break;
302  case ARM::BI__builtin_neon_vclzq_v: mask = 0x7070000; break;
303  case ARM::BI__builtin_neon_vcnt_v: mask = 0x121; break;
304  case ARM::BI__builtin_neon_vcntq_v: mask = 0x1210000; break;
305  case ARM::BI__builtin_neon_vcvt_f16_v: mask = 0x80; break;
306  case ARM::BI__builtin_neon_vcvt_f32_v: mask = 0x404; break;
307  case ARM::BI__builtin_neon_vcvtq_f32_v: mask = 0x4040000; break;
308  case ARM::BI__builtin_neon_vcvt_f32_f16: mask = 0x100000; break;
309  case ARM::BI__builtin_neon_vcvt_n_f32_v: mask = 0x404; break;
310  case ARM::BI__builtin_neon_vcvtq_n_f32_v: mask = 0x4040000; break;
311  case ARM::BI__builtin_neon_vcvt_n_s32_v: mask = 0x4; break;
312  case ARM::BI__builtin_neon_vcvtq_n_s32_v: mask = 0x40000; break;
313  case ARM::BI__builtin_neon_vcvt_n_u32_v: mask = 0x400; break;
314  case ARM::BI__builtin_neon_vcvtq_n_u32_v: mask = 0x4000000; break;
315  case ARM::BI__builtin_neon_vcvt_s32_v: mask = 0x4; break;
316  case ARM::BI__builtin_neon_vcvtq_s32_v: mask = 0x40000; break;
317  case ARM::BI__builtin_neon_vcvt_u32_v: mask = 0x400; break;
318  case ARM::BI__builtin_neon_vcvtq_u32_v: mask = 0x4000000; break;
319  case ARM::BI__builtin_neon_vext_v: mask = 0xF6F; break;
320  case ARM::BI__builtin_neon_vextq_v: mask = 0xF6F0000; break;
321  case ARM::BI__builtin_neon_vhadd_v: mask = 0x707; break;
322  case ARM::BI__builtin_neon_vhaddq_v: mask = 0x7070000; break;
323  case ARM::BI__builtin_neon_vhsub_v: mask = 0x707; break;
324  case ARM::BI__builtin_neon_vhsubq_v: mask = 0x7070000; break;
325  case ARM::BI__builtin_neon_vld1_v: mask = 0xFFF; break;
326  case ARM::BI__builtin_neon_vld1q_v: mask = 0xFFF0000; break;
327  case ARM::BI__builtin_neon_vld1_dup_v: mask = 0xFFF; break;
328  case ARM::BI__builtin_neon_vld1q_dup_v: mask = 0xFFF0000; break;
329  case ARM::BI__builtin_neon_vld1_lane_v: mask = 0xFFF; break;
330  case ARM::BI__builtin_neon_vld1q_lane_v: mask = 0xFFF0000; break;
331  case ARM::BI__builtin_neon_vld2_v: mask = 0xFFF; break;
332  case ARM::BI__builtin_neon_vld2q_v: mask = 0x7F70000; break;
333  case ARM::BI__builtin_neon_vld2_dup_v: mask = 0xFFF; break;
334  case ARM::BI__builtin_neon_vld2_lane_v: mask = 0x7F7; break;
335  case ARM::BI__builtin_neon_vld2q_lane_v: mask = 0x6D60000; break;
336  case ARM::BI__builtin_neon_vld3_v: mask = 0xFFF; break;
337  case ARM::BI__builtin_neon_vld3q_v: mask = 0x7F70000; break;
338  case ARM::BI__builtin_neon_vld3_dup_v: mask = 0xFFF; break;
339  case ARM::BI__builtin_neon_vld3_lane_v: mask = 0x7F7; break;
340  case ARM::BI__builtin_neon_vld3q_lane_v: mask = 0x6D60000; break;
341  case ARM::BI__builtin_neon_vld4_v: mask = 0xFFF; break;
342  case ARM::BI__builtin_neon_vld4q_v: mask = 0x7F70000; break;
343  case ARM::BI__builtin_neon_vld4_dup_v: mask = 0xFFF; break;
344  case ARM::BI__builtin_neon_vld4_lane_v: mask = 0x7F7; break;
345  case ARM::BI__builtin_neon_vld4q_lane_v: mask = 0x6D60000; break;
346  case ARM::BI__builtin_neon_vmax_v: mask = 0x717; break;
347  case ARM::BI__builtin_neon_vmaxq_v: mask = 0x7170000; break;
348  case ARM::BI__builtin_neon_vmin_v: mask = 0x717; break;
349  case ARM::BI__builtin_neon_vminq_v: mask = 0x7170000; break;
350  case ARM::BI__builtin_neon_vmlal_v: mask = 0xE0E0000; break;
351  case ARM::BI__builtin_neon_vmlal_lane_v: mask = 0xC0C0000; break;
352  case ARM::BI__builtin_neon_vmla_lane_v: mask = 0x616; break;
353  case ARM::BI__builtin_neon_vmlaq_lane_v: mask = 0x6160000; break;
354  case ARM::BI__builtin_neon_vmlsl_v: mask = 0xE0E0000; break;
355  case ARM::BI__builtin_neon_vmlsl_lane_v: mask = 0xC0C0000; break;
356  case ARM::BI__builtin_neon_vmls_lane_v: mask = 0x616; break;
357  case ARM::BI__builtin_neon_vmlsq_lane_v: mask = 0x6160000; break;
358  case ARM::BI__builtin_neon_vmovl_v: mask = 0xE0E0000; break;
359  case ARM::BI__builtin_neon_vmovn_v: mask = 0x707; break;
360  case ARM::BI__builtin_neon_vmull_v: mask = 0xE4E0000; break;
361  case ARM::BI__builtin_neon_vmull_lane_v: mask = 0xC0C0000; break;
362  case ARM::BI__builtin_neon_vpadal_v: mask = 0xE0E; break;
363  case ARM::BI__builtin_neon_vpadalq_v: mask = 0xE0E0000; break;
364  case ARM::BI__builtin_neon_vpadd_v: mask = 0x717; break;
365  case ARM::BI__builtin_neon_vpaddl_v: mask = 0xE0E; break;
366  case ARM::BI__builtin_neon_vpaddlq_v: mask = 0xE0E0000; break;
367  case ARM::BI__builtin_neon_vpmax_v: mask = 0x717; break;
368  case ARM::BI__builtin_neon_vpmin_v: mask = 0x717; break;
369  case ARM::BI__builtin_neon_vqabs_v: mask = 0x7; break;
370  case ARM::BI__builtin_neon_vqabsq_v: mask = 0x70000; break;
371  case ARM::BI__builtin_neon_vqadd_v: mask = 0xF0F; break;
372  case ARM::BI__builtin_neon_vqaddq_v: mask = 0xF0F0000; break;
373  case ARM::BI__builtin_neon_vqdmlal_v: mask = 0xC0000; break;
374  case ARM::BI__builtin_neon_vqdmlal_lane_v: mask = 0xC0000; break;
375  case ARM::BI__builtin_neon_vqdmlsl_v: mask = 0xC0000; break;
376  case ARM::BI__builtin_neon_vqdmlsl_lane_v: mask = 0xC0000; break;
377  case ARM::BI__builtin_neon_vqdmulh_v: mask = 0x6; break;
378  case ARM::BI__builtin_neon_vqdmulhq_v: mask = 0x60000; break;
379  case ARM::BI__builtin_neon_vqdmulh_lane_v: mask = 0x6; break;
380  case ARM::BI__builtin_neon_vqdmulhq_lane_v: mask = 0x60000; break;
381  case ARM::BI__builtin_neon_vqdmull_v: mask = 0xC0000; break;
382  case ARM::BI__builtin_neon_vqdmull_lane_v: mask = 0xC0000; break;
383  case ARM::BI__builtin_neon_vqmovn_v: mask = 0x707; break;
384  case ARM::BI__builtin_neon_vqmovun_v: mask = 0x700; break;
385  case ARM::BI__builtin_neon_vqneg_v: mask = 0x7; break;
386  case ARM::BI__builtin_neon_vqnegq_v: mask = 0x70000; break;
387  case ARM::BI__builtin_neon_vqrdmulh_v: mask = 0x6; break;
388  case ARM::BI__builtin_neon_vqrdmulhq_v: mask = 0x60000; break;
389  case ARM::BI__builtin_neon_vqrdmulh_lane_v: mask = 0x6; break;
390  case ARM::BI__builtin_neon_vqrdmulhq_lane_v: mask = 0x60000; break;
391  case ARM::BI__builtin_neon_vqrshl_v: mask = 0xF0F; break;
392  case ARM::BI__builtin_neon_vqrshlq_v: mask = 0xF0F0000; break;
393  case ARM::BI__builtin_neon_vqrshrn_n_v: mask = 0x707; break;
394  case ARM::BI__builtin_neon_vqrshrun_n_v: mask = 0x700; break;
395  case ARM::BI__builtin_neon_vqshl_v: mask = 0xF0F; break;
396  case ARM::BI__builtin_neon_vqshlq_v: mask = 0xF0F0000; break;
397  case ARM::BI__builtin_neon_vqshlu_n_v: mask = 0xF00; break;
398  case ARM::BI__builtin_neon_vqshluq_n_v: mask = 0xF000000; break;
399  case ARM::BI__builtin_neon_vqshl_n_v: mask = 0xF0F; break;
400  case ARM::BI__builtin_neon_vqshlq_n_v: mask = 0xF0F0000; break;
401  case ARM::BI__builtin_neon_vqshrn_n_v: mask = 0x707; break;
402  case ARM::BI__builtin_neon_vqshrun_n_v: mask = 0x700; break;
403  case ARM::BI__builtin_neon_vqsub_v: mask = 0xF0F; break;
404  case ARM::BI__builtin_neon_vqsubq_v: mask = 0xF0F0000; break;
405  case ARM::BI__builtin_neon_vraddhn_v: mask = 0x707; break;
406  case ARM::BI__builtin_neon_vrecpe_v: mask = 0x410; break;
407  case ARM::BI__builtin_neon_vrecpeq_v: mask = 0x4100000; break;
408  case ARM::BI__builtin_neon_vrecps_v: mask = 0x10; break;
409  case ARM::BI__builtin_neon_vrecpsq_v: mask = 0x100000; break;
410  case ARM::BI__builtin_neon_vrhadd_v: mask = 0x707; break;
411  case ARM::BI__builtin_neon_vrhaddq_v: mask = 0x7070000; break;
412  case ARM::BI__builtin_neon_vrshl_v: mask = 0xF0F; break;
413  case ARM::BI__builtin_neon_vrshlq_v: mask = 0xF0F0000; break;
414  case ARM::BI__builtin_neon_vrshrn_n_v: mask = 0x707; break;
415  case ARM::BI__builtin_neon_vrshr_n_v: mask = 0xF0F; break;
416  case ARM::BI__builtin_neon_vrshrq_n_v: mask = 0xF0F0000; break;
417  case ARM::BI__builtin_neon_vrsqrte_v: mask = 0x410; break;
418  case ARM::BI__builtin_neon_vrsqrteq_v: mask = 0x4100000; break;
419  case ARM::BI__builtin_neon_vrsqrts_v: mask = 0x10; break;
420  case ARM::BI__builtin_neon_vrsqrtsq_v: mask = 0x100000; break;
421  case ARM::BI__builtin_neon_vrsra_n_v: mask = 0xF0F; break;
422  case ARM::BI__builtin_neon_vrsraq_n_v: mask = 0xF0F0000; break;
423  case ARM::BI__builtin_neon_vrsubhn_v: mask = 0x707; break;
424  case ARM::BI__builtin_neon_vshl_v: mask = 0xF0F; break;
425  case ARM::BI__builtin_neon_vshlq_v: mask = 0xF0F0000; break;
426  case ARM::BI__builtin_neon_vshll_n_v: mask = 0xE0E0000; break;
427  case ARM::BI__builtin_neon_vshl_n_v: mask = 0xF0F; break;
428  case ARM::BI__builtin_neon_vshlq_n_v: mask = 0xF0F0000; break;
429  case ARM::BI__builtin_neon_vshrn_n_v: mask = 0x707; break;
430  case ARM::BI__builtin_neon_vshr_n_v: mask = 0xF0F; break;
431  case ARM::BI__builtin_neon_vshrq_n_v: mask = 0xF0F0000; break;
432  case ARM::BI__builtin_neon_vsli_n_v: mask = 0xF6F; break;
433  case ARM::BI__builtin_neon_vsliq_n_v: mask = 0xF6F0000; break;
434  case ARM::BI__builtin_neon_vsra_n_v: mask = 0xF0F; break;
435  case ARM::BI__builtin_neon_vsraq_n_v: mask = 0xF0F0000; break;
436  case ARM::BI__builtin_neon_vsri_n_v: mask = 0xF6F; break;
437  case ARM::BI__builtin_neon_vsriq_n_v: mask = 0xF6F0000; break;
438  case ARM::BI__builtin_neon_vst1_v: mask = 0x9F; break;
439  case ARM::BI__builtin_neon_vst1q_v: mask = 0x9F0000; break;
440  case ARM::BI__builtin_neon_vst1_lane_v: mask = 0x9F; break;
441  case ARM::BI__builtin_neon_vst1q_lane_v: mask = 0x9F0000; break;
442  case ARM::BI__builtin_neon_vst2_v: mask = 0x9F; break;
443  case ARM::BI__builtin_neon_vst2q_v: mask = 0x970000; break;
444  case ARM::BI__builtin_neon_vst2_lane_v: mask = 0x97; break;
445  case ARM::BI__builtin_neon_vst2q_lane_v: mask = 0x960000; break;
446  case ARM::BI__builtin_neon_vst3_v: mask = 0x9F; break;
447  case ARM::BI__builtin_neon_vst3q_v: mask = 0x970000; break;
448  case ARM::BI__builtin_neon_vst3_lane_v: mask = 0x97; break;
449  case ARM::BI__builtin_neon_vst3q_lane_v: mask = 0x960000; break;
450  case ARM::BI__builtin_neon_vst4_v: mask = 0x9F; break;
451  case ARM::BI__builtin_neon_vst4q_v: mask = 0x970000; break;
452  case ARM::BI__builtin_neon_vst4_lane_v: mask = 0x97; break;
453  case ARM::BI__builtin_neon_vst4q_lane_v: mask = 0x960000; break;
454  case ARM::BI__builtin_neon_vsubhn_v: mask = 0x707; break;
455  case ARM::BI__builtin_neon_vsubl_v: mask = 0xE0E0000; break;
456  case ARM::BI__builtin_neon_vsubw_v: mask = 0xE0E0000; break;
457  case ARM::BI__builtin_neon_vtbl1_v: mask = 0x121; break;
458  case ARM::BI__builtin_neon_vtbl2_v: mask = 0x121; break;
459  case ARM::BI__builtin_neon_vtbl3_v: mask = 0x121; break;
460  case ARM::BI__builtin_neon_vtbl4_v: mask = 0x121; break;
461  case ARM::BI__builtin_neon_vtbx1_v: mask = 0x121; break;
462  case ARM::BI__builtin_neon_vtbx2_v: mask = 0x121; break;
463  case ARM::BI__builtin_neon_vtbx3_v: mask = 0x121; break;
464  case ARM::BI__builtin_neon_vtbx4_v: mask = 0x121; break;
465  case ARM::BI__builtin_neon_vtrn_v: mask = 0x777; break;
466  case ARM::BI__builtin_neon_vtrnq_v: mask = 0x7770000; break;
467  case ARM::BI__builtin_neon_vtst_v: mask = 0x700; break;
468  case ARM::BI__builtin_neon_vtstq_v: mask = 0x7000000; break;
469  case ARM::BI__builtin_neon_vuzp_v: mask = 0x777; break;
470  case ARM::BI__builtin_neon_vuzpq_v: mask = 0x7770000; break;
471  case ARM::BI__builtin_neon_vzip_v: mask = 0x373; break;
472  case ARM::BI__builtin_neon_vzipq_v: mask = 0x7770000; break;
473  }
474
475  // For NEON intrinsics which are overloaded on vector element type, validate
476  // the immediate which specifies which variant to emit.
477  if (mask) {
478    unsigned ArgNo = TheCall->getNumArgs()-1;
479    if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
480      return true;
481
482    TV = Result.getLimitedValue(32);
483    if ((TV > 31) || (mask & (1 << TV)) == 0)
484      return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
485        << TheCall->getArg(ArgNo)->getSourceRange();
486  }
487
488  // For NEON intrinsics which take an immediate value as part of the
489  // instruction, range check them here.
490  unsigned i = 0, l = 0, u = 0;
491  switch (BuiltinID) {
492  default: return false;
493  case ARM::BI__builtin_neon_vcvt_n_f32_v: i = 1; u = RFT(TV); break;
494  case ARM::BI__builtin_neon_vcvtq_n_f32_v: i = 1; u = RFT(TV); break;
495  case ARM::BI__builtin_neon_vcvt_n_s32_v: i = 1; u = RFT(TV); break;
496  case ARM::BI__builtin_neon_vcvtq_n_s32_v: i = 1; u = RFT(TV); break;
497  case ARM::BI__builtin_neon_vcvt_n_u32_v: i = 1; u = RFT(TV); break;
498  case ARM::BI__builtin_neon_vcvtq_n_u32_v: i = 1; u = RFT(TV); break;
499  case ARM::BI__builtin_neon_vext_v: i = 2; u = RFT(TV); break;
500  case ARM::BI__builtin_neon_vextq_v: i = 2; u = RFT(TV); break;
501  case ARM::BI__builtin_neon_vget_lane_i8: i = 1; u = 7; break;
502  case ARM::BI__builtin_neon_vget_lane_i16: i = 1; u = 3; break;
503  case ARM::BI__builtin_neon_vget_lane_i32: i = 1; u = 1; break;
504  case ARM::BI__builtin_neon_vget_lane_f32: i = 1; u = 1; break;
505  case ARM::BI__builtin_neon_vgetq_lane_i8: i = 1; u = 15; break;
506  case ARM::BI__builtin_neon_vgetq_lane_i16: i = 1; u = 7; break;
507  case ARM::BI__builtin_neon_vgetq_lane_i32: i = 1; u = 3; break;
508  case ARM::BI__builtin_neon_vgetq_lane_f32: i = 1; u = 3; break;
509  case ARM::BI__builtin_neon_vget_lane_i64: i = 1; u = 0; break;
510  case ARM::BI__builtin_neon_vgetq_lane_i64: i = 1; u = 1; break;
511  case ARM::BI__builtin_neon_vld1q_lane_v: i = 1; u = RFT(TV); break;
512  case ARM::BI__builtin_neon_vld1_lane_v: i = 1; u = RFT(TV); break;
513  case ARM::BI__builtin_neon_vld2q_lane_v: i = 1; u = RFT(TV); break;
514  case ARM::BI__builtin_neon_vld2_lane_v: i = 1; u = RFT(TV); break;
515  case ARM::BI__builtin_neon_vld3q_lane_v: i = 1; u = RFT(TV); break;
516  case ARM::BI__builtin_neon_vld3_lane_v: i = 1; u = RFT(TV); break;
517  case ARM::BI__builtin_neon_vld4q_lane_v: i = 1; u = RFT(TV); break;
518  case ARM::BI__builtin_neon_vld4_lane_v: i = 1; u = RFT(TV); break;
519  case ARM::BI__builtin_neon_vmlal_lane_v: i = 3; u = RFT(TV); break;
520  case ARM::BI__builtin_neon_vmla_lane_v: i = 3; u = RFT(TV); break;
521  case ARM::BI__builtin_neon_vmlaq_lane_v: i = 3; u = RFT(TV); break;
522  case ARM::BI__builtin_neon_vmlsl_lane_v: i = 3; u = RFT(TV); break;
523  case ARM::BI__builtin_neon_vmls_lane_v: i = 3; u = RFT(TV); break;
524  case ARM::BI__builtin_neon_vmlsq_lane_v: i = 3; u = RFT(TV); break;
525  case ARM::BI__builtin_neon_vmull_lane_v: i = 2; u = RFT(TV); break;
526  case ARM::BI__builtin_neon_vqdmlal_lane_v: i = 3; u = RFT(TV); break;
527  case ARM::BI__builtin_neon_vqdmlsl_lane_v: i = 3; u = RFT(TV); break;
528  case ARM::BI__builtin_neon_vqdmulh_lane_v: i = 2; u = RFT(TV); break;
529  case ARM::BI__builtin_neon_vqdmulhq_lane_v: i = 2; u = RFT(TV); break;
530  case ARM::BI__builtin_neon_vqdmull_lane_v: i = 2; u = RFT(TV); break;
531  case ARM::BI__builtin_neon_vqrdmulh_lane_v: i = 2; u = RFT(TV); break;
532  case ARM::BI__builtin_neon_vqrdmulhq_lane_v: i = 2; u = RFT(TV); break;
533  case ARM::BI__builtin_neon_vqrshrn_n_v: i = 1; l = 1; u = RFT(TV, true); break;
534  case ARM::BI__builtin_neon_vqrshrun_n_v: i = 1; l = 1; u = RFT(TV, true); break;
535  case ARM::BI__builtin_neon_vqshlu_n_v: i = 1; u = RFT(TV, true); break;
536  case ARM::BI__builtin_neon_vqshluq_n_v: i = 1; u = RFT(TV, true); break;
537  case ARM::BI__builtin_neon_vqshl_n_v: i = 1; u = RFT(TV, true); break;
538  case ARM::BI__builtin_neon_vqshlq_n_v: i = 1; u = RFT(TV, true); break;
539  case ARM::BI__builtin_neon_vqshrn_n_v: i = 1; l = 1; u = RFT(TV, true); break;
540  case ARM::BI__builtin_neon_vqshrun_n_v: i = 1; l = 1; u = RFT(TV, true); break;
541  case ARM::BI__builtin_neon_vrshrn_n_v: i = 1; l = 1; u = RFT(TV, true); break;
542  case ARM::BI__builtin_neon_vrshr_n_v: i = 1; l = 1; u = RFT(TV, true); break;
543  case ARM::BI__builtin_neon_vrshrq_n_v: i = 1; l = 1; u = RFT(TV, true); break;
544  case ARM::BI__builtin_neon_vrsra_n_v: i = 2; l = 1; u = RFT(TV, true); break;
545  case ARM::BI__builtin_neon_vrsraq_n_v: i = 2; l = 1; u = RFT(TV, true); break;
546  case ARM::BI__builtin_neon_vset_lane_i8: i = 2; u = 7; break;
547  case ARM::BI__builtin_neon_vset_lane_i16: i = 2; u = 3; break;
548  case ARM::BI__builtin_neon_vset_lane_i32: i = 2; u = 1; break;
549  case ARM::BI__builtin_neon_vset_lane_f32: i = 2; u = 1; break;
550  case ARM::BI__builtin_neon_vsetq_lane_i8: i = 2; u = 15; break;
551  case ARM::BI__builtin_neon_vsetq_lane_i16: i = 2; u = 7; break;
552  case ARM::BI__builtin_neon_vsetq_lane_i32: i = 2; u = 3; break;
553  case ARM::BI__builtin_neon_vsetq_lane_f32: i = 2; u = 3; break;
554  case ARM::BI__builtin_neon_vset_lane_i64: i = 2; u = 0; break;
555  case ARM::BI__builtin_neon_vsetq_lane_i64: i = 2; u = 1; break;
556  case ARM::BI__builtin_neon_vshll_n_v: i = 1; u = RFT(TV, true); break;
557  case ARM::BI__builtin_neon_vshl_n_v: i = 1; u = RFT(TV, true); break;
558  case ARM::BI__builtin_neon_vshlq_n_v: i = 1; u = RFT(TV, true); break;
559  case ARM::BI__builtin_neon_vshrn_n_v: i = 1; l = 1; u = RFT(TV, true); break;
560  case ARM::BI__builtin_neon_vshr_n_v: i = 1; l = 1; u = RFT(TV, true); break;
561  case ARM::BI__builtin_neon_vshrq_n_v: i = 1; l = 1; u = RFT(TV, true); break;
562  case ARM::BI__builtin_neon_vsli_n_v: i = 2; u = RFT(TV, true); break;
563  case ARM::BI__builtin_neon_vsliq_n_v: i = 2; u = RFT(TV, true); break;
564  case ARM::BI__builtin_neon_vsra_n_v: i = 2; l = 1; u = RFT(TV, true); break;
565  case ARM::BI__builtin_neon_vsraq_n_v: i = 2; l = 1; u = RFT(TV, true); break;
566  case ARM::BI__builtin_neon_vsri_n_v: i = 2; l = 1; u = RFT(TV, true); break;
567  case ARM::BI__builtin_neon_vsriq_n_v: i = 2; l = 1; u = RFT(TV, true); break;
568  case ARM::BI__builtin_neon_vst1q_lane_v: i = 2; u = RFT(TV); break;
569  case ARM::BI__builtin_neon_vst1_lane_v: i = 2; u = RFT(TV); break;
570  case ARM::BI__builtin_neon_vst2q_lane_v: i = 2; u = RFT(TV); break;
571  case ARM::BI__builtin_neon_vst2_lane_v: i = 2; u = RFT(TV); break;
572  case ARM::BI__builtin_neon_vst3q_lane_v: i = 2; u = RFT(TV); break;
573  case ARM::BI__builtin_neon_vst3_lane_v: i = 2; u = RFT(TV); break;
574  case ARM::BI__builtin_neon_vst4q_lane_v: i = 2; u = RFT(TV); break;
575  case ARM::BI__builtin_neon_vst4_lane_v: i = 2; u = RFT(TV); break;
576  };
577
578  // Check that the immediate argument is actually a constant.
579  if (SemaBuiltinConstantArg(TheCall, i, Result))
580    return true;
581
582  // Range check against the upper/lower values for this isntruction.
583  unsigned Val = Result.getZExtValue();
584  if (Val < l || Val > (u + l))
585    return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
586      << llvm::utostr(l) << llvm::utostr(u+l)
587      << TheCall->getArg(i)->getSourceRange();
588
589  return false;
590}
591
592/// CheckFunctionCall - Check a direct function call for various correctness
593/// and safety properties not strictly enforced by the C type system.
594bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
595  // Get the IdentifierInfo* for the called function.
596  IdentifierInfo *FnInfo = FDecl->getIdentifier();
597
598  // None of the checks below are needed for functions that don't have
599  // simple names (e.g., C++ conversion functions).
600  if (!FnInfo)
601    return false;
602
603  // FIXME: This mechanism should be abstracted to be less fragile and
604  // more efficient. For example, just map function ids to custom
605  // handlers.
606
607  // Printf checking.
608  if (const FormatAttr *Format = FDecl->getAttr<FormatAttr>()) {
609    if (CheckablePrintfAttr(Format, TheCall)) {
610      bool HasVAListArg = Format->getFirstArg() == 0;
611      CheckPrintfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
612                           HasVAListArg ? 0 : Format->getFirstArg() - 1);
613    }
614  }
615
616  for (const NonNullAttr *NonNull = FDecl->getAttr<NonNullAttr>(); NonNull;
617       NonNull = NonNull->getNext<NonNullAttr>())
618    CheckNonNullArguments(NonNull, TheCall);
619
620  return false;
621}
622
623bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
624  // Printf checking.
625  const FormatAttr *Format = NDecl->getAttr<FormatAttr>();
626  if (!Format)
627    return false;
628
629  const VarDecl *V = dyn_cast<VarDecl>(NDecl);
630  if (!V)
631    return false;
632
633  QualType Ty = V->getType();
634  if (!Ty->isBlockPointerType())
635    return false;
636
637  if (!CheckablePrintfAttr(Format, TheCall))
638    return false;
639
640  bool HasVAListArg = Format->getFirstArg() == 0;
641  CheckPrintfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
642                       HasVAListArg ? 0 : Format->getFirstArg() - 1);
643
644  return false;
645}
646
647/// SemaBuiltinAtomicOverloaded - We have a call to a function like
648/// __sync_fetch_and_add, which is an overloaded function based on the pointer
649/// type of its first argument.  The main ActOnCallExpr routines have already
650/// promoted the types of arguments because all of these calls are prototyped as
651/// void(...).
652///
653/// This function goes through and does final semantic checking for these
654/// builtins,
655bool Sema::SemaBuiltinAtomicOverloaded(CallExpr *TheCall) {
656  DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
657  FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
658
659  // Ensure that we have at least one argument to do type inference from.
660  if (TheCall->getNumArgs() < 1)
661    return Diag(TheCall->getLocEnd(),
662              diag::err_typecheck_call_too_few_args_at_least)
663              << 0 << 1 << TheCall->getNumArgs()
664              << TheCall->getCallee()->getSourceRange();
665
666  // Inspect the first argument of the atomic builtin.  This should always be
667  // a pointer type, whose element is an integral scalar or pointer type.
668  // Because it is a pointer type, we don't have to worry about any implicit
669  // casts here.
670  Expr *FirstArg = TheCall->getArg(0);
671  if (!FirstArg->getType()->isPointerType())
672    return Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
673             << FirstArg->getType() << FirstArg->getSourceRange();
674
675  QualType ValType = FirstArg->getType()->getAs<PointerType>()->getPointeeType();
676  if (!ValType->isIntegerType() && !ValType->isPointerType() &&
677      !ValType->isBlockPointerType())
678    return Diag(DRE->getLocStart(),
679                diag::err_atomic_builtin_must_be_pointer_intptr)
680             << FirstArg->getType() << FirstArg->getSourceRange();
681
682  // We need to figure out which concrete builtin this maps onto.  For example,
683  // __sync_fetch_and_add with a 2 byte object turns into
684  // __sync_fetch_and_add_2.
685#define BUILTIN_ROW(x) \
686  { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
687    Builtin::BI##x##_8, Builtin::BI##x##_16 }
688
689  static const unsigned BuiltinIndices[][5] = {
690    BUILTIN_ROW(__sync_fetch_and_add),
691    BUILTIN_ROW(__sync_fetch_and_sub),
692    BUILTIN_ROW(__sync_fetch_and_or),
693    BUILTIN_ROW(__sync_fetch_and_and),
694    BUILTIN_ROW(__sync_fetch_and_xor),
695
696    BUILTIN_ROW(__sync_add_and_fetch),
697    BUILTIN_ROW(__sync_sub_and_fetch),
698    BUILTIN_ROW(__sync_and_and_fetch),
699    BUILTIN_ROW(__sync_or_and_fetch),
700    BUILTIN_ROW(__sync_xor_and_fetch),
701
702    BUILTIN_ROW(__sync_val_compare_and_swap),
703    BUILTIN_ROW(__sync_bool_compare_and_swap),
704    BUILTIN_ROW(__sync_lock_test_and_set),
705    BUILTIN_ROW(__sync_lock_release)
706  };
707#undef BUILTIN_ROW
708
709  // Determine the index of the size.
710  unsigned SizeIndex;
711  switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
712  case 1: SizeIndex = 0; break;
713  case 2: SizeIndex = 1; break;
714  case 4: SizeIndex = 2; break;
715  case 8: SizeIndex = 3; break;
716  case 16: SizeIndex = 4; break;
717  default:
718    return Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
719             << FirstArg->getType() << FirstArg->getSourceRange();
720  }
721
722  // Each of these builtins has one pointer argument, followed by some number of
723  // values (0, 1 or 2) followed by a potentially empty varags list of stuff
724  // that we ignore.  Find out which row of BuiltinIndices to read from as well
725  // as the number of fixed args.
726  unsigned BuiltinID = FDecl->getBuiltinID();
727  unsigned BuiltinIndex, NumFixed = 1;
728  switch (BuiltinID) {
729  default: assert(0 && "Unknown overloaded atomic builtin!");
730  case Builtin::BI__sync_fetch_and_add: BuiltinIndex = 0; break;
731  case Builtin::BI__sync_fetch_and_sub: BuiltinIndex = 1; break;
732  case Builtin::BI__sync_fetch_and_or:  BuiltinIndex = 2; break;
733  case Builtin::BI__sync_fetch_and_and: BuiltinIndex = 3; break;
734  case Builtin::BI__sync_fetch_and_xor: BuiltinIndex = 4; break;
735
736  case Builtin::BI__sync_add_and_fetch: BuiltinIndex = 5; break;
737  case Builtin::BI__sync_sub_and_fetch: BuiltinIndex = 6; break;
738  case Builtin::BI__sync_and_and_fetch: BuiltinIndex = 7; break;
739  case Builtin::BI__sync_or_and_fetch:  BuiltinIndex = 8; break;
740  case Builtin::BI__sync_xor_and_fetch: BuiltinIndex = 9; break;
741
742  case Builtin::BI__sync_val_compare_and_swap:
743    BuiltinIndex = 10;
744    NumFixed = 2;
745    break;
746  case Builtin::BI__sync_bool_compare_and_swap:
747    BuiltinIndex = 11;
748    NumFixed = 2;
749    break;
750  case Builtin::BI__sync_lock_test_and_set: BuiltinIndex = 12; break;
751  case Builtin::BI__sync_lock_release:
752    BuiltinIndex = 13;
753    NumFixed = 0;
754    break;
755  }
756
757  // Now that we know how many fixed arguments we expect, first check that we
758  // have at least that many.
759  if (TheCall->getNumArgs() < 1+NumFixed)
760    return Diag(TheCall->getLocEnd(),
761            diag::err_typecheck_call_too_few_args_at_least)
762            << 0 << 1+NumFixed << TheCall->getNumArgs()
763            << TheCall->getCallee()->getSourceRange();
764
765
766  // Get the decl for the concrete builtin from this, we can tell what the
767  // concrete integer type we should convert to is.
768  unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
769  const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
770  IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
771  FunctionDecl *NewBuiltinDecl =
772    cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
773                                           TUScope, false, DRE->getLocStart()));
774  const FunctionProtoType *BuiltinFT =
775    NewBuiltinDecl->getType()->getAs<FunctionProtoType>();
776  ValType = BuiltinFT->getArgType(0)->getAs<PointerType>()->getPointeeType();
777
778  // If the first type needs to be converted (e.g. void** -> int*), do it now.
779  if (BuiltinFT->getArgType(0) != FirstArg->getType()) {
780    ImpCastExprToType(FirstArg, BuiltinFT->getArgType(0), CastExpr::CK_BitCast);
781    TheCall->setArg(0, FirstArg);
782  }
783
784  // Next, walk the valid ones promoting to the right type.
785  for (unsigned i = 0; i != NumFixed; ++i) {
786    Expr *Arg = TheCall->getArg(i+1);
787
788    // If the argument is an implicit cast, then there was a promotion due to
789    // "...", just remove it now.
790    if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
791      Arg = ICE->getSubExpr();
792      ICE->setSubExpr(0);
793      ICE->Destroy(Context);
794      TheCall->setArg(i+1, Arg);
795    }
796
797    // GCC does an implicit conversion to the pointer or integer ValType.  This
798    // can fail in some cases (1i -> int**), check for this error case now.
799    CastExpr::CastKind Kind = CastExpr::CK_Unknown;
800    CXXBaseSpecifierArray BasePath;
801    if (CheckCastTypes(Arg->getSourceRange(), ValType, Arg, Kind, BasePath))
802      return true;
803
804    // Okay, we have something that *can* be converted to the right type.  Check
805    // to see if there is a potentially weird extension going on here.  This can
806    // happen when you do an atomic operation on something like an char* and
807    // pass in 42.  The 42 gets converted to char.  This is even more strange
808    // for things like 45.123 -> char, etc.
809    // FIXME: Do this check.
810    ImpCastExprToType(Arg, ValType, Kind);
811    TheCall->setArg(i+1, Arg);
812  }
813
814  // Switch the DeclRefExpr to refer to the new decl.
815  DRE->setDecl(NewBuiltinDecl);
816  DRE->setType(NewBuiltinDecl->getType());
817
818  // Set the callee in the CallExpr.
819  // FIXME: This leaks the original parens and implicit casts.
820  Expr *PromotedCall = DRE;
821  UsualUnaryConversions(PromotedCall);
822  TheCall->setCallee(PromotedCall);
823
824
825  // Change the result type of the call to match the result type of the decl.
826  TheCall->setType(NewBuiltinDecl->getResultType());
827  return false;
828}
829
830
831/// CheckObjCString - Checks that the argument to the builtin
832/// CFString constructor is correct
833/// FIXME: GCC currently emits the following warning:
834/// "warning: input conversion stopped due to an input byte that does not
835///           belong to the input codeset UTF-8"
836/// Note: It might also make sense to do the UTF-16 conversion here (would
837/// simplify the backend).
838bool Sema::CheckObjCString(Expr *Arg) {
839  Arg = Arg->IgnoreParenCasts();
840  StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
841
842  if (!Literal || Literal->isWide()) {
843    Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
844      << Arg->getSourceRange();
845    return true;
846  }
847
848  const char *Data = Literal->getStrData();
849  unsigned Length = Literal->getByteLength();
850
851  for (unsigned i = 0; i < Length; ++i) {
852    if (!Data[i]) {
853      Diag(getLocationOfStringLiteralByte(Literal, i),
854           diag::warn_cfstring_literal_contains_nul_character)
855        << Arg->getSourceRange();
856      break;
857    }
858  }
859
860  return false;
861}
862
863/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
864/// Emit an error and return true on failure, return false on success.
865bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
866  Expr *Fn = TheCall->getCallee();
867  if (TheCall->getNumArgs() > 2) {
868    Diag(TheCall->getArg(2)->getLocStart(),
869         diag::err_typecheck_call_too_many_args)
870      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
871      << Fn->getSourceRange()
872      << SourceRange(TheCall->getArg(2)->getLocStart(),
873                     (*(TheCall->arg_end()-1))->getLocEnd());
874    return true;
875  }
876
877  if (TheCall->getNumArgs() < 2) {
878    return Diag(TheCall->getLocEnd(),
879      diag::err_typecheck_call_too_few_args_at_least)
880      << 0 /*function call*/ << 2 << TheCall->getNumArgs();
881  }
882
883  // Determine whether the current function is variadic or not.
884  BlockScopeInfo *CurBlock = getCurBlock();
885  bool isVariadic;
886  if (CurBlock)
887    isVariadic = CurBlock->TheDecl->isVariadic();
888  else if (FunctionDecl *FD = getCurFunctionDecl())
889    isVariadic = FD->isVariadic();
890  else
891    isVariadic = getCurMethodDecl()->isVariadic();
892
893  if (!isVariadic) {
894    Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
895    return true;
896  }
897
898  // Verify that the second argument to the builtin is the last argument of the
899  // current function or method.
900  bool SecondArgIsLastNamedArgument = false;
901  const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
902
903  if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
904    if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
905      // FIXME: This isn't correct for methods (results in bogus warning).
906      // Get the last formal in the current function.
907      const ParmVarDecl *LastArg;
908      if (CurBlock)
909        LastArg = *(CurBlock->TheDecl->param_end()-1);
910      else if (FunctionDecl *FD = getCurFunctionDecl())
911        LastArg = *(FD->param_end()-1);
912      else
913        LastArg = *(getCurMethodDecl()->param_end()-1);
914      SecondArgIsLastNamedArgument = PV == LastArg;
915    }
916  }
917
918  if (!SecondArgIsLastNamedArgument)
919    Diag(TheCall->getArg(1)->getLocStart(),
920         diag::warn_second_parameter_of_va_start_not_last_named_argument);
921  return false;
922}
923
924/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
925/// friends.  This is declared to take (...), so we have to check everything.
926bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
927  if (TheCall->getNumArgs() < 2)
928    return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
929      << 0 << 2 << TheCall->getNumArgs()/*function call*/;
930  if (TheCall->getNumArgs() > 2)
931    return Diag(TheCall->getArg(2)->getLocStart(),
932                diag::err_typecheck_call_too_many_args)
933      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
934      << SourceRange(TheCall->getArg(2)->getLocStart(),
935                     (*(TheCall->arg_end()-1))->getLocEnd());
936
937  Expr *OrigArg0 = TheCall->getArg(0);
938  Expr *OrigArg1 = TheCall->getArg(1);
939
940  // Do standard promotions between the two arguments, returning their common
941  // type.
942  QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
943
944  // Make sure any conversions are pushed back into the call; this is
945  // type safe since unordered compare builtins are declared as "_Bool
946  // foo(...)".
947  TheCall->setArg(0, OrigArg0);
948  TheCall->setArg(1, OrigArg1);
949
950  if (OrigArg0->isTypeDependent() || OrigArg1->isTypeDependent())
951    return false;
952
953  // If the common type isn't a real floating type, then the arguments were
954  // invalid for this operation.
955  if (!Res->isRealFloatingType())
956    return Diag(OrigArg0->getLocStart(),
957                diag::err_typecheck_call_invalid_ordered_compare)
958      << OrigArg0->getType() << OrigArg1->getType()
959      << SourceRange(OrigArg0->getLocStart(), OrigArg1->getLocEnd());
960
961  return false;
962}
963
964/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
965/// __builtin_isnan and friends.  This is declared to take (...), so we have
966/// to check everything. We expect the last argument to be a floating point
967/// value.
968bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
969  if (TheCall->getNumArgs() < NumArgs)
970    return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
971      << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
972  if (TheCall->getNumArgs() > NumArgs)
973    return Diag(TheCall->getArg(NumArgs)->getLocStart(),
974                diag::err_typecheck_call_too_many_args)
975      << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
976      << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
977                     (*(TheCall->arg_end()-1))->getLocEnd());
978
979  Expr *OrigArg = TheCall->getArg(NumArgs-1);
980
981  if (OrigArg->isTypeDependent())
982    return false;
983
984  // This operation requires a non-_Complex floating-point number.
985  if (!OrigArg->getType()->isRealFloatingType())
986    return Diag(OrigArg->getLocStart(),
987                diag::err_typecheck_call_invalid_unary_fp)
988      << OrigArg->getType() << OrigArg->getSourceRange();
989
990  // If this is an implicit conversion from float -> double, remove it.
991  if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
992    Expr *CastArg = Cast->getSubExpr();
993    if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
994      assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
995             "promotion from float to double is the only expected cast here");
996      Cast->setSubExpr(0);
997      Cast->Destroy(Context);
998      TheCall->setArg(NumArgs-1, CastArg);
999      OrigArg = CastArg;
1000    }
1001  }
1002
1003  return false;
1004}
1005
1006/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1007// This is declared to take (...), so we have to check everything.
1008Action::OwningExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
1009  if (TheCall->getNumArgs() < 2)
1010    return ExprError(Diag(TheCall->getLocEnd(),
1011                          diag::err_typecheck_call_too_few_args_at_least)
1012      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1013      << TheCall->getSourceRange());
1014
1015  // Determine which of the following types of shufflevector we're checking:
1016  // 1) unary, vector mask: (lhs, mask)
1017  // 2) binary, vector mask: (lhs, rhs, mask)
1018  // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1019  QualType resType = TheCall->getArg(0)->getType();
1020  unsigned numElements = 0;
1021
1022  if (!TheCall->getArg(0)->isTypeDependent() &&
1023      !TheCall->getArg(1)->isTypeDependent()) {
1024    QualType LHSType = TheCall->getArg(0)->getType();
1025    QualType RHSType = TheCall->getArg(1)->getType();
1026
1027    if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
1028      Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
1029        << SourceRange(TheCall->getArg(0)->getLocStart(),
1030                       TheCall->getArg(1)->getLocEnd());
1031      return ExprError();
1032    }
1033
1034    numElements = LHSType->getAs<VectorType>()->getNumElements();
1035    unsigned numResElements = TheCall->getNumArgs() - 2;
1036
1037    // Check to see if we have a call with 2 vector arguments, the unary shuffle
1038    // with mask.  If so, verify that RHS is an integer vector type with the
1039    // same number of elts as lhs.
1040    if (TheCall->getNumArgs() == 2) {
1041      if (!RHSType->isIntegerType() ||
1042          RHSType->getAs<VectorType>()->getNumElements() != numElements)
1043        Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
1044          << SourceRange(TheCall->getArg(1)->getLocStart(),
1045                         TheCall->getArg(1)->getLocEnd());
1046      numResElements = numElements;
1047    }
1048    else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
1049      Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
1050        << SourceRange(TheCall->getArg(0)->getLocStart(),
1051                       TheCall->getArg(1)->getLocEnd());
1052      return ExprError();
1053    } else if (numElements != numResElements) {
1054      QualType eltType = LHSType->getAs<VectorType>()->getElementType();
1055      resType = Context.getVectorType(eltType, numResElements, false, false);
1056    }
1057  }
1058
1059  for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
1060    if (TheCall->getArg(i)->isTypeDependent() ||
1061        TheCall->getArg(i)->isValueDependent())
1062      continue;
1063
1064    llvm::APSInt Result(32);
1065    if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1066      return ExprError(Diag(TheCall->getLocStart(),
1067                  diag::err_shufflevector_nonconstant_argument)
1068                << TheCall->getArg(i)->getSourceRange());
1069
1070    if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
1071      return ExprError(Diag(TheCall->getLocStart(),
1072                  diag::err_shufflevector_argument_too_large)
1073               << TheCall->getArg(i)->getSourceRange());
1074  }
1075
1076  llvm::SmallVector<Expr*, 32> exprs;
1077
1078  for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
1079    exprs.push_back(TheCall->getArg(i));
1080    TheCall->setArg(i, 0);
1081  }
1082
1083  return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
1084                                            exprs.size(), resType,
1085                                            TheCall->getCallee()->getLocStart(),
1086                                            TheCall->getRParenLoc()));
1087}
1088
1089/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1090// This is declared to take (const void*, ...) and can take two
1091// optional constant int args.
1092bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
1093  unsigned NumArgs = TheCall->getNumArgs();
1094
1095  if (NumArgs > 3)
1096    return Diag(TheCall->getLocEnd(),
1097             diag::err_typecheck_call_too_many_args_at_most)
1098             << 0 /*function call*/ << 3 << NumArgs
1099             << TheCall->getSourceRange();
1100
1101  // Argument 0 is checked for us and the remaining arguments must be
1102  // constant integers.
1103  for (unsigned i = 1; i != NumArgs; ++i) {
1104    Expr *Arg = TheCall->getArg(i);
1105
1106    llvm::APSInt Result;
1107    if (SemaBuiltinConstantArg(TheCall, i, Result))
1108      return true;
1109
1110    // FIXME: gcc issues a warning and rewrites these to 0. These
1111    // seems especially odd for the third argument since the default
1112    // is 3.
1113    if (i == 1) {
1114      if (Result.getLimitedValue() > 1)
1115        return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1116             << "0" << "1" << Arg->getSourceRange();
1117    } else {
1118      if (Result.getLimitedValue() > 3)
1119        return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1120            << "0" << "3" << Arg->getSourceRange();
1121    }
1122  }
1123
1124  return false;
1125}
1126
1127/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1128/// TheCall is a constant expression.
1129bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1130                                  llvm::APSInt &Result) {
1131  Expr *Arg = TheCall->getArg(ArgNum);
1132  DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1133  FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1134
1135  if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1136
1137  if (!Arg->isIntegerConstantExpr(Result, Context))
1138    return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
1139                << FDecl->getDeclName() <<  Arg->getSourceRange();
1140
1141  return false;
1142}
1143
1144/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1145/// int type). This simply type checks that type is one of the defined
1146/// constants (0-3).
1147// For compatability check 0-3, llvm only handles 0 and 2.
1148bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
1149  llvm::APSInt Result;
1150
1151  // Check constant-ness first.
1152  if (SemaBuiltinConstantArg(TheCall, 1, Result))
1153    return true;
1154
1155  Expr *Arg = TheCall->getArg(1);
1156  if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
1157    return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1158             << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1159  }
1160
1161  return false;
1162}
1163
1164/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
1165/// This checks that val is a constant 1.
1166bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1167  Expr *Arg = TheCall->getArg(1);
1168  llvm::APSInt Result;
1169
1170  // TODO: This is less than ideal. Overload this to take a value.
1171  if (SemaBuiltinConstantArg(TheCall, 1, Result))
1172    return true;
1173
1174  if (Result != 1)
1175    return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
1176             << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1177
1178  return false;
1179}
1180
1181// Handle i > 1 ? "x" : "y", recursivelly
1182bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
1183                                  bool HasVAListArg,
1184                                  unsigned format_idx, unsigned firstDataArg) {
1185  if (E->isTypeDependent() || E->isValueDependent())
1186    return false;
1187
1188  switch (E->getStmtClass()) {
1189  case Stmt::ConditionalOperatorClass: {
1190    const ConditionalOperator *C = cast<ConditionalOperator>(E);
1191    return SemaCheckStringLiteral(C->getTrueExpr(), TheCall,
1192                                  HasVAListArg, format_idx, firstDataArg)
1193        && SemaCheckStringLiteral(C->getRHS(), TheCall,
1194                                  HasVAListArg, format_idx, firstDataArg);
1195  }
1196
1197  case Stmt::ImplicitCastExprClass: {
1198    const ImplicitCastExpr *Expr = cast<ImplicitCastExpr>(E);
1199    return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
1200                                  format_idx, firstDataArg);
1201  }
1202
1203  case Stmt::ParenExprClass: {
1204    const ParenExpr *Expr = cast<ParenExpr>(E);
1205    return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
1206                                  format_idx, firstDataArg);
1207  }
1208
1209  case Stmt::DeclRefExprClass: {
1210    const DeclRefExpr *DR = cast<DeclRefExpr>(E);
1211
1212    // As an exception, do not flag errors for variables binding to
1213    // const string literals.
1214    if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1215      bool isConstant = false;
1216      QualType T = DR->getType();
1217
1218      if (const ArrayType *AT = Context.getAsArrayType(T)) {
1219        isConstant = AT->getElementType().isConstant(Context);
1220      } else if (const PointerType *PT = T->getAs<PointerType>()) {
1221        isConstant = T.isConstant(Context) &&
1222                     PT->getPointeeType().isConstant(Context);
1223      }
1224
1225      if (isConstant) {
1226        if (const Expr *Init = VD->getAnyInitializer())
1227          return SemaCheckStringLiteral(Init, TheCall,
1228                                        HasVAListArg, format_idx, firstDataArg);
1229      }
1230
1231      // For vprintf* functions (i.e., HasVAListArg==true), we add a
1232      // special check to see if the format string is a function parameter
1233      // of the function calling the printf function.  If the function
1234      // has an attribute indicating it is a printf-like function, then we
1235      // should suppress warnings concerning non-literals being used in a call
1236      // to a vprintf function.  For example:
1237      //
1238      // void
1239      // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
1240      //      va_list ap;
1241      //      va_start(ap, fmt);
1242      //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
1243      //      ...
1244      //
1245      //
1246      //  FIXME: We don't have full attribute support yet, so just check to see
1247      //    if the argument is a DeclRefExpr that references a parameter.  We'll
1248      //    add proper support for checking the attribute later.
1249      if (HasVAListArg)
1250        if (isa<ParmVarDecl>(VD))
1251          return true;
1252    }
1253
1254    return false;
1255  }
1256
1257  case Stmt::CallExprClass: {
1258    const CallExpr *CE = cast<CallExpr>(E);
1259    if (const ImplicitCastExpr *ICE
1260          = dyn_cast<ImplicitCastExpr>(CE->getCallee())) {
1261      if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) {
1262        if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
1263          if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) {
1264            unsigned ArgIndex = FA->getFormatIdx();
1265            const Expr *Arg = CE->getArg(ArgIndex - 1);
1266
1267            return SemaCheckStringLiteral(Arg, TheCall, HasVAListArg,
1268                                          format_idx, firstDataArg);
1269          }
1270        }
1271      }
1272    }
1273
1274    return false;
1275  }
1276  case Stmt::ObjCStringLiteralClass:
1277  case Stmt::StringLiteralClass: {
1278    const StringLiteral *StrE = NULL;
1279
1280    if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
1281      StrE = ObjCFExpr->getString();
1282    else
1283      StrE = cast<StringLiteral>(E);
1284
1285    if (StrE) {
1286      CheckPrintfString(StrE, E, TheCall, HasVAListArg, format_idx,
1287                        firstDataArg);
1288      return true;
1289    }
1290
1291    return false;
1292  }
1293
1294  default:
1295    return false;
1296  }
1297}
1298
1299void
1300Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
1301                            const CallExpr *TheCall) {
1302  for (NonNullAttr::iterator i = NonNull->begin(), e = NonNull->end();
1303       i != e; ++i) {
1304    const Expr *ArgExpr = TheCall->getArg(*i);
1305    if (ArgExpr->isNullPointerConstant(Context,
1306                                       Expr::NPC_ValueDependentIsNotNull))
1307      Diag(TheCall->getCallee()->getLocStart(), diag::warn_null_arg)
1308        << ArgExpr->getSourceRange();
1309  }
1310}
1311
1312/// CheckPrintfArguments - Check calls to printf (and similar functions) for
1313/// correct use of format strings.
1314///
1315///  HasVAListArg - A predicate indicating whether the printf-like
1316///    function is passed an explicit va_arg argument (e.g., vprintf)
1317///
1318///  format_idx - The index into Args for the format string.
1319///
1320/// Improper format strings to functions in the printf family can be
1321/// the source of bizarre bugs and very serious security holes.  A
1322/// good source of information is available in the following paper
1323/// (which includes additional references):
1324///
1325///  FormatGuard: Automatic Protection From printf Format String
1326///  Vulnerabilities, Proceedings of the 10th USENIX Security Symposium, 2001.
1327///
1328/// TODO:
1329/// Functionality implemented:
1330///
1331///  We can statically check the following properties for string
1332///  literal format strings for non v.*printf functions (where the
1333///  arguments are passed directly):
1334//
1335///  (1) Are the number of format conversions equal to the number of
1336///      data arguments?
1337///
1338///  (2) Does each format conversion correctly match the type of the
1339///      corresponding data argument?
1340///
1341/// Moreover, for all printf functions we can:
1342///
1343///  (3) Check for a missing format string (when not caught by type checking).
1344///
1345///  (4) Check for no-operation flags; e.g. using "#" with format
1346///      conversion 'c'  (TODO)
1347///
1348///  (5) Check the use of '%n', a major source of security holes.
1349///
1350///  (6) Check for malformed format conversions that don't specify anything.
1351///
1352///  (7) Check for empty format strings.  e.g: printf("");
1353///
1354///  (8) Check that the format string is a wide literal.
1355///
1356/// All of these checks can be done by parsing the format string.
1357///
1358void
1359Sema::CheckPrintfArguments(const CallExpr *TheCall, bool HasVAListArg,
1360                           unsigned format_idx, unsigned firstDataArg) {
1361  const Expr *Fn = TheCall->getCallee();
1362
1363  // The way the format attribute works in GCC, the implicit this argument
1364  // of member functions is counted. However, it doesn't appear in our own
1365  // lists, so decrement format_idx in that case.
1366  if (isa<CXXMemberCallExpr>(TheCall)) {
1367    // Catch a format attribute mistakenly referring to the object argument.
1368    if (format_idx == 0)
1369      return;
1370    --format_idx;
1371    if(firstDataArg != 0)
1372      --firstDataArg;
1373  }
1374
1375  // CHECK: printf-like function is called with no format string.
1376  if (format_idx >= TheCall->getNumArgs()) {
1377    Diag(TheCall->getRParenLoc(), diag::warn_printf_missing_format_string)
1378      << Fn->getSourceRange();
1379    return;
1380  }
1381
1382  const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
1383
1384  // CHECK: format string is not a string literal.
1385  //
1386  // Dynamically generated format strings are difficult to
1387  // automatically vet at compile time.  Requiring that format strings
1388  // are string literals: (1) permits the checking of format strings by
1389  // the compiler and thereby (2) can practically remove the source of
1390  // many format string exploits.
1391
1392  // Format string can be either ObjC string (e.g. @"%d") or
1393  // C string (e.g. "%d")
1394  // ObjC string uses the same format specifiers as C string, so we can use
1395  // the same format string checking logic for both ObjC and C strings.
1396  if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx,
1397                             firstDataArg))
1398    return;  // Literal format string found, check done!
1399
1400  // If there are no arguments specified, warn with -Wformat-security, otherwise
1401  // warn only with -Wformat-nonliteral.
1402  if (TheCall->getNumArgs() == format_idx+1)
1403    Diag(TheCall->getArg(format_idx)->getLocStart(),
1404         diag::warn_printf_nonliteral_noargs)
1405      << OrigFormatExpr->getSourceRange();
1406  else
1407    Diag(TheCall->getArg(format_idx)->getLocStart(),
1408         diag::warn_printf_nonliteral)
1409           << OrigFormatExpr->getSourceRange();
1410}
1411
1412namespace {
1413class CheckPrintfHandler : public analyze_printf::FormatStringHandler {
1414  Sema &S;
1415  const StringLiteral *FExpr;
1416  const Expr *OrigFormatExpr;
1417  const unsigned FirstDataArg;
1418  const unsigned NumDataArgs;
1419  const bool IsObjCLiteral;
1420  const char *Beg; // Start of format string.
1421  const bool HasVAListArg;
1422  const CallExpr *TheCall;
1423  unsigned FormatIdx;
1424  llvm::BitVector CoveredArgs;
1425  bool usesPositionalArgs;
1426  bool atFirstArg;
1427public:
1428  CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
1429                     const Expr *origFormatExpr, unsigned firstDataArg,
1430                     unsigned numDataArgs, bool isObjCLiteral,
1431                     const char *beg, bool hasVAListArg,
1432                     const CallExpr *theCall, unsigned formatIdx)
1433    : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
1434      FirstDataArg(firstDataArg),
1435      NumDataArgs(numDataArgs),
1436      IsObjCLiteral(isObjCLiteral), Beg(beg),
1437      HasVAListArg(hasVAListArg),
1438      TheCall(theCall), FormatIdx(formatIdx),
1439      usesPositionalArgs(false), atFirstArg(true) {
1440        CoveredArgs.resize(numDataArgs);
1441        CoveredArgs.reset();
1442      }
1443
1444  void DoneProcessing();
1445
1446  void HandleIncompleteFormatSpecifier(const char *startSpecifier,
1447                                       unsigned specifierLen);
1448
1449  bool
1450  HandleInvalidConversionSpecifier(const analyze_printf::FormatSpecifier &FS,
1451                                   const char *startSpecifier,
1452                                   unsigned specifierLen);
1453
1454  virtual void HandleInvalidPosition(const char *startSpecifier,
1455                                     unsigned specifierLen,
1456                                     analyze_printf::PositionContext p);
1457
1458  virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
1459
1460  void HandleNullChar(const char *nullCharacter);
1461
1462  bool HandleFormatSpecifier(const analyze_printf::FormatSpecifier &FS,
1463                             const char *startSpecifier,
1464                             unsigned specifierLen);
1465private:
1466  SourceRange getFormatStringRange();
1467  SourceRange getFormatSpecifierRange(const char *startSpecifier,
1468                                      unsigned specifierLen);
1469  SourceLocation getLocationOfByte(const char *x);
1470
1471  bool HandleAmount(const analyze_printf::OptionalAmount &Amt, unsigned k,
1472                    const char *startSpecifier, unsigned specifierLen);
1473  void HandleFlags(const analyze_printf::FormatSpecifier &FS,
1474                   llvm::StringRef flag, llvm::StringRef cspec,
1475                   const char *startSpecifier, unsigned specifierLen);
1476
1477  const Expr *getDataArg(unsigned i) const;
1478};
1479}
1480
1481SourceRange CheckPrintfHandler::getFormatStringRange() {
1482  return OrigFormatExpr->getSourceRange();
1483}
1484
1485SourceRange CheckPrintfHandler::
1486getFormatSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
1487  return SourceRange(getLocationOfByte(startSpecifier),
1488                     getLocationOfByte(startSpecifier+specifierLen-1));
1489}
1490
1491SourceLocation CheckPrintfHandler::getLocationOfByte(const char *x) {
1492  return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
1493}
1494
1495void CheckPrintfHandler::
1496HandleIncompleteFormatSpecifier(const char *startSpecifier,
1497                                unsigned specifierLen) {
1498  SourceLocation Loc = getLocationOfByte(startSpecifier);
1499  S.Diag(Loc, diag::warn_printf_incomplete_specifier)
1500    << getFormatSpecifierRange(startSpecifier, specifierLen);
1501}
1502
1503void
1504CheckPrintfHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
1505                                          analyze_printf::PositionContext p) {
1506  SourceLocation Loc = getLocationOfByte(startPos);
1507  S.Diag(Loc, diag::warn_printf_invalid_positional_specifier)
1508    << (unsigned) p << getFormatSpecifierRange(startPos, posLen);
1509}
1510
1511void CheckPrintfHandler::HandleZeroPosition(const char *startPos,
1512                                            unsigned posLen) {
1513  SourceLocation Loc = getLocationOfByte(startPos);
1514  S.Diag(Loc, diag::warn_printf_zero_positional_specifier)
1515    << getFormatSpecifierRange(startPos, posLen);
1516}
1517
1518bool CheckPrintfHandler::
1519HandleInvalidConversionSpecifier(const analyze_printf::FormatSpecifier &FS,
1520                                 const char *startSpecifier,
1521                                 unsigned specifierLen) {
1522
1523  unsigned argIndex = FS.getArgIndex();
1524  bool keepGoing = true;
1525  if (argIndex < NumDataArgs) {
1526    // Consider the argument coverered, even though the specifier doesn't
1527    // make sense.
1528    CoveredArgs.set(argIndex);
1529  }
1530  else {
1531    // If argIndex exceeds the number of data arguments we
1532    // don't issue a warning because that is just a cascade of warnings (and
1533    // they may have intended '%%' anyway). We don't want to continue processing
1534    // the format string after this point, however, as we will like just get
1535    // gibberish when trying to match arguments.
1536    keepGoing = false;
1537  }
1538
1539  const analyze_printf::ConversionSpecifier &CS =
1540    FS.getConversionSpecifier();
1541  SourceLocation Loc = getLocationOfByte(CS.getStart());
1542  S.Diag(Loc, diag::warn_printf_invalid_conversion)
1543      << llvm::StringRef(CS.getStart(), CS.getLength())
1544      << getFormatSpecifierRange(startSpecifier, specifierLen);
1545
1546  return keepGoing;
1547}
1548
1549void CheckPrintfHandler::HandleNullChar(const char *nullCharacter) {
1550  // The presence of a null character is likely an error.
1551  S.Diag(getLocationOfByte(nullCharacter),
1552         diag::warn_printf_format_string_contains_null_char)
1553    << getFormatStringRange();
1554}
1555
1556const Expr *CheckPrintfHandler::getDataArg(unsigned i) const {
1557  return TheCall->getArg(FirstDataArg + i);
1558}
1559
1560void CheckPrintfHandler::HandleFlags(const analyze_printf::FormatSpecifier &FS,
1561                                     llvm::StringRef flag,
1562                                     llvm::StringRef cspec,
1563                                     const char *startSpecifier,
1564                                     unsigned specifierLen) {
1565  const analyze_printf::ConversionSpecifier &CS = FS.getConversionSpecifier();
1566  S.Diag(getLocationOfByte(CS.getStart()), diag::warn_printf_nonsensical_flag)
1567    << flag << cspec << getFormatSpecifierRange(startSpecifier, specifierLen);
1568}
1569
1570bool
1571CheckPrintfHandler::HandleAmount(const analyze_printf::OptionalAmount &Amt,
1572                                 unsigned k, const char *startSpecifier,
1573                                 unsigned specifierLen) {
1574
1575  if (Amt.hasDataArgument()) {
1576    if (!HasVAListArg) {
1577      unsigned argIndex = Amt.getArgIndex();
1578      if (argIndex >= NumDataArgs) {
1579        S.Diag(getLocationOfByte(Amt.getStart()),
1580               diag::warn_printf_asterisk_missing_arg)
1581          << k << getFormatSpecifierRange(startSpecifier, specifierLen);
1582        // Don't do any more checking.  We will just emit
1583        // spurious errors.
1584        return false;
1585      }
1586
1587      // Type check the data argument.  It should be an 'int'.
1588      // Although not in conformance with C99, we also allow the argument to be
1589      // an 'unsigned int' as that is a reasonably safe case.  GCC also
1590      // doesn't emit a warning for that case.
1591      CoveredArgs.set(argIndex);
1592      const Expr *Arg = getDataArg(argIndex);
1593      QualType T = Arg->getType();
1594
1595      const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context);
1596      assert(ATR.isValid());
1597
1598      if (!ATR.matchesType(S.Context, T)) {
1599        S.Diag(getLocationOfByte(Amt.getStart()),
1600               diag::warn_printf_asterisk_wrong_type)
1601          << k
1602          << ATR.getRepresentativeType(S.Context) << T
1603          << getFormatSpecifierRange(startSpecifier, specifierLen)
1604          << Arg->getSourceRange();
1605        // Don't do any more checking.  We will just emit
1606        // spurious errors.
1607        return false;
1608      }
1609    }
1610  }
1611  return true;
1612}
1613
1614bool
1615CheckPrintfHandler::HandleFormatSpecifier(const analyze_printf::FormatSpecifier
1616                                            &FS,
1617                                          const char *startSpecifier,
1618                                          unsigned specifierLen) {
1619
1620  using namespace analyze_printf;
1621  const ConversionSpecifier &CS = FS.getConversionSpecifier();
1622
1623  if (atFirstArg) {
1624    atFirstArg = false;
1625    usesPositionalArgs = FS.usesPositionalArg();
1626  }
1627  else if (usesPositionalArgs != FS.usesPositionalArg()) {
1628    // Cannot mix-and-match positional and non-positional arguments.
1629    S.Diag(getLocationOfByte(CS.getStart()),
1630           diag::warn_printf_mix_positional_nonpositional_args)
1631      << getFormatSpecifierRange(startSpecifier, specifierLen);
1632    return false;
1633  }
1634
1635  // First check if the field width, precision, and conversion specifier
1636  // have matching data arguments.
1637  if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
1638                    startSpecifier, specifierLen)) {
1639    return false;
1640  }
1641
1642  if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
1643                    startSpecifier, specifierLen)) {
1644    return false;
1645  }
1646
1647  if (!CS.consumesDataArgument()) {
1648    // FIXME: Technically specifying a precision or field width here
1649    // makes no sense.  Worth issuing a warning at some point.
1650    return true;
1651  }
1652
1653  // Consume the argument.
1654  unsigned argIndex = FS.getArgIndex();
1655  if (argIndex < NumDataArgs) {
1656    // The check to see if the argIndex is valid will come later.
1657    // We set the bit here because we may exit early from this
1658    // function if we encounter some other error.
1659    CoveredArgs.set(argIndex);
1660  }
1661
1662  // Check for using an Objective-C specific conversion specifier
1663  // in a non-ObjC literal.
1664  if (!IsObjCLiteral && CS.isObjCArg()) {
1665    return HandleInvalidConversionSpecifier(FS, startSpecifier, specifierLen);
1666  }
1667
1668  // Are we using '%n'?  Issue a warning about this being
1669  // a possible security issue.
1670  if (CS.getKind() == ConversionSpecifier::OutIntPtrArg) {
1671    S.Diag(getLocationOfByte(CS.getStart()), diag::warn_printf_write_back)
1672      << getFormatSpecifierRange(startSpecifier, specifierLen);
1673    // Continue checking the other format specifiers.
1674    return true;
1675  }
1676
1677  if (CS.getKind() == ConversionSpecifier::VoidPtrArg) {
1678    if (FS.getPrecision().getHowSpecified() != OptionalAmount::NotSpecified)
1679      S.Diag(getLocationOfByte(CS.getStart()),
1680             diag::warn_printf_nonsensical_precision)
1681        << CS.getCharacters()
1682        << getFormatSpecifierRange(startSpecifier, specifierLen);
1683  }
1684  if (CS.getKind() == ConversionSpecifier::VoidPtrArg ||
1685      CS.getKind() == ConversionSpecifier::CStrArg) {
1686    // FIXME: Instead of using "0", "+", etc., eventually get them from
1687    // the FormatSpecifier.
1688    if (FS.hasLeadingZeros())
1689      HandleFlags(FS, "0", CS.getCharacters(), startSpecifier, specifierLen);
1690    if (FS.hasPlusPrefix())
1691      HandleFlags(FS, "+", CS.getCharacters(), startSpecifier, specifierLen);
1692    if (FS.hasSpacePrefix())
1693      HandleFlags(FS, " ", CS.getCharacters(), startSpecifier, specifierLen);
1694  }
1695
1696  // The remaining checks depend on the data arguments.
1697  if (HasVAListArg)
1698    return true;
1699
1700  if (argIndex >= NumDataArgs) {
1701    if (FS.usesPositionalArg())  {
1702      S.Diag(getLocationOfByte(CS.getStart()),
1703             diag::warn_printf_positional_arg_exceeds_data_args)
1704        << (argIndex+1) << NumDataArgs
1705        << getFormatSpecifierRange(startSpecifier, specifierLen);
1706    }
1707    else {
1708      S.Diag(getLocationOfByte(CS.getStart()),
1709             diag::warn_printf_insufficient_data_args)
1710        << getFormatSpecifierRange(startSpecifier, specifierLen);
1711    }
1712
1713    // Don't do any more checking.
1714    return false;
1715  }
1716
1717  // Now type check the data expression that matches the
1718  // format specifier.
1719  const Expr *Ex = getDataArg(argIndex);
1720  const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context);
1721  if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
1722    // Check if we didn't match because of an implicit cast from a 'char'
1723    // or 'short' to an 'int'.  This is done because printf is a varargs
1724    // function.
1725    if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex))
1726      if (ICE->getType() == S.Context.IntTy)
1727        if (ATR.matchesType(S.Context, ICE->getSubExpr()->getType()))
1728          return true;
1729
1730    // We may be able to offer a FixItHint if it is a supported type.
1731    FormatSpecifier fixedFS = FS;
1732    bool success = fixedFS.fixType(Ex->getType());
1733
1734    if (success) {
1735      // Get the fix string from the fixed format specifier
1736      llvm::SmallString<128> buf;
1737      llvm::raw_svector_ostream os(buf);
1738      fixedFS.toString(os);
1739
1740      S.Diag(getLocationOfByte(CS.getStart()),
1741          diag::warn_printf_conversion_argument_type_mismatch)
1742        << ATR.getRepresentativeType(S.Context) << Ex->getType()
1743        << getFormatSpecifierRange(startSpecifier, specifierLen)
1744        << Ex->getSourceRange()
1745        << FixItHint::CreateReplacement(
1746            getFormatSpecifierRange(startSpecifier, specifierLen),
1747            os.str());
1748    }
1749    else {
1750      S.Diag(getLocationOfByte(CS.getStart()),
1751             diag::warn_printf_conversion_argument_type_mismatch)
1752        << ATR.getRepresentativeType(S.Context) << Ex->getType()
1753        << getFormatSpecifierRange(startSpecifier, specifierLen)
1754        << Ex->getSourceRange();
1755    }
1756  }
1757
1758  return true;
1759}
1760
1761void CheckPrintfHandler::DoneProcessing() {
1762  // Does the number of data arguments exceed the number of
1763  // format conversions in the format string?
1764  if (!HasVAListArg) {
1765    // Find any arguments that weren't covered.
1766    CoveredArgs.flip();
1767    signed notCoveredArg = CoveredArgs.find_first();
1768    if (notCoveredArg >= 0) {
1769      assert((unsigned)notCoveredArg < NumDataArgs);
1770      S.Diag(getDataArg((unsigned) notCoveredArg)->getLocStart(),
1771             diag::warn_printf_data_arg_not_used)
1772        << getFormatStringRange();
1773    }
1774  }
1775}
1776
1777void Sema::CheckPrintfString(const StringLiteral *FExpr,
1778                             const Expr *OrigFormatExpr,
1779                             const CallExpr *TheCall, bool HasVAListArg,
1780                             unsigned format_idx, unsigned firstDataArg) {
1781
1782  // CHECK: is the format string a wide literal?
1783  if (FExpr->isWide()) {
1784    Diag(FExpr->getLocStart(),
1785         diag::warn_printf_format_string_is_wide_literal)
1786    << OrigFormatExpr->getSourceRange();
1787    return;
1788  }
1789
1790  // Str - The format string.  NOTE: this is NOT null-terminated!
1791  const char *Str = FExpr->getStrData();
1792
1793  // CHECK: empty format string?
1794  unsigned StrLen = FExpr->getByteLength();
1795
1796  if (StrLen == 0) {
1797    Diag(FExpr->getLocStart(), diag::warn_printf_empty_format_string)
1798    << OrigFormatExpr->getSourceRange();
1799    return;
1800  }
1801
1802  CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
1803                       TheCall->getNumArgs() - firstDataArg,
1804                       isa<ObjCStringLiteral>(OrigFormatExpr), Str,
1805                       HasVAListArg, TheCall, format_idx);
1806
1807  if (!analyze_printf::ParseFormatString(H, Str, Str + StrLen))
1808    H.DoneProcessing();
1809}
1810
1811//===--- CHECK: Return Address of Stack Variable --------------------------===//
1812
1813static DeclRefExpr* EvalVal(Expr *E);
1814static DeclRefExpr* EvalAddr(Expr* E);
1815
1816/// CheckReturnStackAddr - Check if a return statement returns the address
1817///   of a stack variable.
1818void
1819Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
1820                           SourceLocation ReturnLoc) {
1821
1822  // Perform checking for returned stack addresses.
1823  if (lhsType->isPointerType() || lhsType->isBlockPointerType()) {
1824    if (DeclRefExpr *DR = EvalAddr(RetValExp))
1825      Diag(DR->getLocStart(), diag::warn_ret_stack_addr)
1826       << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
1827
1828    // Skip over implicit cast expressions when checking for block expressions.
1829    RetValExp = RetValExp->IgnoreParenCasts();
1830
1831    if (BlockExpr *C = dyn_cast<BlockExpr>(RetValExp))
1832      if (C->hasBlockDeclRefExprs())
1833        Diag(C->getLocStart(), diag::err_ret_local_block)
1834          << C->getSourceRange();
1835
1836    if (AddrLabelExpr *ALE = dyn_cast<AddrLabelExpr>(RetValExp))
1837      Diag(ALE->getLocStart(), diag::warn_ret_addr_label)
1838        << ALE->getSourceRange();
1839
1840  } else if (lhsType->isReferenceType()) {
1841    // Perform checking for stack values returned by reference.
1842    // Check for a reference to the stack
1843    if (DeclRefExpr *DR = EvalVal(RetValExp))
1844      Diag(DR->getLocStart(), diag::warn_ret_stack_ref)
1845        << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
1846  }
1847}
1848
1849/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
1850///  check if the expression in a return statement evaluates to an address
1851///  to a location on the stack.  The recursion is used to traverse the
1852///  AST of the return expression, with recursion backtracking when we
1853///  encounter a subexpression that (1) clearly does not lead to the address
1854///  of a stack variable or (2) is something we cannot determine leads to
1855///  the address of a stack variable based on such local checking.
1856///
1857///  EvalAddr processes expressions that are pointers that are used as
1858///  references (and not L-values).  EvalVal handles all other values.
1859///  At the base case of the recursion is a check for a DeclRefExpr* in
1860///  the refers to a stack variable.
1861///
1862///  This implementation handles:
1863///
1864///   * pointer-to-pointer casts
1865///   * implicit conversions from array references to pointers
1866///   * taking the address of fields
1867///   * arbitrary interplay between "&" and "*" operators
1868///   * pointer arithmetic from an address of a stack variable
1869///   * taking the address of an array element where the array is on the stack
1870static DeclRefExpr* EvalAddr(Expr *E) {
1871  // We should only be called for evaluating pointer expressions.
1872  assert((E->getType()->isAnyPointerType() ||
1873          E->getType()->isBlockPointerType() ||
1874          E->getType()->isObjCQualifiedIdType()) &&
1875         "EvalAddr only works on pointers");
1876
1877  // Our "symbolic interpreter" is just a dispatch off the currently
1878  // viewed AST node.  We then recursively traverse the AST by calling
1879  // EvalAddr and EvalVal appropriately.
1880  switch (E->getStmtClass()) {
1881  case Stmt::ParenExprClass:
1882    // Ignore parentheses.
1883    return EvalAddr(cast<ParenExpr>(E)->getSubExpr());
1884
1885  case Stmt::UnaryOperatorClass: {
1886    // The only unary operator that make sense to handle here
1887    // is AddrOf.  All others don't make sense as pointers.
1888    UnaryOperator *U = cast<UnaryOperator>(E);
1889
1890    if (U->getOpcode() == UnaryOperator::AddrOf)
1891      return EvalVal(U->getSubExpr());
1892    else
1893      return NULL;
1894  }
1895
1896  case Stmt::BinaryOperatorClass: {
1897    // Handle pointer arithmetic.  All other binary operators are not valid
1898    // in this context.
1899    BinaryOperator *B = cast<BinaryOperator>(E);
1900    BinaryOperator::Opcode op = B->getOpcode();
1901
1902    if (op != BinaryOperator::Add && op != BinaryOperator::Sub)
1903      return NULL;
1904
1905    Expr *Base = B->getLHS();
1906
1907    // Determine which argument is the real pointer base.  It could be
1908    // the RHS argument instead of the LHS.
1909    if (!Base->getType()->isPointerType()) Base = B->getRHS();
1910
1911    assert (Base->getType()->isPointerType());
1912    return EvalAddr(Base);
1913  }
1914
1915  // For conditional operators we need to see if either the LHS or RHS are
1916  // valid DeclRefExpr*s.  If one of them is valid, we return it.
1917  case Stmt::ConditionalOperatorClass: {
1918    ConditionalOperator *C = cast<ConditionalOperator>(E);
1919
1920    // Handle the GNU extension for missing LHS.
1921    if (Expr *lhsExpr = C->getLHS())
1922      if (DeclRefExpr* LHS = EvalAddr(lhsExpr))
1923        return LHS;
1924
1925     return EvalAddr(C->getRHS());
1926  }
1927
1928  // For casts, we need to handle conversions from arrays to
1929  // pointer values, and pointer-to-pointer conversions.
1930  case Stmt::ImplicitCastExprClass:
1931  case Stmt::CStyleCastExprClass:
1932  case Stmt::CXXFunctionalCastExprClass: {
1933    Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
1934    QualType T = SubExpr->getType();
1935
1936    if (SubExpr->getType()->isPointerType() ||
1937        SubExpr->getType()->isBlockPointerType() ||
1938        SubExpr->getType()->isObjCQualifiedIdType())
1939      return EvalAddr(SubExpr);
1940    else if (T->isArrayType())
1941      return EvalVal(SubExpr);
1942    else
1943      return 0;
1944  }
1945
1946  // C++ casts.  For dynamic casts, static casts, and const casts, we
1947  // are always converting from a pointer-to-pointer, so we just blow
1948  // through the cast.  In the case the dynamic cast doesn't fail (and
1949  // return NULL), we take the conservative route and report cases
1950  // where we return the address of a stack variable.  For Reinterpre
1951  // FIXME: The comment about is wrong; we're not always converting
1952  // from pointer to pointer. I'm guessing that this code should also
1953  // handle references to objects.
1954  case Stmt::CXXStaticCastExprClass:
1955  case Stmt::CXXDynamicCastExprClass:
1956  case Stmt::CXXConstCastExprClass:
1957  case Stmt::CXXReinterpretCastExprClass: {
1958      Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
1959      if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
1960        return EvalAddr(S);
1961      else
1962        return NULL;
1963  }
1964
1965  // Everything else: we simply don't reason about them.
1966  default:
1967    return NULL;
1968  }
1969}
1970
1971
1972///  EvalVal - This function is complements EvalAddr in the mutual recursion.
1973///   See the comments for EvalAddr for more details.
1974static DeclRefExpr* EvalVal(Expr *E) {
1975
1976  // We should only be called for evaluating non-pointer expressions, or
1977  // expressions with a pointer type that are not used as references but instead
1978  // are l-values (e.g., DeclRefExpr with a pointer type).
1979
1980  // Our "symbolic interpreter" is just a dispatch off the currently
1981  // viewed AST node.  We then recursively traverse the AST by calling
1982  // EvalAddr and EvalVal appropriately.
1983  switch (E->getStmtClass()) {
1984  case Stmt::DeclRefExprClass: {
1985    // DeclRefExpr: the base case.  When we hit a DeclRefExpr we are looking
1986    //  at code that refers to a variable's name.  We check if it has local
1987    //  storage within the function, and if so, return the expression.
1988    DeclRefExpr *DR = cast<DeclRefExpr>(E);
1989
1990    if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
1991      if (V->hasLocalStorage() && !V->getType()->isReferenceType()) return DR;
1992
1993    return NULL;
1994  }
1995
1996  case Stmt::ParenExprClass:
1997    // Ignore parentheses.
1998    return EvalVal(cast<ParenExpr>(E)->getSubExpr());
1999
2000  case Stmt::UnaryOperatorClass: {
2001    // The only unary operator that make sense to handle here
2002    // is Deref.  All others don't resolve to a "name."  This includes
2003    // handling all sorts of rvalues passed to a unary operator.
2004    UnaryOperator *U = cast<UnaryOperator>(E);
2005
2006    if (U->getOpcode() == UnaryOperator::Deref)
2007      return EvalAddr(U->getSubExpr());
2008
2009    return NULL;
2010  }
2011
2012  case Stmt::ArraySubscriptExprClass: {
2013    // Array subscripts are potential references to data on the stack.  We
2014    // retrieve the DeclRefExpr* for the array variable if it indeed
2015    // has local storage.
2016    return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase());
2017  }
2018
2019  case Stmt::ConditionalOperatorClass: {
2020    // For conditional operators we need to see if either the LHS or RHS are
2021    // non-NULL DeclRefExpr's.  If one is non-NULL, we return it.
2022    ConditionalOperator *C = cast<ConditionalOperator>(E);
2023
2024    // Handle the GNU extension for missing LHS.
2025    if (Expr *lhsExpr = C->getLHS())
2026      if (DeclRefExpr *LHS = EvalVal(lhsExpr))
2027        return LHS;
2028
2029    return EvalVal(C->getRHS());
2030  }
2031
2032  // Accesses to members are potential references to data on the stack.
2033  case Stmt::MemberExprClass: {
2034    MemberExpr *M = cast<MemberExpr>(E);
2035
2036    // Check for indirect access.  We only want direct field accesses.
2037    if (!M->isArrow())
2038      return EvalVal(M->getBase());
2039    else
2040      return NULL;
2041  }
2042
2043  // Everything else: we simply don't reason about them.
2044  default:
2045    return NULL;
2046  }
2047}
2048
2049//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
2050
2051/// Check for comparisons of floating point operands using != and ==.
2052/// Issue a warning if these are no self-comparisons, as they are not likely
2053/// to do what the programmer intended.
2054void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
2055  bool EmitWarning = true;
2056
2057  Expr* LeftExprSansParen = lex->IgnoreParens();
2058  Expr* RightExprSansParen = rex->IgnoreParens();
2059
2060  // Special case: check for x == x (which is OK).
2061  // Do not emit warnings for such cases.
2062  if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
2063    if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
2064      if (DRL->getDecl() == DRR->getDecl())
2065        EmitWarning = false;
2066
2067
2068  // Special case: check for comparisons against literals that can be exactly
2069  //  represented by APFloat.  In such cases, do not emit a warning.  This
2070  //  is a heuristic: often comparison against such literals are used to
2071  //  detect if a value in a variable has not changed.  This clearly can
2072  //  lead to false negatives.
2073  if (EmitWarning) {
2074    if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
2075      if (FLL->isExact())
2076        EmitWarning = false;
2077    } else
2078      if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
2079        if (FLR->isExact())
2080          EmitWarning = false;
2081    }
2082  }
2083
2084  // Check for comparisons with builtin types.
2085  if (EmitWarning)
2086    if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
2087      if (CL->isBuiltinCall(Context))
2088        EmitWarning = false;
2089
2090  if (EmitWarning)
2091    if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
2092      if (CR->isBuiltinCall(Context))
2093        EmitWarning = false;
2094
2095  // Emit the diagnostic.
2096  if (EmitWarning)
2097    Diag(loc, diag::warn_floatingpoint_eq)
2098      << lex->getSourceRange() << rex->getSourceRange();
2099}
2100
2101//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
2102//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
2103
2104namespace {
2105
2106/// Structure recording the 'active' range of an integer-valued
2107/// expression.
2108struct IntRange {
2109  /// The number of bits active in the int.
2110  unsigned Width;
2111
2112  /// True if the int is known not to have negative values.
2113  bool NonNegative;
2114
2115  IntRange() {}
2116  IntRange(unsigned Width, bool NonNegative)
2117    : Width(Width), NonNegative(NonNegative)
2118  {}
2119
2120  // Returns the range of the bool type.
2121  static IntRange forBoolType() {
2122    return IntRange(1, true);
2123  }
2124
2125  // Returns the range of an integral type.
2126  static IntRange forType(ASTContext &C, QualType T) {
2127    return forCanonicalType(C, T->getCanonicalTypeInternal().getTypePtr());
2128  }
2129
2130  // Returns the range of an integeral type based on its canonical
2131  // representation.
2132  static IntRange forCanonicalType(ASTContext &C, const Type *T) {
2133    assert(T->isCanonicalUnqualified());
2134
2135    if (const VectorType *VT = dyn_cast<VectorType>(T))
2136      T = VT->getElementType().getTypePtr();
2137    if (const ComplexType *CT = dyn_cast<ComplexType>(T))
2138      T = CT->getElementType().getTypePtr();
2139
2140    if (const EnumType *ET = dyn_cast<EnumType>(T)) {
2141      EnumDecl *Enum = ET->getDecl();
2142      unsigned NumPositive = Enum->getNumPositiveBits();
2143      unsigned NumNegative = Enum->getNumNegativeBits();
2144
2145      return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
2146    }
2147
2148    const BuiltinType *BT = cast<BuiltinType>(T);
2149    assert(BT->isInteger());
2150
2151    return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
2152  }
2153
2154  // Returns the supremum of two ranges: i.e. their conservative merge.
2155  static IntRange join(IntRange L, IntRange R) {
2156    return IntRange(std::max(L.Width, R.Width),
2157                    L.NonNegative && R.NonNegative);
2158  }
2159
2160  // Returns the infinum of two ranges: i.e. their aggressive merge.
2161  static IntRange meet(IntRange L, IntRange R) {
2162    return IntRange(std::min(L.Width, R.Width),
2163                    L.NonNegative || R.NonNegative);
2164  }
2165};
2166
2167IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
2168  if (value.isSigned() && value.isNegative())
2169    return IntRange(value.getMinSignedBits(), false);
2170
2171  if (value.getBitWidth() > MaxWidth)
2172    value.trunc(MaxWidth);
2173
2174  // isNonNegative() just checks the sign bit without considering
2175  // signedness.
2176  return IntRange(value.getActiveBits(), true);
2177}
2178
2179IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
2180                       unsigned MaxWidth) {
2181  if (result.isInt())
2182    return GetValueRange(C, result.getInt(), MaxWidth);
2183
2184  if (result.isVector()) {
2185    IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
2186    for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
2187      IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
2188      R = IntRange::join(R, El);
2189    }
2190    return R;
2191  }
2192
2193  if (result.isComplexInt()) {
2194    IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
2195    IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
2196    return IntRange::join(R, I);
2197  }
2198
2199  // This can happen with lossless casts to intptr_t of "based" lvalues.
2200  // Assume it might use arbitrary bits.
2201  // FIXME: The only reason we need to pass the type in here is to get
2202  // the sign right on this one case.  It would be nice if APValue
2203  // preserved this.
2204  assert(result.isLValue());
2205  return IntRange(MaxWidth, Ty->isUnsignedIntegerType());
2206}
2207
2208/// Pseudo-evaluate the given integer expression, estimating the
2209/// range of values it might take.
2210///
2211/// \param MaxWidth - the width to which the value will be truncated
2212IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
2213  E = E->IgnoreParens();
2214
2215  // Try a full evaluation first.
2216  Expr::EvalResult result;
2217  if (E->Evaluate(result, C))
2218    return GetValueRange(C, result.Val, E->getType(), MaxWidth);
2219
2220  // I think we only want to look through implicit casts here; if the
2221  // user has an explicit widening cast, we should treat the value as
2222  // being of the new, wider type.
2223  if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
2224    if (CE->getCastKind() == CastExpr::CK_NoOp)
2225      return GetExprRange(C, CE->getSubExpr(), MaxWidth);
2226
2227    IntRange OutputTypeRange = IntRange::forType(C, CE->getType());
2228
2229    bool isIntegerCast = (CE->getCastKind() == CastExpr::CK_IntegralCast);
2230    if (!isIntegerCast && CE->getCastKind() == CastExpr::CK_Unknown)
2231      isIntegerCast = CE->getSubExpr()->getType()->isIntegerType();
2232
2233    // Assume that non-integer casts can span the full range of the type.
2234    if (!isIntegerCast)
2235      return OutputTypeRange;
2236
2237    IntRange SubRange
2238      = GetExprRange(C, CE->getSubExpr(),
2239                     std::min(MaxWidth, OutputTypeRange.Width));
2240
2241    // Bail out if the subexpr's range is as wide as the cast type.
2242    if (SubRange.Width >= OutputTypeRange.Width)
2243      return OutputTypeRange;
2244
2245    // Otherwise, we take the smaller width, and we're non-negative if
2246    // either the output type or the subexpr is.
2247    return IntRange(SubRange.Width,
2248                    SubRange.NonNegative || OutputTypeRange.NonNegative);
2249  }
2250
2251  if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2252    // If we can fold the condition, just take that operand.
2253    bool CondResult;
2254    if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
2255      return GetExprRange(C, CondResult ? CO->getTrueExpr()
2256                                        : CO->getFalseExpr(),
2257                          MaxWidth);
2258
2259    // Otherwise, conservatively merge.
2260    IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
2261    IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
2262    return IntRange::join(L, R);
2263  }
2264
2265  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2266    switch (BO->getOpcode()) {
2267
2268    // Boolean-valued operations are single-bit and positive.
2269    case BinaryOperator::LAnd:
2270    case BinaryOperator::LOr:
2271    case BinaryOperator::LT:
2272    case BinaryOperator::GT:
2273    case BinaryOperator::LE:
2274    case BinaryOperator::GE:
2275    case BinaryOperator::EQ:
2276    case BinaryOperator::NE:
2277      return IntRange::forBoolType();
2278
2279    // The type of these compound assignments is the type of the LHS,
2280    // so the RHS is not necessarily an integer.
2281    case BinaryOperator::MulAssign:
2282    case BinaryOperator::DivAssign:
2283    case BinaryOperator::RemAssign:
2284    case BinaryOperator::AddAssign:
2285    case BinaryOperator::SubAssign:
2286      return IntRange::forType(C, E->getType());
2287
2288    // Operations with opaque sources are black-listed.
2289    case BinaryOperator::PtrMemD:
2290    case BinaryOperator::PtrMemI:
2291      return IntRange::forType(C, E->getType());
2292
2293    // Bitwise-and uses the *infinum* of the two source ranges.
2294    case BinaryOperator::And:
2295    case BinaryOperator::AndAssign:
2296      return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
2297                            GetExprRange(C, BO->getRHS(), MaxWidth));
2298
2299    // Left shift gets black-listed based on a judgement call.
2300    case BinaryOperator::Shl:
2301      // ...except that we want to treat '1 << (blah)' as logically
2302      // positive.  It's an important idiom.
2303      if (IntegerLiteral *I
2304            = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
2305        if (I->getValue() == 1) {
2306          IntRange R = IntRange::forType(C, E->getType());
2307          return IntRange(R.Width, /*NonNegative*/ true);
2308        }
2309      }
2310      // fallthrough
2311
2312    case BinaryOperator::ShlAssign:
2313      return IntRange::forType(C, E->getType());
2314
2315    // Right shift by a constant can narrow its left argument.
2316    case BinaryOperator::Shr:
2317    case BinaryOperator::ShrAssign: {
2318      IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
2319
2320      // If the shift amount is a positive constant, drop the width by
2321      // that much.
2322      llvm::APSInt shift;
2323      if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
2324          shift.isNonNegative()) {
2325        unsigned zext = shift.getZExtValue();
2326        if (zext >= L.Width)
2327          L.Width = (L.NonNegative ? 0 : 1);
2328        else
2329          L.Width -= zext;
2330      }
2331
2332      return L;
2333    }
2334
2335    // Comma acts as its right operand.
2336    case BinaryOperator::Comma:
2337      return GetExprRange(C, BO->getRHS(), MaxWidth);
2338
2339    // Black-list pointer subtractions.
2340    case BinaryOperator::Sub:
2341      if (BO->getLHS()->getType()->isPointerType())
2342        return IntRange::forType(C, E->getType());
2343      // fallthrough
2344
2345    default:
2346      break;
2347    }
2348
2349    // Treat every other operator as if it were closed on the
2350    // narrowest type that encompasses both operands.
2351    IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
2352    IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
2353    return IntRange::join(L, R);
2354  }
2355
2356  if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
2357    switch (UO->getOpcode()) {
2358    // Boolean-valued operations are white-listed.
2359    case UnaryOperator::LNot:
2360      return IntRange::forBoolType();
2361
2362    // Operations with opaque sources are black-listed.
2363    case UnaryOperator::Deref:
2364    case UnaryOperator::AddrOf: // should be impossible
2365    case UnaryOperator::OffsetOf:
2366      return IntRange::forType(C, E->getType());
2367
2368    default:
2369      return GetExprRange(C, UO->getSubExpr(), MaxWidth);
2370    }
2371  }
2372
2373  if (dyn_cast<OffsetOfExpr>(E)) {
2374    IntRange::forType(C, E->getType());
2375  }
2376
2377  FieldDecl *BitField = E->getBitField();
2378  if (BitField) {
2379    llvm::APSInt BitWidthAP = BitField->getBitWidth()->EvaluateAsInt(C);
2380    unsigned BitWidth = BitWidthAP.getZExtValue();
2381
2382    return IntRange(BitWidth, BitField->getType()->isUnsignedIntegerType());
2383  }
2384
2385  return IntRange::forType(C, E->getType());
2386}
2387
2388IntRange GetExprRange(ASTContext &C, Expr *E) {
2389  return GetExprRange(C, E, C.getIntWidth(E->getType()));
2390}
2391
2392/// Checks whether the given value, which currently has the given
2393/// source semantics, has the same value when coerced through the
2394/// target semantics.
2395bool IsSameFloatAfterCast(const llvm::APFloat &value,
2396                          const llvm::fltSemantics &Src,
2397                          const llvm::fltSemantics &Tgt) {
2398  llvm::APFloat truncated = value;
2399
2400  bool ignored;
2401  truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
2402  truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
2403
2404  return truncated.bitwiseIsEqual(value);
2405}
2406
2407/// Checks whether the given value, which currently has the given
2408/// source semantics, has the same value when coerced through the
2409/// target semantics.
2410///
2411/// The value might be a vector of floats (or a complex number).
2412bool IsSameFloatAfterCast(const APValue &value,
2413                          const llvm::fltSemantics &Src,
2414                          const llvm::fltSemantics &Tgt) {
2415  if (value.isFloat())
2416    return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
2417
2418  if (value.isVector()) {
2419    for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
2420      if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
2421        return false;
2422    return true;
2423  }
2424
2425  assert(value.isComplexFloat());
2426  return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
2427          IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
2428}
2429
2430void AnalyzeImplicitConversions(Sema &S, Expr *E);
2431
2432bool IsZero(Sema &S, Expr *E) {
2433  llvm::APSInt Value;
2434  return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
2435}
2436
2437void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
2438  BinaryOperator::Opcode op = E->getOpcode();
2439  if (op == BinaryOperator::LT && IsZero(S, E->getRHS())) {
2440    S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
2441      << "< 0" << "false"
2442      << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
2443  } else if (op == BinaryOperator::GE && IsZero(S, E->getRHS())) {
2444    S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
2445      << ">= 0" << "true"
2446      << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
2447  } else if (op == BinaryOperator::GT && IsZero(S, E->getLHS())) {
2448    S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
2449      << "0 >" << "false"
2450      << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
2451  } else if (op == BinaryOperator::LE && IsZero(S, E->getLHS())) {
2452    S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
2453      << "0 <=" << "true"
2454      << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
2455  }
2456}
2457
2458/// Analyze the operands of the given comparison.  Implements the
2459/// fallback case from AnalyzeComparison.
2460void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
2461  AnalyzeImplicitConversions(S, E->getLHS());
2462  AnalyzeImplicitConversions(S, E->getRHS());
2463}
2464
2465/// \brief Implements -Wsign-compare.
2466///
2467/// \param lex the left-hand expression
2468/// \param rex the right-hand expression
2469/// \param OpLoc the location of the joining operator
2470/// \param BinOpc binary opcode or 0
2471void AnalyzeComparison(Sema &S, BinaryOperator *E) {
2472  // The type the comparison is being performed in.
2473  QualType T = E->getLHS()->getType();
2474  assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
2475         && "comparison with mismatched types");
2476
2477  // We don't do anything special if this isn't an unsigned integral
2478  // comparison:  we're only interested in integral comparisons, and
2479  // signed comparisons only happen in cases we don't care to warn about.
2480  if (!T->isUnsignedIntegerType())
2481    return AnalyzeImpConvsInComparison(S, E);
2482
2483  Expr *lex = E->getLHS()->IgnoreParenImpCasts();
2484  Expr *rex = E->getRHS()->IgnoreParenImpCasts();
2485
2486  // Check to see if one of the (unmodified) operands is of different
2487  // signedness.
2488  Expr *signedOperand, *unsignedOperand;
2489  if (lex->getType()->isSignedIntegerType()) {
2490    assert(!rex->getType()->isSignedIntegerType() &&
2491           "unsigned comparison between two signed integer expressions?");
2492    signedOperand = lex;
2493    unsignedOperand = rex;
2494  } else if (rex->getType()->isSignedIntegerType()) {
2495    signedOperand = rex;
2496    unsignedOperand = lex;
2497  } else {
2498    CheckTrivialUnsignedComparison(S, E);
2499    return AnalyzeImpConvsInComparison(S, E);
2500  }
2501
2502  // Otherwise, calculate the effective range of the signed operand.
2503  IntRange signedRange = GetExprRange(S.Context, signedOperand);
2504
2505  // Go ahead and analyze implicit conversions in the operands.  Note
2506  // that we skip the implicit conversions on both sides.
2507  AnalyzeImplicitConversions(S, lex);
2508  AnalyzeImplicitConversions(S, rex);
2509
2510  // If the signed range is non-negative, -Wsign-compare won't fire,
2511  // but we should still check for comparisons which are always true
2512  // or false.
2513  if (signedRange.NonNegative)
2514    return CheckTrivialUnsignedComparison(S, E);
2515
2516  // For (in)equality comparisons, if the unsigned operand is a
2517  // constant which cannot collide with a overflowed signed operand,
2518  // then reinterpreting the signed operand as unsigned will not
2519  // change the result of the comparison.
2520  if (E->isEqualityOp()) {
2521    unsigned comparisonWidth = S.Context.getIntWidth(T);
2522    IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
2523
2524    // We should never be unable to prove that the unsigned operand is
2525    // non-negative.
2526    assert(unsignedRange.NonNegative && "unsigned range includes negative?");
2527
2528    if (unsignedRange.Width < comparisonWidth)
2529      return;
2530  }
2531
2532  S.Diag(E->getOperatorLoc(), diag::warn_mixed_sign_comparison)
2533    << lex->getType() << rex->getType()
2534    << lex->getSourceRange() << rex->getSourceRange();
2535}
2536
2537/// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
2538void DiagnoseImpCast(Sema &S, Expr *E, QualType T, unsigned diag) {
2539  S.Diag(E->getExprLoc(), diag) << E->getType() << T << E->getSourceRange();
2540}
2541
2542void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
2543                             bool *ICContext = 0) {
2544  if (E->isTypeDependent() || E->isValueDependent()) return;
2545
2546  const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
2547  const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
2548  if (Source == Target) return;
2549  if (Target->isDependentType()) return;
2550
2551  // Never diagnose implicit casts to bool.
2552  if (Target->isSpecificBuiltinType(BuiltinType::Bool))
2553    return;
2554
2555  // Strip vector types.
2556  if (isa<VectorType>(Source)) {
2557    if (!isa<VectorType>(Target))
2558      return DiagnoseImpCast(S, E, T, diag::warn_impcast_vector_scalar);
2559
2560    Source = cast<VectorType>(Source)->getElementType().getTypePtr();
2561    Target = cast<VectorType>(Target)->getElementType().getTypePtr();
2562  }
2563
2564  // Strip complex types.
2565  if (isa<ComplexType>(Source)) {
2566    if (!isa<ComplexType>(Target))
2567      return DiagnoseImpCast(S, E, T, diag::warn_impcast_complex_scalar);
2568
2569    Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
2570    Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
2571  }
2572
2573  const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
2574  const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
2575
2576  // If the source is floating point...
2577  if (SourceBT && SourceBT->isFloatingPoint()) {
2578    // ...and the target is floating point...
2579    if (TargetBT && TargetBT->isFloatingPoint()) {
2580      // ...then warn if we're dropping FP rank.
2581
2582      // Builtin FP kinds are ordered by increasing FP rank.
2583      if (SourceBT->getKind() > TargetBT->getKind()) {
2584        // Don't warn about float constants that are precisely
2585        // representable in the target type.
2586        Expr::EvalResult result;
2587        if (E->Evaluate(result, S.Context)) {
2588          // Value might be a float, a float vector, or a float complex.
2589          if (IsSameFloatAfterCast(result.Val,
2590                   S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
2591                   S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
2592            return;
2593        }
2594
2595        DiagnoseImpCast(S, E, T, diag::warn_impcast_float_precision);
2596      }
2597      return;
2598    }
2599
2600    // If the target is integral, always warn.
2601    if ((TargetBT && TargetBT->isInteger()))
2602      // TODO: don't warn for integer values?
2603      DiagnoseImpCast(S, E, T, diag::warn_impcast_float_integer);
2604
2605    return;
2606  }
2607
2608  if (!Source->isIntegerType() || !Target->isIntegerType())
2609    return;
2610
2611  IntRange SourceRange = GetExprRange(S.Context, E);
2612  IntRange TargetRange = IntRange::forCanonicalType(S.Context, Target);
2613
2614  if (SourceRange.Width > TargetRange.Width) {
2615    // People want to build with -Wshorten-64-to-32 and not -Wconversion
2616    // and by god we'll let them.
2617    if (SourceRange.Width == 64 && TargetRange.Width == 32)
2618      return DiagnoseImpCast(S, E, T, diag::warn_impcast_integer_64_32);
2619    return DiagnoseImpCast(S, E, T, diag::warn_impcast_integer_precision);
2620  }
2621
2622  if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
2623      (!TargetRange.NonNegative && SourceRange.NonNegative &&
2624       SourceRange.Width == TargetRange.Width)) {
2625    unsigned DiagID = diag::warn_impcast_integer_sign;
2626
2627    // Traditionally, gcc has warned about this under -Wsign-compare.
2628    // We also want to warn about it in -Wconversion.
2629    // So if -Wconversion is off, use a completely identical diagnostic
2630    // in the sign-compare group.
2631    // The conditional-checking code will
2632    if (ICContext) {
2633      DiagID = diag::warn_impcast_integer_sign_conditional;
2634      *ICContext = true;
2635    }
2636
2637    return DiagnoseImpCast(S, E, T, DiagID);
2638  }
2639
2640  return;
2641}
2642
2643void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T);
2644
2645void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
2646                             bool &ICContext) {
2647  E = E->IgnoreParenImpCasts();
2648
2649  if (isa<ConditionalOperator>(E))
2650    return CheckConditionalOperator(S, cast<ConditionalOperator>(E), T);
2651
2652  AnalyzeImplicitConversions(S, E);
2653  if (E->getType() != T)
2654    return CheckImplicitConversion(S, E, T, &ICContext);
2655  return;
2656}
2657
2658void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T) {
2659  AnalyzeImplicitConversions(S, E->getCond());
2660
2661  bool Suspicious = false;
2662  CheckConditionalOperand(S, E->getTrueExpr(), T, Suspicious);
2663  CheckConditionalOperand(S, E->getFalseExpr(), T, Suspicious);
2664
2665  // If -Wconversion would have warned about either of the candidates
2666  // for a signedness conversion to the context type...
2667  if (!Suspicious) return;
2668
2669  // ...but it's currently ignored...
2670  if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional))
2671    return;
2672
2673  // ...and -Wsign-compare isn't...
2674  if (!S.Diags.getDiagnosticLevel(diag::warn_mixed_sign_conditional))
2675    return;
2676
2677  // ...then check whether it would have warned about either of the
2678  // candidates for a signedness conversion to the condition type.
2679  if (E->getType() != T) {
2680    Suspicious = false;
2681    CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
2682                            E->getType(), &Suspicious);
2683    if (!Suspicious)
2684      CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
2685                              E->getType(), &Suspicious);
2686    if (!Suspicious)
2687      return;
2688  }
2689
2690  // If so, emit a diagnostic under -Wsign-compare.
2691  Expr *lex = E->getTrueExpr()->IgnoreParenImpCasts();
2692  Expr *rex = E->getFalseExpr()->IgnoreParenImpCasts();
2693  S.Diag(E->getQuestionLoc(), diag::warn_mixed_sign_conditional)
2694    << lex->getType() << rex->getType()
2695    << lex->getSourceRange() << rex->getSourceRange();
2696}
2697
2698/// AnalyzeImplicitConversions - Find and report any interesting
2699/// implicit conversions in the given expression.  There are a couple
2700/// of competing diagnostics here, -Wconversion and -Wsign-compare.
2701void AnalyzeImplicitConversions(Sema &S, Expr *OrigE) {
2702  QualType T = OrigE->getType();
2703  Expr *E = OrigE->IgnoreParenImpCasts();
2704
2705  // For conditional operators, we analyze the arguments as if they
2706  // were being fed directly into the output.
2707  if (isa<ConditionalOperator>(E)) {
2708    ConditionalOperator *CO = cast<ConditionalOperator>(E);
2709    CheckConditionalOperator(S, CO, T);
2710    return;
2711  }
2712
2713  // Go ahead and check any implicit conversions we might have skipped.
2714  // The non-canonical typecheck is just an optimization;
2715  // CheckImplicitConversion will filter out dead implicit conversions.
2716  if (E->getType() != T)
2717    CheckImplicitConversion(S, E, T);
2718
2719  // Now continue drilling into this expression.
2720
2721  // Skip past explicit casts.
2722  if (isa<ExplicitCastExpr>(E)) {
2723    E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
2724    return AnalyzeImplicitConversions(S, E);
2725  }
2726
2727  // Do a somewhat different check with comparison operators.
2728  if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isComparisonOp())
2729    return AnalyzeComparison(S, cast<BinaryOperator>(E));
2730
2731  // These break the otherwise-useful invariant below.  Fortunately,
2732  // we don't really need to recurse into them, because any internal
2733  // expressions should have been analyzed already when they were
2734  // built into statements.
2735  if (isa<StmtExpr>(E)) return;
2736
2737  // Don't descend into unevaluated contexts.
2738  if (isa<SizeOfAlignOfExpr>(E)) return;
2739
2740  // Now just recurse over the expression's children.
2741  for (Stmt::child_iterator I = E->child_begin(), IE = E->child_end();
2742         I != IE; ++I)
2743    AnalyzeImplicitConversions(S, cast<Expr>(*I));
2744}
2745
2746} // end anonymous namespace
2747
2748/// Diagnoses "dangerous" implicit conversions within the given
2749/// expression (which is a full expression).  Implements -Wconversion
2750/// and -Wsign-compare.
2751void Sema::CheckImplicitConversions(Expr *E) {
2752  // Don't diagnose in unevaluated contexts.
2753  if (ExprEvalContexts.back().Context == Sema::Unevaluated)
2754    return;
2755
2756  // Don't diagnose for value- or type-dependent expressions.
2757  if (E->isTypeDependent() || E->isValueDependent())
2758    return;
2759
2760  AnalyzeImplicitConversions(*this, E);
2761}
2762
2763/// CheckParmsForFunctionDef - Check that the parameters of the given
2764/// function are appropriate for the definition of a function. This
2765/// takes care of any checks that cannot be performed on the
2766/// declaration itself, e.g., that the types of each of the function
2767/// parameters are complete.
2768bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
2769  bool HasInvalidParm = false;
2770  for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
2771    ParmVarDecl *Param = FD->getParamDecl(p);
2772
2773    // C99 6.7.5.3p4: the parameters in a parameter type list in a
2774    // function declarator that is part of a function definition of
2775    // that function shall not have incomplete type.
2776    //
2777    // This is also C++ [dcl.fct]p6.
2778    if (!Param->isInvalidDecl() &&
2779        RequireCompleteType(Param->getLocation(), Param->getType(),
2780                               diag::err_typecheck_decl_incomplete_type)) {
2781      Param->setInvalidDecl();
2782      HasInvalidParm = true;
2783    }
2784
2785    // C99 6.9.1p5: If the declarator includes a parameter type list, the
2786    // declaration of each parameter shall include an identifier.
2787    if (Param->getIdentifier() == 0 &&
2788        !Param->isImplicit() &&
2789        !getLangOptions().CPlusPlus)
2790      Diag(Param->getLocation(), diag::err_parameter_name_omitted);
2791
2792    // C99 6.7.5.3p12:
2793    //   If the function declarator is not part of a definition of that
2794    //   function, parameters may have incomplete type and may use the [*]
2795    //   notation in their sequences of declarator specifiers to specify
2796    //   variable length array types.
2797    QualType PType = Param->getOriginalType();
2798    if (const ArrayType *AT = Context.getAsArrayType(PType)) {
2799      if (AT->getSizeModifier() == ArrayType::Star) {
2800        // FIXME: This diagnosic should point the the '[*]' if source-location
2801        // information is added for it.
2802        Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
2803      }
2804    }
2805  }
2806
2807  return HasInvalidParm;
2808}
2809